问:
Pass argument to pub function from React sub in Meteor?
I am publishing all my comments collection with this:

```<code>Meteor.publish('comments', function() {
  return Comments.find(
    {},
    { fields: { date: 1, body: 1, user: 1, attachedTo: 1, attachedToID: 1 } },
  );
});
</code>```

And subscribing in a React component with this:

```<code>export default withTracker(() => {
  let commentsSub = Meteor.subscribe('comments');
  return {
    comments: Comments.find({}).fetch(),
  };
})(MyReactComponent);
</code>```

So far this works but now I want to refine what comments are sent. The attachedTo field for comments can be either 'profile' or 'homepage'. Ive modified my pub function to take an input:

```<code>Meteor.publish('comments', function(attachedTo) {
  return Comments.find(
    { attachedTo: attachedTo },
    { fields: { date: 1, body: 1, user: 1, attachedTo: 1, attachedToID: 1 } },
  );
});
</code>```

But I cant see how to pass this parameter from my React component:

```<code>export default withTracker(() => {
  let commentsSub = Meteor.subscribe('comments');
  return {
    comments: Comments.find({ attachedTo: 'group' }).fetch(),
  };
})(MyReactComponent);
</code>```

答:
In your current implementation, attachTo in the publish function will be undefined since you are not passing it any argument.

Subscriptions:

```<code>...
let commentsSub = Meteor.subscribe('comments','group'); // pass the value to the publish function.
...
</code>```

You are going to have to pass 'group' as the argument to the publish function.

Body:
I am publishing all my comments collection with this:

Meteor.publish('comments', function() {
  return Comments.find(
    {},
    { fields: { date: 1, body: 1, user: 1, attachedTo: 1, attachedToID: 1 } },
  );
});

And subscribing in a React component with this:

export default withTracker(() => {
  let commentsSub = Meteor.subscribe('comments');
  return {
    comments: Comments.find({}).fetch(),
  };
})(MyReactComponent);

So far this works but now I want to refine what comments are sent. The attachedTo field for comments can be either 'profile' or 'homepage'. Ive modified my pub function to take an input:

Meteor.publish('comments', function(attachedTo) {
  return Comments.find(
    { attachedTo: attachedTo },
    { fields: { date: 1, body: 1, user: 1, attachedTo: 1, attachedToID: 1 } },
  );
});

But I cant see how to pass this parameter from my React component:

export default withTracker(() => {
  let commentsSub = Meteor.subscribe('comments');
  return {
    comments: Comments.find({ attachedTo: 'group' }).fetch(),
  };
})(MyReactComponent);

Body:
In your current implementation, attachTo in the publish function will be undefined since you are not passing it any argument.

Subscriptions:

...
let commentsSub = Meteor.subscribe('comments','group'); // pass the value to the publish function.
...

You are going to have to pass 'group' as the argument to the publish function.


来源: stackexchange

问:
Spring Rest: Obtain the host base URL before the first call
I've developed a small REST API that runs inside a Spring container on a Tomcat server. As part of my boot sequence I need to be able to dump the base URL to a log file as:

```<code>String myUrl = ...
LOGGER.info("My URL is {}", myUrl);
</code>```

Which will display

```<code>My URL is http://myHostname:8080/myContext/url-pattern
</code>```

This will happen BEFORE the first call to the API. Once the application has started I can check the logs and use curl or wget to check that the app is responding.

All the solutions I've seen depend on HttpServletRequest, but this requires a call to the REST interface

Ideally I'd like to grab the complete pattern from a Spring object injected into my class, however I don't mind constructing the information from different sources if no such object exists.

So far I've read:

myHostname - InetAddress.getLocalHost().getHostName();

myContext - servletContext.getContextPath()

I've still got to get the port and the url-pattern (as defined in the web.xml) from somewhere.

Note: I understand that when I put my host is behind a load balancer then the domain of my REST API wont match myHostname and that's OK.

答:
If you are using WebApplicationInitializer instead of web.xml then, you can get hold of context object in onStartup method.

```<code>public class WebMVCApplicationInitializer implements
  WebApplicationInitializer {

    public void onStartup(ServletContext container) {
      XmlWebApplicationContext appContext = new XmlWebApplicationContext();
      ServletRegistration.Dynamic registration =
        container.addServlet("dispatcher", new DispatcherServlet(appContext));
      registration.setLoadOnStartup(1);
      registration.addMapping("*.request");
    }
}
</code>```

you can then call the getRealPath method to get the absolute file path on the server's filesystem. Ref of ServletContext : here

ContentLicense: CC BY-SA 3.0

Body:
I've developed a small REST API that runs inside a Spring container on a Tomcat server. As part of my boot sequence I need to be able to dump the base URL to a log file as:

String myUrl = ...
LOGGER.info("My URL is {}", myUrl);

Which will display

My URL is http://myHostname:8080/myContext/url-pattern

This will happen BEFORE the first call to the API. Once the application has started I can check the logs and use curl or wget to check that the app is responding.

All the solutions I've seen depend on HttpServletRequest, but this requires a call to the REST interface

Ideally I'd like to grab the complete pattern from a Spring object injected into my class, however I don't mind constructing the information from different sources if no such object exists.

So far I've read:

myHostname - InetAddress.getLocalHost().getHostName();

myContext - servletContext.getContextPath()

I've still got to get the port and the url-pattern (as defined in the web.xml) from somewhere.

Note: I understand that when I put my host is behind a load balancer then the domain of my REST API wont match myHostname and that's OK.

Body:
If you are using WebApplicationInitializer instead of web.xml then, you can get hold of context object in onStartup method.

public class WebMVCApplicationInitializer implements
  WebApplicationInitializer {

    public void onStartup(ServletContext container) {
      XmlWebApplicationContext appContext = new XmlWebApplicationContext();
      ServletRegistration.Dynamic registration =
        container.addServlet("dispatcher", new DispatcherServlet(appContext));
      registration.setLoadOnStartup(1);
      registration.addMapping("*.request");
    }
}

you can then call the getRealPath method to get the absolute file path on the server's filesystem. Ref of ServletContext : here


问:
Uncaught Error: Template parse errors: Can't bind to 'ngModel' since it isn't a known property of 'input'
I'm using Angular 4.2.4 and I am getting an error in the console :

```<code>Uncaught Error: Template parse errors: Can't bind to 'ngModel' since it isn't a known property of 'input'.
</code>```

while I include FormsModule in file app.module.ts like as

```<code>import { FormsModule,ReactiveFormsModule }   from '@angular/forms';
@NgModule({
  declarations: [
    AppComponent,
    ...APP_LAYOUTS,
    ...APP_COMPONENTS,
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    AppRoutingModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
</code>```

and by html code is as

```<code><form id="user-add-form">
    <div class="text-center m-t-10"><span class="login-img"><i class="ti-check-box"></i></span></div>
    <h3 class="login-title">Add New User</h3>
    <div class="row">
      <div class="col-6">
        <div class="form-group">
          <input class="form-control" type="text" name="first_name" [(ngModel)]="first_name" placeholder="First Name">
        </div>
      </div>
      <div class="col-6">
        <div class="form-group">
          <input class="form-control" type="text" name="last_name" [(ngModel)]="last_name" placeholder="Last Name">
        </div>
      </div>
    </div>
    <div class="form-group">
      <input class="form-control" type="email" name="email" [(ngModel)]="email" placeholder="Email" autocomplete="off">
    </div>
    <div class="form-group">
      <input class="form-control" id="password" type="password" name="password" [(ngModel)]="password" placeholder="Password">
    </div>
    <div class="form-group">
      <input class="form-control" type="password" name="password_confirmation" [(ngModel)]="password_confirmation" placeholder="Confirm Password">
    </div>
    <div class="form-group">
      <button class="btn btn-info btn-block" type="submit">Submit</button>
    </div>
  </form>
</code>```

and some component file code is

```<code>import { FormBuilder,Validator } from '@angular/forms';
export class UserAddComponent implements OnInit, OnDestroy, AfterViewInit {
    first_name: string;
    last_name: string;
    email: string;
    password: string;
    password_confirmation: string;
</code>```

I already see the below links but not get any solutions

Angular 4 - "Can't bind to 'ngModel' since it isn't a known property of 'input' " error

Angular 2: Can't bind to 'ngModel' since it isn't a known property of 'input'

Can't bind to 'ngModel' since it isn't a known property of 'input'

please help to resolve it

答:
From Wiki,

This error often means that you haven't declared the directive "x" or
  haven't imported the NgModule to which "x" belongs.

You also get this error if "x" really isn't a property or if "x" is a
  private component property (i.e., lacks the @Input or @Output
  decorator).

For example, if "x" is ngModel, you may not have imported the
  FormsModule from @angular/forms.

Perhaps you declared "x" in an application feature module but forgot
  to export it? The "x" class isn't visible to other components of other
  NgModules until you add it to the exports list

So just import 'FormsModule' in 'UserAddComponent'

import { FormsModule,ReactiveFormsModule }   from '@angular/forms';

Hope it helps !!

Body:
I'm using Angular 4.2.4 and I am getting an error in the console :

Uncaught Error: Template parse errors: Can't bind to 'ngModel' since it isn't a known property of 'input'.

while I include FormsModule in file app.module.ts like as

import { FormsModule,ReactiveFormsModule }   from '@angular/forms';
@NgModule({
  declarations: [
    AppComponent,
    ...APP_LAYOUTS,
    ...APP_COMPONENTS,
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    AppRoutingModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})

and by html code is as

<form id="user-add-form">

Add New User

          <input class="form-control" type="text" name="first_name" [(ngModel)]="first_name" placeholder="First Name">

          <input class="form-control" type="text" name="last_name" [(ngModel)]="last_name" placeholder="Last Name">

      <input class="form-control" type="email" name="email" [(ngModel)]="email" placeholder="Email" autocomplete="off">

      <input class="form-control" id="password" type="password" name="password" [(ngModel)]="password" placeholder="Password">

      <input class="form-control" type="password" name="password_confirmation" [(ngModel)]="password_confirmation" placeholder="Confirm Password">

      <button class="btn btn-info btn-block" type="submit">Submit</button>

  </form>

and some component file code is

import { FormBuilder,Validator } from '@angular/forms';
export class UserAddComponent implements OnInit, OnDestroy, AfterViewInit {
    first_name: string;
    last_name: string;
    email: string;
    password: string;
    password_confirmation: string;

I already see the below links but not get any solutions

Angular 4 - "Can't bind to 'ngModel' since it isn't a known property of 'input' " error

Angular 2: Can't bind to 'ngModel' since it isn't a known property of 'input'

Can't bind to 'ngModel' since it isn't a known property of 'input'

please help to resolve it


问:
May periodic read locks in multiple threads completely stall writing thread for a long time?
```<code>// thread function for readers
void func_readers()
{
    for (int i = 0; i < 1000000; ++i)
    {
        read_lock();
        //do some work;
    }
}

// thread function for writers
void func_writers()
{
    write_lock();
    // do some work;
}
</code>```

Let's say there are 4 reader threads, and writer thread starts working. It stops, since there are 4 reading threads. When first reading thread finishes an iteration, it starts another one, and calls read_lock(). writing thread still waits, since there are 3 reading threads. Since there are no writing thread, first reading thread starts another iteration, and so on... Does this mean it's very likely that all 4 threads will do their work for 1000000 times, and only after that writing thread starts doing it's work?

答:
I believe in this situation, if the reader and writer threads share the same lock, the writer will still have a chance to write something. Think of it as this under the hood:

Let's say reader1 currently has the lock. Reader2, reader3, and reader4 are all on a queue waiting for the lock. It's at this point that writer also puts itself on the queue to wait for the lock. Once reader1 finishes, it releases the lock, and then puts itself back on the queue. However, note that at this point, it's on the queue after the writer.

Once reader2, reader3, and reader4 are popped off the queue and do their work, the writer will have the chance to acquire the lock.

Although this code isn't very efficient (it will basically run serially), it will work. Also, since you're on this topic, you should look into different implementations of reader/writer using multiple locks, counters, etc. :)

Body:
// thread function for readers
void func_readers()
{
    for (int i = 0; i < 1000000; ++i)
    {
        read_lock();
        //do some work;
    }
}

// thread function for writers
void func_writers()
{
    write_lock();
    // do some work;
}

Let's say there are 4 reader threads, and writer thread starts working. It stops, since there are 4 reading threads. When first reading thread finishes an iteration, it starts another one, and calls read_lock(). writing thread still waits, since there are 3 reading threads. Since there are no writing thread, first reading thread starts another iteration, and so on... Does this mean it's very likely that all 4 threads will do their work for 1000000 times, and only after that writing thread starts doing it's work?


问:
Match "any string" in Haskell record in HSpec test
I have a data class Entity which is defined like this:

```<code>data Entity = Entity { id :: String, name :: String }
</code>```

and a function that returns IO Entity:

```<code>newPersistentEntity :: String -> IO Entity
</code>```

And I'd like to write an HSpec test for this:

```<code>spec :: Spec
spec = describe "newPersistentEntity function" $
       it "returns a new Entity with a generated id and the specified name" $
       newPersistentEntity "myName" `shouldReturn` Entity {id = <any string>, name = "myName"}
</code>```

The problem is that the id is a UUID generated by the database. I want to assert that the id is a string to make the test pass.

How can I achieve this?

答:
I actually solved this myself in a different way that I'll show here for context. You probably shouldn't use it since the accepted answer is easier to understand and less verbose.

```<code>spec :: Spec
spec = describe "newPersistentEntity function" $
       it "returns a new Entity with a generated id and the specified name" $
       newPersistentEntity "myName" >>= (`shouldSatisfy` (\case
           Entity {id = _, name = "myName"} -> True
           _ -> False))
</code>```

But for this to work you also need to apply the lamda case language extension:

```<code>{-# LANGUAGE LambdaCase #-}
</code>```

Body:
I have a data class Entity which is defined like this:

data Entity = Entity { id :: String, name :: String }

and a function that returns IO Entity:

newPersistentEntity :: String -> IO Entity

And I'd like to write an HSpec test for this:

spec :: Spec
spec = describe "newPersistentEntity function" $
       it "returns a new Entity with a generated id and the specified name" $
       newPersistentEntity "myName" `shouldReturn` Entity {id = <any string>, name = "myName"}

The problem is that the id is a UUID generated by the database. I want to assert that the id is a string to make the test pass.

How can I achieve this?

Body:
I actually solved this myself in a different way that I'll show here for context. You probably shouldn't use it since the accepted answer is easier to understand and less verbose.

spec :: Spec
spec = describe "newPersistentEntity function" $
       it "returns a new Entity with a generated id and the specified name" $
       newPersistentEntity "myName" >>= (`shouldSatisfy` (\case
           Entity {id = _, name = "myName"} -> True
           _ -> False))

But for this to work you also need to apply the lamda case language extension:

{-# LANGUAGE LambdaCase #-}


问:
Are progress/indeterminate dialog boxes added to the end of the UI thread? Do they require a second thread?
I have a simple dialog box.  When I click a button the dialog box is supposed to be shown, while a file save operation is performed, and then the dialog box is dismissed.  The problem I am having is the dialog box isn't shown until after the onClick event of the button finishes.

Taken from the Dialog developer doc:

The setup is simple. Most of the code
  needed to create a progress dialog is
  actually involved in the process that
  updates it. You might find that it's
  necessary to create a second thread in
  your application for this work and
  then report the progress back to the
  Activity's UI thread with a Handler
  object. If you're not familiar with
  using additional threads with a
  Handler, see the example Activity
  below that uses a second thread to
  increment a progress dialog managed by
  the Activity.

Why isn't the dialog shown until after the onClick method finishes?  Is the dialog added to the end of the UI thread?

Is the only way to do this to create a new thread and handler?  That's fairly bad wording in the developer doc if so.

Thanks all.

```<code>    Button send = (Button) findViewById(R.id.send);
    send.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            showDialog(SAVING_DIALOG);
            //Do all the file saving operations
            ...
            ...
            dismissDialog(SAVING_DIALOG);
        }
    });
</code>```

Here is the dialog

```<code>@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {
        case SAVING_DIALOG: {
            ProgressDialog dialog = new ProgressDialog(this);
            dialog.setMessage("Saving file...");
            dialog.setIndeterminate(true);
            dialog.setCancelable(false);
            return dialog;
        }
    }
    return null;
}
</code>```

答:
Shouldn't work be done on a thread when using the progress dialog?

http://www.helloandroid.com/tutorials/using-threads-and-progressdialog

ContentLicense: CC BY-SA 2.5

Body:
I have a simple dialog box.  When I click a button the dialog box is supposed to be shown, while a file save operation is performed, and then the dialog box is dismissed.  The problem I am having is the dialog box isn't shown until after the onClick event of the button finishes.

Taken from the Dialog developer doc:

The setup is simple. Most of the code
  needed to create a progress dialog is
  actually involved in the process that
  updates it. You might find that it's
  necessary to create a second thread in
  your application for this work and
  then report the progress back to the
  Activity's UI thread with a Handler
  object. If you're not familiar with
  using additional threads with a
  Handler, see the example Activity
  below that uses a second thread to
  increment a progress dialog managed by
  the Activity.

Why isn't the dialog shown until after the onClick method finishes?  Is the dialog added to the end of the UI thread?

Is the only way to do this to create a new thread and handler?  That's fairly bad wording in the developer doc if so.

Thanks all.

    Button send = (Button) findViewById(R.id.send);
    send.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            showDialog(SAVING_DIALOG);
            //Do all the file saving operations
            ...
            ...
            dismissDialog(SAVING_DIALOG);
        }
    });

Here is the dialog

@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {
        case SAVING_DIALOG: {
            ProgressDialog dialog = new ProgressDialog(this);
            dialog.setMessage("Saving file...");
            dialog.setIndeterminate(true);
            dialog.setCancelable(false);
            return dialog;
        }
    }
    return null;
}


问:
Upload_to with name of objects
I have a question I think it's easy to your guys about upload_to in Django but it's difficult to me. Hope your helps!

```<code># Upload_to Def
from datetime import datetime
def avatar_country_path(instance, filename):
    ext = filename.split('.')[-1]
    filename = '%s' % (instance.id)
    datetime_str = datetime.now().strftime("%Y%m%d%H%M%S")
    return "geo/country/%s/%s_avatar.%s" %(filename, datetime_str, ext)

def cover_country_path(instance, filename):
    ext = filename.split('.')[-1]
    filename = '%s' % (instance.id)
    datetime_str = datetime.now().strftime("%Y%m%d%H%M%S")
    return "geo/country/%s/%s_cover.%s" %(filename, datetime_str, ext)

def flag_country_path(instance, filename):
    ext = filename.split('.')[-1]
    filename = '%s' % (instance.id)
    datetime_str = datetime.now().strftime("%Y%m%d%H%M%S")
    return "geo/country/%s/%s_flag.%s" %(filename, datetime_str, ext)

class BaseCountry(Place, SlugModel):
    # More
    avatar = models.ImageField(max_length=1024, upload_to=avatar_country_path, blank=True)
    cover = models.ImageField(max_length=1024, upload_to=cover_country_path, blank=True)
    flag = models.ImageField(max_length=1024, upload_to=flag_country_path, blank=True
</code>```

As you see, I need 3 functions to make upload_to with a similar Path, just different in NAME OF FIELDS (avatar, cover, flag) but I dont know how to shorten it.

Could you guys help me?

答:
A trick for figuring out how to shorten code like this is to look for duplicate lines and then try to parameterize the rest like so:

from datetime import datetime

def inject_field_type(instance, filename, suffix):
    ext = filename.split('.')[-1]
    filename = '%s' % (instance.id)
    datetime_str = datetime.now().strftime("%Y%m%d%H%M%S")
    return "geo/country/%s/%s_%s.%s" %(filename, datetime_str, ext, suffix)

def avatar_country_path(instance, filename):
    return inject_field_type(instance, filename, 'avatar')

def cover_country_path(instance, filename):
    return inject_field_type(instance, filename, 'cover')

def flag_country_path(instance, filename):
    return inject_field_type(instance, filename, 'flag')

class BaseCountry(Place, SlugModel):
    avatar = models.ImageField(max_length=1024, upload_to=avatar_country_path, blank=True)
    cover = models.ImageField(max_length=1024, upload_to=cover_country_path, blank=True)
    flag = models.ImageField(max_length=1024, upload_to=flag_country_path, blank=True
```

This way you can change the logic required for creating the path an affect all 3 fields rather than having to change it in 3 different functions.

Title: Upload_to with name of objects

Body:
I have a question I think it's easy to your guys about upload_to in Django but it's difficult to me. Hope your helps!

# Upload_to Def
from datetime import datetime
def avatar_country_path(instance, filename):
    ext = filename.split('.')[-1]
    filename = '%s' % (instance.id)
    datetime_str = datetime.now().strftime("%Y%m%d%H%M%S")
    return "geo/country/%s/%s_avatar.%s" %(filename, datetime_str, ext)

def cover_country_path(instance, filename):
    ext = filename.split('.')[-1]
    filename = '%s' % (instance.id)
    datetime_str = datetime.now().strftime("%Y%m%d%H%M%S")
    return "geo/country/%s/%s_cover.%s" %(filename, datetime_str, ext)

def flag_country_path(instance, filename):
    ext = filename.split('.')[-1]
    filename = '%s' % (instance.id)
    datetime_str = datetime.now().strftime("%Y%m%d%H%M%S")
    return "geo/country/%s/%s_flag.%s" %(filename, datetime_str, ext)

class BaseCountry(Place, SlugModel):
    # More
    avatar = models.ImageField(max_length=1024, upload_to=avatar_country_path, blank=True)
    cover = models.ImageField(max_length=1024, upload_to=cover_country_path, blank=True)
    flag = models.ImageField(max_length=1024, upload_to=flag_country_path, blank=True

As you see, I need 3 functions to make upload_to with a similar Path, just different in NAME OF FIELDS (avatar, cover, flag) but I dont know how to shorten it.

Could you guys help me?

Body:
A trick for figuring out how to shorten code like this is to look for duplicate lines and then try to parameterize the rest like so:

from datetime import datetime

def inject_field_type(instance, filename, suffix):
    ext = filename.split('.')[-1]
    filename = '%s' % (instance.id)
    datetime_str = datetime.now().strftime("%Y%m%d%H%M%S")
    return "geo/country/%s/%s_%s.%s" %(filename, datetime_str, ext, suffix)

def avatar_country_path(instance, filename):
    return inject_field_type(instance, filename, 'avatar')

def cover_country_path(instance, filename):
    return inject_field_type(instance, filename, 'cover')

def flag_country_path(instance, filename):
    return inject_field_type(instance, filename, 'flag')

class BaseCountry(Place, SlugModel):
    avatar = models.ImageField(max_length=1024, upload_to=avatar_country_path, blank=True)
    cover = models.ImageField(max_length=1024, upload_to=cover_country_path, blank=True)
    flag = models.ImageField(max_length=1024, upload_to=flag_country_path, blank=True

This way you can change the logic required for creating the path an affect all 3 fields rather than having to change it in 3 different functions.


问:
Calculations by Subgroup in a Column
I have a dataset that looks approximately like this:

```<code>> dataSet
   month detrend
1    Jan  315.71
2    Jan  317.45
3    Jan   317.5
4    Jan   317.1
5    Jan  315.71
6    Feb  317.45
7    Feb   313.5
8    Feb   317.1
9    Feb  314.37
10   Feb  315.41
11 March  316.44
12 March  315.73
13 March  318.73
14 March  315.55
15 March  312.64
.
.
.
</code>```

How do I compute the average by month?  E.g., I want something like

```<code>> by_month
   month ave_detrend
1    Jan  315.71
2    Feb  317.45
3  March   317.5
</code>```

答:
What you need to focus on is a means to group your column of interest (the "detrend") by the month.  There are ways to do this within "vanilla R", but the most effective way is to use tidyverse's dplyr.

I will use the example taken directly from that page:

```<code>mtcars %>%
  group_by(cyl) %>%
  summarise(disp = mean(disp), sd = sd(disp))
</code>```

In your case, that would be:

```<code>by_month <- dataSet %>%
  group_by(month) %>%
  summarize(avg = mean(detrend))
</code>```

This new "tidyverse" style looks quite different, and you seem quite new, so I'll explain what's happening (sorry if this is overly obvious):

First, we are grabbing the dataframe, which I'm calling dataSet.

Then we are piping that dataset to our next function, which is group_by.  Piping means that we're putting the results of the last command (which in this case is just the dataframe dataSet) and using it as the first parameter of our next function.  The function group_by has a dataframe provided as its first function.

Then the results of that group by are piped to the next function, which is summarize (or summarise if you're from down under, as the author is).  summarize simply calculates using all the data in the column, however, the group_by function creates partitions in that column.  So we now have the mean calculated for each partition that we've made, which is month.

This is the key: group_by creates "flags" so that summarize calculates the function (mean, in this case) separately on each group.  So, for instance, all of the Jan values are grouped together and then the mean is calculated only on them.  Then for all of the Feb values, the mean is calculated, etc.

HTH!!

Title: Calculations by Subgroup in a Column

Body:
I have a dataset that looks approximately like this:

> dataSet
   month detrend
1    Jan  315.71
2    Jan  317.45
3    Jan   317.5
4    Jan   317.1
5    Jan  315.71
6    Feb  317.45
7    Feb   313.5
8    Feb   317.1
9    Feb  314.37
10   Feb  315.41
11 March  316.44
12 March  315.73
13 March  318.73
14 March  315.55
15 March  312.64
.
.
.

How do I compute the average by month?  E.g., I want something like

> by_month
   month ave_detrend
1    Jan  315.71
2    Feb  317.45
3  March   317.5

Body:
What you need to focus on is a means to group your column of interest (the "detrend") by the month.  There are ways to do this within "vanilla R", but the most effective way is to use tidyverse's dplyr.

I will use the example taken directly from that page:

mtcars %>%
  group_by(cyl) %>%
  summarise(disp = mean(disp), sd = sd(disp))

In your case, that would be:

by_month <- dataSet %>%
  group_by(month) %>%
  summarize(avg = mean(detrend))

This new "tidyverse" style looks quite different, and you seem quite new, so I'll explain what's happening (sorry if this is overly obvious):

First, we are grabbing the dataframe, which I'm calling dataSet.

Then we are piping that dataset to our next function, which is group_by.  Piping means that we're putting the results of the last command (which in this case is just the dataframe dataSet) and using it as the first parameter of our next function.  The function group_by has a dataframe provided as its first function.

Then the results of that group by are piped to the next function, which is summarize (or summarise if you're from down under, as the author is).  summarize simply calculates using all the data in the column, however, the group_by function creates partitions in that column.  So we now have the mean calculated for each partition that we've made, which is month.

This is the key: group_by creates "flags" so that summarize calculates the function (mean, in this case) separately on each group.  So, for instance, all of the Jan values are grouped together and then the mean is calculated only on them.  Then for all of the Feb values, the mean is calculated, etc.

HTH!!


问:
Remove app from recent apps programmatically
I know that Activities can be declared in manifest as being excluded from recents with android:excludeFromRecents:
http://developer.android.com/guide/topics/manifest/activity-element.html#exclude

However, that's not what I'm looking for, I would like to know if there is a way to remove the app from recent apps programmatically

答:
Add these lines to the Activity from which you are exiting the application:</p>

```<code>@Override
public void finish() {
    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        super.finishAndRemoveTask();
    }
    else {
        super.finish();
    }
}
</code>```

Body:
Add these lines to the Activity from which you are exiting the application:

@Override
public void finish() {
    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        super.finishAndRemoveTask();
    }
    else {
        super.finish();
    }
}


问:
Wordpress, Plesk Windows hosting, IIS, slow resolve, GoDaddy
So before anyone states the obvious of Wordpress and IIS don't go together. I am aware of this, but I am switching over to a .Net CMS later so I got a Windows hosting plan.

That said, the current Wordpress site is insanely slow at resolving and I was wondering if there is anything in IIS (Plesk) I can set up speed up the site.
I have a .user.ini file in which I added the property

```<code>[wincache]
wincache.ocenabled = 1
</code>```

this did nothing to speed up the site.  Not sure if the .user.ini file that came with the hosting (GoDaddy) even does anything.  GoDaddy has not been much help in terms of helping resolve or give ideas about the issue other than Wordpress doesn't belong on a Windows hosting.  That is fine and all, but I have another PHP application at my work running on IIS and the thing is fairly quick, so PHP and Windows CAN exist and be faster than 5-8 second load times a page.  Images are optimized and most pages are text with navigation and a header image. This seems to resolve slow no matter how fast a network is.

FastCGI application and PHP 5.6 are both enabled.
I am adding another image of my Plesk set up for PHP.

I see there is a Plesk rewrite property in the web.config that I can only suspect is a culprit because it looks like some sort of rewrite per file and directory, but it looks like this is needed because when I took it out, all the links for the navigation and everything 404'd.

```<code>     <rewrite>
  <rules><rule name="Plesk. Wordpress redirect wpConfigRule #cdc1b047-917c-43e1-9137-a839c52db841" stopProcessing="true"><match url="^wp-config.php$" ignoreCase="false"/><action type="CustomResponse" statusCode="403" statusReason="Forbidden" statusDescription="Forbidden"/></rule>
        <rule name="WordPress: http://mysiteurlhere.com" patternSyntax="Wildcard">
            <match url="*"/>
                <conditions>
                    <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true"/>
                    <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true"/>
                </conditions>
            <action type="Rewrite" url="index.php"/>
        </rule></rules>
</rewrite>
</code>```

Any ideas on Plesk Window Hosting configuration, IIS configuration, that I should be looking at to help speed up a website in general as well as a Wordpress site for the time being?

UPDATE:

Issue seems to specifically be with GoDaddy.  I have LunarPages Windows hosting and the same set up works very quickly.

It is due to a rewrite rule set up on the server for some reason.  Both my Lunarpages hosting and the GoDaddy hosting are hosted in Plesk.  But it seems only the GoDaddy has a rewrite rule in it's web.config. Commenting out the rewrite rule breaks the routing.

答: I would advise you to switch to a more faster PHP 7.x version. Plesk allows you to do this easily.</p>

Body:
So before anyone states the obvious of Wordpress and IIS don't go together. I am aware of this, but I am switching over to a .Net CMS later so I got a Windows hosting plan.

That said, the current Wordpress site is insanely slow at resolving and I was wondering if there is anything in IIS (Plesk) I can set up speed up the site.
I have a .user.ini file in which I added the property

[wincache]
wincache.ocenabled = 1

this did nothing to speed up the site.  Not sure if the .user.ini file that came with the hosting (GoDaddy) even does anything.  GoDaddy has not been much help in terms of helping resolve or give ideas about the issue other than Wordpress doesn't belong on a Windows hosting.  That is fine and all, but I have another PHP application at my work running on IIS and the thing is fairly quick, so PHP and Windows CAN exist and be faster than 5-8 second load times a page.  Images are optimized and most pages are text with navigation and a header image. This seems to resolve slow no matter how fast a network is.

FastCGI application and PHP 5.6 are both enabled.
I am adding another image of my Plesk set up for PHP.

I see there is a Plesk rewrite property in the web.config that I can only suspect is a culprit because it looks like some sort of rewrite per file and directory, but it looks like this is needed because when I took it out, all the links for the navigation and everything 404'd.

     <rewrite>
  <rules><rule name="Plesk. Wordpress redirect wpConfigRule #cdc1b047-917c-43e1-9137-a839c52db841" stopProcessing="true"><match url="^wp-config.php$" ignoreCase="false"/><action type="CustomResponse" statusCode="403" statusReason="Forbidden" statusDescription="Forbidden"/></rule>
        <rule name="WordPress: http://mysiteurlhere.com" patternSyntax="Wildcard">
            <match url="*"/>
                <conditions>
                    <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true"/>
                    <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true"/>
                </conditions>
            <action type="Rewrite" url="index.php"/>
        </rule></rules>
</rewrite>

Any ideas on Plesk Window Hosting configuration, IIS configuration, that I should be looking at to help speed up a website in general as well as a Wordpress site for the time being?

UPDATE:

Issue seems to specifically be with GoDaddy.  I have LunarPages Windows hosting and the same set up works very quickly.

It is due to a rewrite rule set up on the server for some reason.  Both my Lunarpages hosting and the GoDaddy hosting are hosted in Plesk.  But it seems only the GoDaddy has a rewrite rule in it's web.config. Commenting out the rewrite rule breaks the routing.


问:
Problem selecting max year, max month & max date in one query
```<code>CREATE TABLE TEMP
(
C_INVOICE_ID NUMBER(10),
DIA NUMBER,
MES NUMBER,
ANO NUMBER,
SOCIO_NEGOCIO NVARCHAR2(60) NOT NULL,
PRODUCTO_NOM NVARCHAR2(60) NOT NULL,
M_PRODUCT_ID NUMBER(10),
CATEGORIA NVARCHAR2(60) NOT NULL,
COSTO NUMBER
)

INSERT INTO TEMP VALUES(10111,1,2,2010,'1585','ALURON 100MG X 30 TABLETAS',1530,15,1.15);
INSERT INTO TEMP VALUES(1015,15,2,2010,'1520','ALURON 100MG X 30 TABLETAS',1530,15,2.15);
INSERT INTO TEMP VALUES(5654,5,2,2010,'1520','AMARYL 2MG X 15 TABLETAS',1531,15,4.2);
INSERT INTO TEMP VALUES(15321,4,6,2010,'1520','AMARYL 2MG X 15 TABLETAS',1531,15,4.8);
INSERT INTO TEMP VALUES(13548,8,6,2010,'1585','AMARYL 2MG X 15 TABLETAS',1531,15,4.3);
INSERT INTO TEMP VALUES(19456,31,4,2010,'1220','AMARYL 2MG X 15 TABLETAS',1531,15,4);
INSERT INTO TEMP VALUES(116544,8,8,2010,'1220','AMARYL 2MG X 15 TABLETAS',1531,15,4.8);
INSERT INTO TEMP VALUES(132,2,3,2010,'1220','AMARYL 2MG X 15 TABLETAS',1531,15,4.1);
INSERT INTO TEMP VALUES(168,15,1,2010,'1220','AMARYL 2MG X 15 TABLETAS',1531,15,4.9);
INSERT INTO TEMP VALUES(4898,7,4,2010,'1220','AMOXAL 250MG X 75ML SUSPENSION',1534,15,3.8);
INSERT INTO TEMP VALUES(15132,25,9,2010,'1585','AMOXAL 250MG X 75ML SUSPENSION',1534,15,3.4);
INSERT INTO TEMP VALUES(1684,18,8,2010,'1585','AMOXAL 250MG X 75ML SUSPENSION',1534,15,3.3);
INSERT INTO TEMP VALUES(14988,8,8,2010,'1585','AMOXAL 250MG X 75ML SUSPENSION',1534,15,2.9);
INSERT INTO TEMP VALUES(84941,8,9,2010,'1585','AMOXAL 250MG X 75ML SUSPENSION',1534,15,4.1);
INSERT INTO TEMP VALUES(1155,7,4,2010,'1585','AMOXAL 250MG X 75ML SUSPENSION',1534,15,4.7);
INSERT INTO TEMP VALUES(184,1,1,2010,'1520','AMOXAL 250MG X 75ML SUSPENSION',1534,15,3.9);
INSERT INTO TEMP VALUES(48994,8,4,2010,'1520','AMOXAL 250MG X 75ML SUSPENSION',1534,15,3.7);
INSERT INTO TEMP VALUES(1465465,9,5,2009,'1520','AMOXAL 250MG X 75ML SUSPENSION',1534,15,3.8);
INSERT INTO TEMP VALUES(16,18,6,2009,'1520','AMOXAL 250MG X 75ML SUSPENSION',1534,15,3.9);
INSERT INTO TEMP VALUES(894886,20,4,2009,'1520','AMOXAL 250MG X 75ML SUSPENSION',1534,15,3.9);

CREATE TABLE TEMP
(
C_INVOICE_ID NUMBER(10),
DIA NUMBER,
MES NUMBER,
ANO NUMBER,
SOCIO_NEGOCIO NVARCHAR2(60) NOT NULL,
PRODUCTO_NOM NVARCHAR2(60) NOT NULL,
M_PRODUCT_ID NUMBER(10),
CATEGORIA NVARCHAR2(60) NOT NULL,
COSTO NUMBER
)

INSERT INTO TEMP VALUES(10111,1,2,2010,'1585','ALURON 100MG X 30 TABLETAS',1530,15,1.15);
INSERT INTO TEMP VALUES(1015,15,2,2010,'1520','ALURON 100MG X 30 TABLETAS',1530,15,2.15);
INSERT INTO TEMP VALUES(5654,5,2,2010,'1520','AMARYL 2MG X 15 TABLETAS',1531,15,4.2);
INSERT INTO TEMP VALUES(15321,4,6,2010,'1520','AMARYL 2MG X 15 TABLETAS',1531,15,4.8);
INSERT INTO TEMP VALUES(13548,8,6,2010,'1585','AMARYL 2MG X 15 TABLETAS',1531,15,4.3);
INSERT INTO TEMP VALUES(19456,31,4,2010,'1220','AMARYL 2MG X 15 TABLETAS',1531,15,4);
INSERT INTO TEMP VALUES(116544,8,8,2010,'1220','AMARYL 2MG X 15 TABLETAS',1531,15,4.8);
INSERT INTO TEMP VALUES(132,2,3,2010,'1220','AMARYL 2MG X 15 TABLETAS',1531,15,4.1);
INSERT INTO TEMP VALUES(168,15,1,2010,'1220','AMARYL 2MG X 15 TABLETAS',1531,15,4.9);
INSERT INTO TEMP VALUES(4898,7,4,2010,'1220','AMOXAL 250MG X 75ML SUSPENSION',1534,15,3.8);
INSERT INTO TEMP VALUES(15132,25,9,2010,'1585','AMOXAL 250MG X 75ML SUSPENSION',1534,15,3.4);
INSERT INTO TEMP VALUES(1684,18,8,2010,'1585','AMOXAL 250MG X 75ML SUSPENSION',1534,15,3.3);
INSERT INTO TEMP VALUES(14988,8,8,2010,'1585','AMOXAL 250MG X 75ML SUSPENSION',1534,15,2.9);
INSERT INTO TEMP VALUES(84941,8,9,2010,'1585','AMOXAL 250MG X 75ML SUSPENSION',1534,15,4.1);
INSERT INTO TEMP VALUES(1155,7,4,2010,'1585','AMOXAL 250MG X 75ML SUSPENSION',1534,15,4.7);
INSERT INTO TEMP VALUES(184,1,1,2010,'1520','AMOXAL 250MG X 75ML SUSPENSION',1534,15,3.9);
INSERT INTO TEMP VALUES(48994,8,4,2010,'1520','AMOXAL 250MG X 75ML SUSPENSION',1534,15,3.7);
INSERT INTO TEMP VALUES(1465465,9,5,2009,'1520','AMOXAL 250MG X 75ML SUSPENSION',1534,15,3.8);
INSERT INTO TEMP VALUES(16,18,6,2009,'1520','AMOXAL 250MG X 75ML SUSPENSION',1534,15,3.9);
INSERT INTO TEMP VALUES(894886,20,4,2009,'1520','AMOXAL 250MG X 75ML SUSPENSION',1534,15,3.9);
</code>```

I have this query so far,

```<code>SELECT MAX (TEMP.COSTO) COSTO,
       TEMP.M_PRODUCT_ID,
       TEMP.ANO
  FROM TEMP TEMP
       INNER JOIN
       (SELECT MAX(ANO) ANO,
               M_PRODUCT_ID
          FROM TEMP I
        GROUP BY M_PRODUCT_ID
       ) LA ON
       LA.ANO = TEMP.ANO
   AND LA.M_PRODUCT_ID = TEMP.M_PRODUCT_ID
GROUP BY TEMP.M_PRODUCT_ID,
         TEMP.ANO;
</code>```

but my intention is not to have the max cost, my intention is to query in this order

first i need to select distinct m_product_id then

for every m_product_id i need to

filter max (ano) then filter max (mes) then filter max (dia)

I need the result set like this.

```<code>C_INVOICE_ID DIA MES ANO SOCIO  PRODUCTO_NO                 M_PRODUCT_ID CATERGORIA COSTO
1015         15  2    2010 1520 ALURON 100MG X 30 TABLETAS     1530           15     2.15
5654         5   2    2010 1520 AMARYL 2MG X 15 TABLETAS       1531           15     4.2
15132        25  9    2010 1585 AMOXAL 250MG X 75ML SUSPENSION 1534           15     3.4
</code>```

please i really apritiated any help, thanks pd:i'm using oracle 9i

答:
Try this:</p>

```<code>SELECT a.*
  FROM (
         SELECT a.*, RANK() OVER(PARTITION BY m_product_id ORDER BY DIA,MES,ANO DESC) rnk
           FROM temp a
       ) a
 WHERE rnk=1
</code>```

Body:
CREATE TABLE TEMP
(
C_INVOICE_ID NUMBER(10),
DIA NUMBER,
MES NUMBER,
ANO NUMBER,
SOCIO_NEGOCIO NVARCHAR2(60) NOT NULL,
PRODUCTO_NOM NVARCHAR2(60) NOT NULL,
M_PRODUCT_ID NUMBER(10),
CATEGORIA NVARCHAR2(60) NOT NULL,
COSTO NUMBER
)

INSERT INTO TEMP VALUES(10111,1,2,2010,'1585','ALURON 100MG X 30 TABLETAS',1530,15,1.15);
INSERT INTO TEMP VALUES(1015,15,2,2010,'1520','ALURON 100MG X 30 TABLETAS',1530,15,2.15);
INSERT INTO TEMP VALUES(5654,5,2,2010,'1520','AMARYL 2MG X 15 TABLETAS',1531,15,4.2);
INSERT INTO TEMP VALUES(15321,4,6,2010,'1520','AMARYL 2MG X 15 TABLETAS',1531,15,4.8);
INSERT INTO TEMP VALUES(13548,8,6,2010,'1585','AMARYL 2MG X 15 TABLETAS',1531,15,4.3);
INSERT INTO TEMP VALUES(19456,31,4,2010,'1220','AMARYL 2MG X 15 TABLETAS',1531,15,4);
INSERT INTO TEMP VALUES(116544,8,8,2010,'1220','AMARYL 2MG X 15 TABLETAS',1531,15,4.8);
INSERT INTO TEMP VALUES(132,2,3,2010,'1220','AMARYL 2MG X 15 TABLETAS',1531,15,4.1);
INSERT INTO TEMP VALUES(168,15,1,2010,'1220','AMARYL 2MG X 15 TABLETAS',1531,15,4.9);
INSERT INTO TEMP VALUES(4898,7,4,2010,'1220','AMOXAL 250MG X 75ML SUSPENSION',1534,15,3.8);
INSERT INTO TEMP VALUES(15132,25,9,2010,'1585','AMOXAL 250MG X 75ML SUSPENSION',1534,15,3.4);
INSERT INTO TEMP VALUES(1684,18,8,2010,'1585','AMOXAL 250MG X 75ML SUSPENSION',1534,15,3.3);
INSERT INTO TEMP VALUES(14988,8,8,2010,'1585','AMOXAL 250MG X 75ML SUSPENSION',1534,15,2.9);
INSERT INTO TEMP VALUES(84941,8,9,2010,'1585','AMOXAL 250MG X 75ML SUSPENSION',1534,15,4.1);
INSERT INTO TEMP VALUES(1155,7,4,2010,'1585','AMOXAL 250MG X 75ML SUSPENSION',1534,15,4.7);
INSERT INTO TEMP VALUES(184,1,1,2010,'1520','AMOXAL 250MG X 75ML SUSPENSION',1534,15,3.9);
INSERT INTO TEMP VALUES(48994,8,4,2010,'1520','AMOXAL 250MG X 75ML SUSPENSION',1534,15,3.7);
INSERT INTO TEMP VALUES(1465465,9,5,2009,'1520','AMOXAL 250MG X 75ML SUSPENSION',1534,15,3.8);
INSERT INTO TEMP VALUES(16,18,6,2009,'1520','AMOXAL 250MG X 75ML SUSPENSION',1534,15,3.9);
INSERT INTO TEMP VALUES(894886,20,4,2009,'1520','AMOXAL 250MG X 75ML SUSPENSION',1534,15,3.9);

CREATE TABLE TEMP
(
C_INVOICE_ID NUMBER(10),
DIA NUMBER,
MES NUMBER,
ANO NUMBER,
SOCIO_NEGOCIO NVARCHAR2(60) NOT NULL,
PRODUCTO_NOM NVARCHAR2(60) NOT NULL,
M_PRODUCT_ID NUMBER(10),
CATEGORIA NVARCHAR2(60) NOT NULL,
COSTO NUMBER
)

INSERT INTO TEMP VALUES(10111,1,2,2010,'1585','ALURON 100MG X 30 TABLETAS',1530,15,1.15);
INSERT INTO TEMP VALUES(1015,15,2,2010,'1520','ALURON 100MG X 30 TABLETAS',1530,15,2.15);
INSERT INTO TEMP VALUES(5654,5,2,2010,'1520','AMARYL 2MG X 15 TABLETAS',1531,15,4.2);
INSERT INTO TEMP VALUES(15321,4,6,2010,'1520','AMARYL 2MG X 15 TABLETAS',1531,15,4.8);
INSERT INTO TEMP VALUES(13548,8,6,2010,'1585','AMARYL 2MG X 15 TABLETAS',1531,15,4.3);
INSERT INTO TEMP VALUES(19456,31,4,2010,'1220','AMARYL 2MG X 15 TABLETAS',1531,15,4);
INSERT INTO TEMP VALUES(116544,8,8,2010,'1220','AMARYL 2MG X 15 TABLETAS',1531,15,4.8);
INSERT INTO TEMP VALUES(132,2,3,2010,'1220','AMARYL 2MG X 15 TABLETAS',1531,15,4.1);
INSERT INTO TEMP VALUES(168,15,1,2010,'1220','AMARYL 2MG X 15 TABLETAS',1531,15,4.9);
INSERT INTO TEMP VALUES(4898,7,4,2010,'1220','AMOXAL 250MG X 75ML SUSPENSION',1534,15,3.8);
INSERT INTO TEMP VALUES(15132,25,9,2010,'1585','AMOXAL 250MG X 75ML SUSPENSION',1534,15,3.4);
INSERT INTO TEMP VALUES(1684,18,8,2010,'1585','AMOXAL 250MG X 75ML SUSPENSION',1534,15,3.3);
INSERT INTO TEMP VALUES(14988,8,8,2010,'1585','AMOXAL 250MG X 75ML SUSPENSION',1534,15,2.9);
INSERT INTO TEMP VALUES(84941,8,9,2010,'1585','AMOXAL 250MG X 75ML SUSPENSION',1534,15,4.1);
INSERT INTO TEMP VALUES(1155,7,4,2010,'1585','AMOXAL 250MG X 75ML SUSPENSION',1534,15,4.7);
INSERT INTO TEMP VALUES(184,1,1,2010,'1520','AMOXAL 250MG X 75ML SUSPENSION',1534,15,3.9);
INSERT INTO TEMP VALUES(48994,8,4,2010,'1520','AMOXAL 250MG X 75ML SUSPENSION',1534,15,3.7);
INSERT INTO TEMP VALUES(1465465,9,5,2009,'1520','AMOXAL 250MG X 75ML SUSPENSION',1534,15,3.8);
INSERT INTO TEMP VALUES(16,18,6,2009,'1520','AMOXAL 250MG X 75ML SUSPENSION',1534,15,3.9);
INSERT INTO TEMP VALUES(894886,20,4,2009,'1520','AMOXAL 250MG X 75ML SUSPENSION',1534,15,3.9);

I have this query so far,

SELECT MAX (TEMP.COSTO) COSTO,
       TEMP.M_PRODUCT_ID,
       TEMP.ANO
  FROM TEMP TEMP
       INNER JOIN
       (SELECT MAX(ANO) ANO,
               M_PRODUCT_ID
          FROM TEMP I
        GROUP BY M_PRODUCT_ID
       ) LA ON
       LA.ANO = TEMP.ANO
   AND LA.M_PRODUCT_ID = TEMP.M_PRODUCT_ID
GROUP BY TEMP.M_PRODUCT_ID,
         TEMP.ANO;

but my intention is not to have the max cost, my intention is to query in this order

first i need to select distinct m_product_id then

for every m_product_id i need to

filter max (ano) then filter max (mes) then filter max (dia)

I need the result set like this.

C_INVOICE_ID DIA MES ANO SOCIO  PRODUCTO_NO                 M_PRODUCT_ID CATERGORIA COSTO
1015         15  2    2010 1520 ALURON 100MG X 30 TABLETAS     1530           15     2.15
5654         5   2    2010 1520 AMARYL 2MG X 15 TABLETAS       1531           15     4.2
15132        25  9    2010 1585 AMOXAL 250MG X 75ML SUSPENSION 1534           15     3.4

please i really apritiated any help, thanks pd:i'm using oracle 9i

Body:
Try this:

SELECT a.*
  FROM (
         SELECT a.*, RANK() OVER(PARTITION BY m_product_id ORDER BY DIA,MES,ANO DESC) rnk
           FROM temp a
       ) a
 WHERE rnk=1


问:
How to build Python Lambda for Alexa skill with sequence of statements?
I am building Alexa skill for my application. When your ask's 'what is my account status?' this intent return sequence of statements related to user's account. API gives following response

```<code>response = [{
..
text: 'Total orders are 41, Delivered 28'
..
},
{
..
text: 'Today orders are 12, Delivered 2'
..
},
{}]
</code>```

How to build response sequence based on API response?

With this intent, I get the response from API with set statements Alexa should prompt each statement one by one. If the user said 'next' in between any of the statement while Alexa prompting then it goes to next statement in the response array.

答:
First when user says "what is my account status?" your intent will be called and you will get response in a list where in the first call you will display 0th item.

API Result:

```<code>response = [{
..
text: 'Total orders are 41, Delivered 28'
..
},
{
..
text: 'Today orders are 12, Delivered 2'
..
},
{}]
</code>```

You need to store information in Session attributes, like intent name, index which you displayed (0 in case of first call) etc.

Now you need to setup one more intent which will be triggered on keywords like next. In the code you will check values of session attributes and make your response according to the values. For example you would want to check previous intent name, previous index. If all is fine you will modify the session attributes and respond to user.

Hope it helps.

Body:
I am building Alexa skill for my application. When your ask's 'what is my account status?' this intent return sequence of statements related to user's account. API gives following response

response = [{
..
text: 'Total orders are 41, Delivered 28'
..
},
{
..
text: 'Today orders are 12, Delivered 2'
..
},
{}]

How to build response sequence based on API response?

With this intent, I get the response from API with set statements Alexa should prompt each statement one by one. If the user said 'next' in between any of the statement while Alexa prompting then it goes to next statement in the response array.

Body:
First when user says "what is my account status?" your intent will be called and you will get response in a list where in the first call you will display 0th item.

API Result:

response = [{
..
text: 'Total orders are 41, Delivered 28'
..
},
{
..
text: 'Today orders are 12, Delivered 2'
..
},
{}]

You need to store information in Session attributes, like intent name, index which you displayed (0 in case of first call) etc.

Now you need to setup one more intent which will be triggered on keywords like next. In the code you will check values of session attributes and make your response according to the values. For example you would want to check previous intent name, previous index. If all is fine you will modify the session attributes and respond to user.

Hope it helps.


问:
How would I calculate the standard deviation from a file of floating point numbers?
I'm trying to write a Java program to calculate the maximum, minimum, mean and standard deviation after reading a text file full of floating point numbers. As you can see, I've calculated the max, min, mean, but for the standard deviation, I'm confused. Any ideas how I should implement this?

Also, I'm fairly new to programming, so sorry if things aren't structured correctly.

Here's my code:

```<code>/*
 * Create a Java program to read a file of floating point numbers and compute
 * the following statistics from the data file:
 *
 * 1. Maximum
 * 2. Minimum
 * 3. Arithmetic Average (Mean)
 * 4. Standard Deviation
 *
 * Do not assume anything about the large numbers in the file. They could be
 * positive or negative, and their magnitude could be extremely large or
 * extremely small.
 */

import java.io.*;
import java.util.Scanner;

public class DataFile {

public static void main(String[] args) {
    // declare variables
    double number, maximum, minimum, sum, mean, standardDeviation;
    int count;

    Scanner file = null;

/* -------------------------------------------------------------------------- */
    try {
        file = new Scanner(new File("RawData.txt"));
    }

    catch(FileNotFoundException e) {
        System.out.print("Error; The program was terminated!");
        System.exit(1);
    }

/* -------------------------------------------------------------------------- */
    // initialize variables
    maximum = file.nextDouble();
    minimum = maximum;
    sum = 0;
    count = 1;

    while(file.hasNextDouble()) {
        number = file.nextDouble();

        if(number > maximum)
            maximum = number;

        else if(number < minimum)
            minimum = number;

        sum += number;
        count += 1;

    } // end while loop

    file.close();

/* -------------------------------------------------------------------------- */
    // mean calculation
    mean = sum / count;

    // standard deviation calculation
    // .....

    // display statistics
    System.out.println("Maximum ------------> " + maximum                   );
    System.out.println("Minimum ------------> " + minimum                   );
    System.out.println("Sum ----------------> " + sum                       );
    System.out.println("Count --------------> " + count                     );
    System.out.println("Mean ---------------> " + mean                      );

} // end method main

} // end class DataFile
</code>```

答: It the while loop you could put each of number into the ArrayList that is initialized before this loop. When you reach the end of a file you could change the values in your ArrayList - you need to provide a loop to store in thata list the difference between the values already in list and the mean and you square that difference. After you loop entire ArrayList, you sum the values from ArrayList, divide it with the count and then you just need the element of that result.

Body:
I'm trying to write a Java program to calculate the maximum, minimum, mean and standard deviation after reading a text file full of floating point numbers. As you can see, I've calculated the max, min, mean, but for the standard deviation, I'm confused. Any ideas how I should implement this?

Also, I'm fairly new to programming, so sorry if things aren't structured correctly.

Here's my code:

/*
 * Create a Java program to read a file of floating point numbers and compute
 * the following statistics from the data file:
 *
 * 1. Maximum
 * 2. Minimum
 * 3. Arithmetic Average (Mean)
 * 4. Standard Deviation
 *
 * Do not assume anything about the large numbers in the file. They could be
 * positive or negative, and their magnitude could be extremely large or
 * extremely small.
 */

import java.io.*;
import java.util.Scanner;

public class DataFile {

public static void main(String[] args) {
    // declare variables
    double number, maximum, minimum, sum, mean, standardDeviation;
    int count;

    Scanner file = null;

/* -------------------------------------------------------------------------- */
    try {
        file = new Scanner(new File("RawData.txt"));
    }

    catch(FileNotFoundException e) {
        System.out.print("Error; The program was terminated!");
        System.exit(1);
    }

/* -------------------------------------------------------------------------- */
    // initialize variables
    maximum = file.nextDouble();
    minimum = maximum;
    sum = 0;
    count = 1;

    while(file.hasNextDouble()) {
        number = file.nextDouble();

        if(number > maximum)
            maximum = number;

        else if(number < minimum)
            minimum = number;

        sum += number;
        count += 1;

    } // end while loop

    file.close();

/* -------------------------------------------------------------------------- */
    // mean calculation
    mean = sum / count;

    // standard deviation calculation
    // .....

    // display statistics
    System.out.println("Maximum ------------> " + maximum                   );
    System.out.println("Minimum ------------> " + minimum                   );
    System.out.println("Sum ----------------> " + sum                       );
    System.out.println("Count --------------> " + count                     );
    System.out.println("Mean ---------------> " + mean                      );

} // end method main

} // end class DataFile


问:
Big O Clarification on Loop with Division
I thought I understood Big-O fully and I think I still have an okay understanding but I wanted to make sure that I am understanding it correctly.

If I have code similar to this:

```<code>while(number > 0)
{
    sum += number;
    number /= 2;
}
</code>```

I believe that my Big-O runtime would be O(N) since the loop would run, by my calculations, for O(N/2) and then each of the statements in the loop would run for O(1) so we end up with O(N ^ 1/2) + O(1) + O(1) so O(N ^ 1/2 + 1 + 1) and we drop the constants leaving us with O(N ^ 1/2)  or O(sqrt N) complexity... I believe this would be log(n) Big-O runtime but just wanted some clarification and verification to make sure I understood this concept. I have read up quite a bit on this topic and watched videos - I just couldn't find a similar enough example anywhere and the 'number /= 2' is what is throwing me off.

For the record, it was a homework question that got me thinking about this.

答:
Mathematically speaking, your algorithm would never even terminate assuming that number can bear a decimal component.  This is because no matter how many times you divide a positive number, you will always be left with some number greater than zero.  In practice, a computer floating point number would eventually hit zero due to rounding error.

I would like to answer your question with a slight change:

```<code>while (number > 1) {
    sum += number;
    number /= 2;
}
</code>```

The running time for this algorithm is actually log_2(N) (i.e. log base 2 of N).  To see why, consider an input number of 16.  Then the following iterations would take place, with corresponding values of number:

```<code>iteration # | number
1           | 16 = 2^4
2           | 8  = 2^3
3           | 4  = 2^2
4           | 2  = 2^1
5           | 1  = 2^0
</code>```

You can convince yourself that the exponent on the base 2 determines the number of iterations.  We access that value by taking the log base 2, hence the running time is O(log_2(N)).

Body:
I thought I understood Big-O fully and I think I still have an okay understanding but I wanted to make sure that I am understanding it correctly.

If I have code similar to this:

while(number > 0)
{
    sum += number;
    number /= 2;
}

I believe that my Big-O runtime would be O(N) since the loop would run, by my calculations, for O(N/2) and then each of the statements in the loop would run for O(1) so we end up with O(N ^ 1/2) + O(1) + O(1) so O(N ^ 1/2 + 1 + 1) and we drop the constants leaving us with O(N ^ 1/2)  or O(sqrt N) complexity... I believe this would be log(n) Big-O runtime but just wanted some clarification and verification to make sure I understood this concept. I have read up quite a bit on this topic and watched videos - I just couldn't find a similar enough example anywhere and the 'number /= 2' is what is throwing me off.

For the record, it was a homework question that got me thinking about this.

Body:
Mathematically speaking, your algorithm would never even terminate assuming that number can bear a decimal component.  This is because no matter how many times you divide a positive number, you will always be left with some number greater than zero.  In practice, a computer floating point number would eventually hit zero due to rounding error.

I would like to answer your question with a slight change:

while (number > 1) {
    sum += number;
    number /= 2;
}

The running time for this algorithm is actually log_2(N) (i.e. log base 2 of N).  To see why, consider an input number of 16.  Then the following iterations would take place, with corresponding values of number:

iteration # | number
1           | 16 = 2^4
2           | 8  = 2^3
3           | 4  = 2^2
4           | 2  = 2^1
5           | 1  = 2^0

You can convince yourself that the exponent on the base 2 determines the number of iterations.  We access that value by taking the log base 2, hence the running time is O(log_2(N)).


问:
Showing more text with jquery
I am looking for a way to show more or less text. I want to show 600 characters by default and if show more is clicked it will show 600 more characters and then if clicked again shows 600 more until there are no more characters. I also would like a show less button to collapse the text back to its default 600 characters. I have pages with 5000+ words and this would make reading much easier and make it look nicer. Right now I am using this to show the first 600 chars and when show more is clicked it expands all the way.

```<code>$(document).ready(function() {
var showChar = 600;
var ellipsestext = "...";
var moretext = "View more";
var lesstext = "View less";
$('.more').each(function() {
    var content = $(this).html();

    if(content.length > showChar) {

        var c = content.substr(0, showChar);
        var h = content.substr(showChar-1, content.length - showChar);

        var html = c + '<span class="moreelipses">'+ellipsestext+'</span> <span class="morecontent"><span>' + h + '  </span><a rel="nofollow" href="" class="morelink">'+moretext+'</a></span>';

        $(this).html(html);
    }

});

$(".morelink").click(function(){
    if($(this).hasClass("less")) {
        $(this).removeClass("less");
        $(this).html(moretext);
    } else {
        $(this).addClass("less");
        $(this).html(lesstext);
    }
    $(this).parent().prev().toggle();
    $(this).prev().toggle();
    return false;
});
});
</code>```

Could somebody please edit this code to work like this or help me to achieve this any other way? I would really like to make my pages more presentable and readable and this would definitely do the trick. Thanks.

答:
Why do all this when you can do more or less what you want by putting the text in a div that has scrollbars. You don't need any javascript at all, just style it using CSS e.g.

```<code><div style="height: 6em; overflow: auto; line-height: 1.5em">
    <p>
        This is a huge load of text<br>
        line 2<br>
        line 3<br>
        line 4<br>
        ...etc....
    </p>
</div>
</code>```

Just set "height" (6em in the example above) to 1.5 times number of lines you want to display at any one time (e.g. for approximately 40 lines set "height: 60em").

This way you also handle the fact that the 600th character will almost certainly be in the middle of a word!

Regards
       Neil

Title: Showing more text with jquery

Body:
I am looking for a way to show more or less text. I want to show 600 characters by default and if show more is clicked it will show 600 more characters and then if clicked again shows 600 more until there are no more characters. I also would like a show less button to collapse the text back to its default 600 characters. I have pages with 5000+ words and this would make reading much easier and make it look nicer. Right now I am using this to show the first 600 chars and when show more is clicked it expands all the way.

$(document).ready(function() {
var showChar = 600;
var ellipsestext = "...";
var moretext = "View more";
var lesstext = "View less";
$('.more').each(function() {
    var content = $(this).html();

    if(content.length > showChar) {

        var c = content.substr(0, showChar);
        var h = content.substr(showChar-1, content.length - showChar);

        var html = c + ''+ellipsestext+' ' + h + '  '+moretext+'';

        $(this).html(html);
    }

});

$(".morelink").click(function(){
    if($(this).hasClass("less")) {
        $(this).removeClass("less");
        $(this).html(moretext);
    } else {
        $(this).addClass("less");
        $(this).html(lesstext);
    }
    $(this).parent().prev().toggle();
    $(this).prev().toggle();
    return false;
});
});

Could somebody please edit this code to work like this or help me to achieve this any other way? I would really like to make my pages more presentable and readable and this would definitely do the trick. Thanks.

Body:
Why do all this when you can do more or less what you want by putting the text in a div that has scrollbars. You don't need any javascript at all, just style it using CSS e.g.

<div style="height: 6em; overflow: auto; line-height: 1.5em">
    <p>
        This is a huge load of text<br>
        line 2<br>
        line 3<br>
        line 4<br>
        ...etc....
    </p>
</div>

Just set "height" (6em in the example above) to 1.5 times number of lines you want to display at any one time (e.g. for approximately 40 lines set "height: 60em").

This way you also handle the fact that the 600th character will almost certainly be in the middle of a word!

Regards
       Neil


问:
Send array to function, multiply each variable by 2, return array c#
i am tryin to make a function that takes an array and multiples each of its values by 2, then returns each multiplied value in a new array, so I can write out the individual values of the original array and the new multiplied one.
IE, an array with 2, 4, and 6, I want to make a function that takes it, then multiplies each value by 2, then return a new array that has 4, 6, and 8.

Here is my function

```<code>public static int[] ArrayFunction(int[] array)
{
     int multiply = 0;
     foreach(int i in array)
     {
         multiply = i*2;
     }
    int[] multiArray = new int[] {multiply}
return multiArray;
}
</code>```

I'm just trying to return an array with each value of the original array multiplied by 2.

答:
You can achieve the desired result by using the below code.</p>

```<code>public static int[] ArrayFunction(int[] array)
{
     int multiply = 0;
     int count= 0;
      int[] multiArray = new int[array.Length];
     foreach(int i in array)
     {
         multiply = i*2;
         multiArray[count]=multiply;
         count++;
     }
     return multiArray;
}
</code>```

Body:
i am tryin to make a function that takes an array and multiples each of its values by 2, then returns each multiplied value in a new array, so I can write out the individual values of the original array and the new multiplied one.
IE, an array with 2, 4, and 6, I want to make a function that takes it, then multiplies each value by 2, then return a new array that has 4, 6, and 8.

Here is my function

public static int[] ArrayFunction(int[] array)
{
     int multiply = 0;
     foreach(int i in array)
     {
         multiply = i*2;
     }
    int[] multiArray = new int[] {multiply}
return multiArray;
}

I'm just trying to return an array with each value of the original array multiplied by 2.

Body:
You can achieve the desired result by using the below code.

public static int[] ArrayFunction(int[] array)
{
     int multiply = 0;
     int count= 0;
      int[] multiArray = new int[array.Length];
     foreach(int i in array)
     {
         multiply = i*2;
         multiArray[count]=multiply;
         count++;
     }
     return multiArray;
}


问:
Apache Thrift make err with libthrift-0.10.0.dylib
I am using macOS 10.12.3.
Yesterday I successfully installed thrift but it could not work correctly with python. So I re-make it today and get this err. Could someone tell me what's wrong. Thx</p>

```<code>Making all in perl
../../compiler/cpp/thrift --gen perl ../../test/ThriftTest.thrift
dyld: Symbol not found: _GENERAL_NAME_free
  Referenced from: /Users/sara/thrift-0.10.0/lib/cpp/.libs/libthrift-0.10.0.dylib
  Expected in: flat namespace
 in /Users/sara/thrift-0.10.0/lib/cpp/.libs/libthrift-0.10.0.dylib
make[3]: *** [gen-perl/ThriftTest/Constants.pm] Abort trap: 6
make[2]: *** [all-recursive] Error 1
make[1]: *** [all-recursive] Error 1
make: *** [all] Error 2
</code>```

答:
I have had the same problem, but now I solve it. when you had the error, I think /usr/local/bin/thrift is already existed in you macOS. Then run

    $ sudo chmod -R 777 /usr/local/include/thrift/
    $ brew link --overwrite thrift

then you will find the command /usr/local/bin/thrift is ok.

Body:
I am using macOS 10.12.3.
Yesterday I successfully installed thrift but it could not work correctly with python. So I re-make it today and get this err. Could someone tell me what's wrong. Thx

Making all in perl
../../compiler/cpp/thrift --gen perl ../../test/ThriftTest.thrift
dyld: Symbol not found: _GENERAL_NAME_free
  Referenced from: /Users/sara/thrift-0.10.0/lib/cpp/.libs/libthrift-0.10.0.dylib
  Expected in: flat namespace
 in /Users/sara/thrift-0.10.0/lib/cpp/.libs/libthrift-0.10.0.dylib
make[3]: *** [gen-perl/ThriftTest/Constants.pm] Abort trap: 6
make[2]: *** [all-recursive] Error 1
make[1]: *** [all-recursive] Error 1
make: *** [all] Error 2


问:
Not able to load ui-view even when the state change
I am using Angular UI Router. Please find the code below.

index.html

```<code><html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.6/angular.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/1.0.3/angular-ui-router.min.js"></script>
    <script src="../../Scripts/AngularControllers/LoginHomeControllers/RouteMainController.js"></script>
    <script src="../../Scripts/AngularControllers/LoginHomeControllers/LoginController.js"></script>
</head>
<body>
    <div ui-view="mainview"></div>
</body>
</html>
</code>```

RouteMainController.js

```<code>var app = angular.module("appHome", ['ui.router']);

app.config(function ($stateProvider, $urlRouterProvider) {
    $urlRouterProvider.otherwise('/login');
    $stateProvider
        .state('introduction', {
            url: '/',
            views: {
                'mainview':
                {
                    templateUrl: 'Login.html',
                    controller: 'ctrlLogin'
                }
            }
        })
        .state('login', {
            url: '/login',
            views: {
                'mainview':
                {
                    templateUrl: 'Login.html',
                    controller: 'ctrlLogin'
                }
            }
        })
        .state('home', {
            url: '/home',
            views: {
                'mainview':
                {
                    templateUrl: 'Home.html',
                }
            }
        })
        .state('home.requestsummary', {
            url: '/requestsummary',
            views: {
                'homedetailview':
                {
                    templateUrl: 'Test1.html',
                }
            }
        })
        .state('home.requestsummary.requestdetail', {
            url: '/requestdetail',
            views: {
                'homedetailview':
                {
                    template: "'<h3>Foo</h3>'"
                }
            }
        })
});
</code>```

Login.html

```<code><div>
    <button id="btnAdd" type="submit"  ng-click="Login()">Login</button>
</div>
</code>```

LoginController.js

```<code>var myApp = angular.module('appHome');
myApp.controller("ctrlLogin", ['$scope', '$location', function ($scope, $location) {
    $scope.Login = function () {
        window.location.href = '#!home/requestsummary';
    }
}]);
</code>```

Home.html

```<code><!--Sample Code for displaying Menu Tab and corresponding link-->
<li>
    <a href="#">Employees <span class="caret"></span></a>
    <ul class="dropdown-menu sub-menu">
        <li><a ui-sref=".employeeadd">Add Employee Record</a></li>
    </ul>
</li>

<div ui-view="homedetailview"></div>
</code>```

Test1.html

```<code><a ui-sref=".requestdetail">Hello World</a>
</code>```

I am able to Login successfully and getting the menu tab with "Hello World" Link. I want to display Menu Tab always and change the below text dynamically.

My problem is that whenever I clicked on "Hello World" Link , I am expecting Foo to appear in place of "Hello World" Link but it is not working.
Even it is changing states(url) but it is not loading the actual view.

Please help me on this.

答:
There is a structural problem with your code. The state requestdetail is a child state of home.requestsummary, and thus, it requires a ui-view in the template of home.requestsummary state, to which it can bind the HTML.

As per your code, there is no ui-view in the Test1.html. So, just to be sure that there is no other problem, you can try adding a ui-view in Test1.html, and change the state config as follows:

```<code><!-- Test.html -->
<a ui-sref=".requestdetail">Hello World</a>
<div ui-view></div>

// RouteMainController.js
...
.state('home.requestsummary.requestdetail', {
  url: '/requestdetail',
  template: "'<h3>Foo</h3>'
})
</code>```

After this change, just check if the heading Foo appears in the view. If it appears, then everything is fine with your code. Now, the second part is to load the heading Foo at the same place where the link of Hello world is shown.

To do that, you need to change the view target, because homedetailview exists in Home.html, which is the parent state of home.requestsummary. So, you need to change the state configuration for home.requestsummary.requestdetail as follows:

```<code>// RouteMainController.js
...
.state('home.requestsummary.requestdetail', {
  url: '/requestdetail',
  views: {
    'homedetailview@home': {
      template: "'<h3>Foo</h3>'
    }
  }
})
</code>```

This will absolutely target the homedetailview in the state home, and your template for home.requestsummary.requestdetail will be shown there.

Body:
I am using Angular UI Router. Please find the code below.

index.html

RouteMainController.js

var app = angular.module("appHome", ['ui.router']);

app.config(function ($stateProvider, $urlRouterProvider) {
    $urlRouterProvider.otherwise('/login');
    $stateProvider
        .state('introduction', {
            url: '/',
            views: {
                'mainview':
                {
                    templateUrl: 'Login.html',
                    controller: 'ctrlLogin'
                }
            }
        })
        .state('login', {
            url: '/login',
            views: {
                'mainview':
                {
                    templateUrl: 'Login.html',
                    controller: 'ctrlLogin'
                }
            }
        })
        .state('home', {
            url: '/home',
            views: {
                'mainview':
                {
                    templateUrl: 'Home.html',
                }
            }
        })
        .state('home.requestsummary', {
            url: '/requestsummary',
            views: {
                'homedetailview':
                {
                    templateUrl: 'Test1.html',
                }
            }
        })
        .state('home.requestsummary.requestdetail', {
            url: '/requestdetail',
            views: {
                'homedetailview':
                {
                    template: "'
Foo
'"
                }
            }
        })
});

Login.html

    <button id="btnAdd" type="submit"  ng-click="Login()">Login</button>

LoginController.js

var myApp = angular.module('appHome');
myApp.controller("ctrlLogin", ['$scope', '$location', function ($scope, $location) {
    $scope.Login = function () {
        window.location.href = '#!home/requestsummary';
    }
}]);

Home.html

    Employees

Add Employee Record

Test1.html

Hello World

I am able to Login successfully and getting the menu tab with "Hello World" Link. I want to display Menu Tab always and change the below text dynamically.

My problem is that whenever I clicked on "Hello World" Link , I am expecting Foo to appear in place of "Hello World" Link but it is not working.
Even it is changing states(url) but it is not loading the actual view.

Please help me on this.

Body:
There is a structural problem with your code. The state requestdetail is a child state of home.requestsummary, and thus, it requires a ui-view in the template of home.requestsummary state, to which it can bind the HTML.

As per your code, there is no ui-view in the Test1.html. So, just to be sure that there is no other problem, you can try adding a ui-view in Test1.html, and change the state config as follows:

<!-- Test.html -->
<a ui-sref=".requestdetail">Hello World</a>
<div ui-view></div>

// RouteMainController.js
...
.state('home.requestsummary.requestdetail', {
  url: '/requestdetail',
  template: "'<h3>Foo</h3>'
})

After this change, just check if the heading Foo appears in the view. If it appears, then everything is fine with your code. Now, the second part is to load the heading Foo at the same place where the link of Hello world is shown.

To do that, you need to change the view target, because homedetailview exists in Home.html, which is the parent state of home.requestsummary. So, you need to change the state configuration for home.requestsummary.requestdetail as follows:

// RouteMainController.js
...
.state('home.requestsummary.requestdetail', {
  url: '/requestdetail',
  views: {
    'homedetailview@home': {
      template: "'<h3>Foo</h3>'
    }
  }
})

This will absolutely target the homedetailview in the state home, and your template for home.requestsummary.requestdetail will be shown there.


问:
Which one to use: Java Swing or GTK+ for GNOME desktop application?
I am considering developing a GNOME desktop application with a graphical user interface. I know GTK+ is the first choice, especially when developing for the GNOME environment. End users also consider GTK+ as the first choice for applications they use. I am, however, considering future improvements: what if my application will need a port to another environments or OS like KDE or Mac or Windows? Which is the best way to go: Java Swing (because it's platform independent) or GTK+?</p>

答: Use GTK+. It's available for Windows as well if you ever do want to port it, and integrates infinitely much better with gnome.</p>


问:
How do I concatenate cell values and text together using Excel VBA?
I have a repetitive task I'd like to automate instead of using the =Concatenate function all the time. Here's my code so far:

```<code>Cells(2, 5).Value = Cells(2, 1).Value&" - "&Cells(2, 2).Value
</code>```

Unfortunately this results in the "Compile error: Expected: end of statement" error, which highlights the " - ". How can I sandwich that text, " - ", between those two values?

答:
One suggestion for whom need:</p>

```<code>Private Sub CommandButton1_Click()
Dim i As Long
Dim j As Long

Dim x As String

i = 1
j = Range("max").Value
x = Cells(i, 2)

For i = 2 To j

x = x & " - " & Cells(i, 2)

Next i

'MsgBox (x)

Range("d1").Value = x

i = 0

End Sub
</code>```

Body:
I have a repetitive task I'd like to automate instead of using the =Concatenate function all the time. Here's my code so far:

Cells(2, 5).Value = Cells(2, 1).Value&" - "&Cells(2, 2).Value

Unfortunately this results in the "Compile error: Expected: end of statement" error, which highlights the " - ". How can I sandwich that text, " - ", between those two values?

Body:
One suggestion for whom need:

Private Sub CommandButton1_Click()
Dim i As Long
Dim j As Long

Dim x As String

i = 1
j = Range("max").Value
x = Cells(i, 2)

For i = 2 To j

x = x & " - " & Cells(i, 2)

Next i

'MsgBox (x)

Range("d1").Value = x

i = 0

End Sub


问:
Applying multiple classes to ReactJS component
I need to apply multiple classes to a React component without installing anything extra. Is that possible?

```<code><Component id="test1" className="blue-text kps hide-on-small-and-down" />
</code>```

I also tried

```<code><Component id="test1" className={`blue-text kps hide-on-small-and-down`} />
</code>```

But nothing works.

I have been searching for hours but did not find anything that does not require extra installations.
Please do not downvote without explaining why.
Thank you

答:
I see a wrong usage of className in your code. className stands for standard class attribute in standard html. Quoting the documentation.

"To specify a CSS class, use the className attribute. This applies to all regular DOM and SVG elements like , , and others."

It is for regular DOM and SVG elements where you can use className attribute.

Example Fiddle

```<code><div className="one two three">
    This is the {this.props.name}
</div>
</code>```

Example usage.

Adding another point I don't think using className to pass props down to child elements is a good idea since the className is serving a purpose here.

Body:
I need to apply multiple classes to a React component without installing anything extra. Is that possible?

<Component id="test1" className="blue-text kps hide-on-small-and-down" />

I also tried

<Component id="test1" className={`blue-text kps hide-on-small-and-down`} />

But nothing works.

I have been searching for hours but did not find anything that does not require extra installations.
Please do not downvote without explaining why.
Thank you

Body:
I see a wrong usage of className in your code. className stands for standard class attribute in standard html. Quoting the documentation.

"To specify a CSS class, use the className attribute. This applies to all regular DOM and SVG elements like , , and others."

It is for regular DOM and SVG elements where you can use className attribute.

Example Fiddle

<div className="one two three">
    This is the {this.props.name}
</div>

Example usage.

Adding another point I don't think using className to pass props down to child elements is a good idea since the className is serving a purpose here.


问:
What is the difference between intermediate and terminal operations?
can someone tell me What is the difference between intermediate and terminal operations for Stream?

Stream operations are combined into pipelines to process streams. All operations are either intermediate or terminal ..means?.

答:
You probably noticed that when you define a stream, the methods aren't just called one by one on the whole stream, but rather they do something on each element from the stream. To be able to run these streams in parallel, for every element, there is basically a whole pipeline.

In order to create multiple pipelines, Java 8+ uses the builder pattern. With every intermediate step you add a filter or converter to the stack. In order to tell Java to generate pipelines from that stack of filters, you use a terminating step. That last step combines all the different pipelines. Usually it just returns the values in a defined format, e.g. a list, but it can also run a function once for each element, or reduce the results to a boolean or a number.


问:
How to send a HTTP-delete with a body in retrofit?
When I try to create a delete method:

```<code>public interface ImageService {
    @DELETE("api/v1/attachment")
    Call<BaseResponse> delete(@Body DeleteModel deleteModel);
}
</code>```

I get the error which basically boils down to these lines from the stacktrace:

```<code>E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Failure delivering result
java.lang.IllegalArgumentException: Non-body HTTP method cannot contain @Body.
Caused by: java.lang.IllegalArgumentException: Non-body HTTP method cannot contain @Body.
</code>```

How can I add a body to a delete method ?

I have searched here but found 3 not answers and nothing using retrofit.

答:
Here is my version</p>

```<code>@HTTP(method = "DELETE", path = "{login}", hasBody = true)
Call<ResponseBody> getData(@Path("login") String postfix, @Body Map<String, Object> options);
</code>```

Body:
When I try to create a delete method:

public interface ImageService {
    @DELETE("api/v1/attachment")
    Call<BaseResponse> delete(@Body DeleteModel deleteModel);
}

I get the error which basically boils down to these lines from the stacktrace:

E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Failure delivering result
java.lang.IllegalArgumentException: Non-body HTTP method cannot contain @Body.
Caused by: java.lang.IllegalArgumentException: Non-body HTTP method cannot contain @Body.

How can I add a body to a delete method ?

I have searched here but found 3 not answers and nothing using retrofit.

Body:
Here is my version

@HTTP(method = "DELETE", path = "{login}", hasBody = true)
Call<ResponseBody> getData(@Path("login") String postfix, @Body Map<String, Object> options);


问:
Clear MySQL General Log Table, Is It Safe?
I server I am working on, general mysql log table is taking near 200GB space, which is huge. So, I am planning to clear it up with:

```<code>TRUNCATE table mysql.general_log
</code>```

Is it ok? Will it cause any issue? I am concerned as the server is live and big application. Thanks.

答:
It will definitely cause a problem unless it is disabled and then you truncate. If you truncate while it is enabled. Truncate will lock the table if table is huge, since mysql.general_log engine is either CSV or MyISAM ,meanwhile newly made entries will try to be written in general log table causing a lock.  So for safety do like this</p>
```<code>mysql> SET GLOBAL general_log=OFF;
mysql> TRUNCATE table mysql.general_log;
mysql> SET GLOBAL general_log=ON;
</code>```

Body:
I server I am working on, general mysql log table is taking near 200GB space, which is huge. So, I am planning to clear it up with:

TRUNCATE table mysql.general_log

Is it ok? Will it cause any issue? I am concerned as the server is live and big application. Thanks.

Body:
It will definitely cause a problem unless it is disabled and then you truncate. If you truncate while it is enabled. Truncate will lock the table if table is huge, since mysql.general_log engine is either CSV or MyISAM ,meanwhile newly made entries will try to be written in general log table causing a lock.  So for safety do like this

mysql> SET GLOBAL general_log=OFF;
mysql> TRUNCATE table mysql.general_log;
mysql> SET GLOBAL general_log=ON;

ContentLicense: CC BY-SA 4.0


问:
NoReverseMatch error in rendering Django
Below is my views.py. After the POST, user gets a success page showing the 5 Items. At the same time I also want to show environment to the user. So I did something like below (passed environment as an argument). I get that while the redirect happens, it tries to find something like success and the environment argument match which it is not able to get. Probably I need
 right regular expression to handle this and I am not sure how to handle this.

```<code>def order_create(request):
    cart = ItemObject.objects.all()

    if request.method == 'POST':
        ...
            environment = envi_dict1.difference(item_dict1)
            return HttpResponseRedirect(reverse('success', {'environment': environment}))

    else:
        form = ItemObjectCreateForm()
    return render(request,
                  'index.html',
                  {'form': form})

def successView(request):

    return render(request, 'success.html', {'items': ItemObject.objects.filter(gp_code='Unknown')[:5]})
</code>```

urls.py

```<code>urlpatterns = [

    url(r'^admin/', admin.site.urls),
    url(r'^export_action/', include("export_action.urls", namespace="export_action")),
    url('^business-logic/', include('business_logic.urls')),
    url('^index/', views.order_create),
    url(r'^success/', views.successView, name='success')
]
</code>```

The error I am getting is this

```<code>NoReverseMatch at /index/
Reverse for 'success' with keyword arguments '{u'environment': set([u'Test1'])}' not found. 1 pattern(s) tried: ['success/']
</code>```

答: I used Sandeep's idea of storing the variables in session. Under views.py I had request.session['environment'] = environment and in success.html, I use request.session.environment

Body:
Below is my views.py. After the POST, user gets a success page showing the 5 Items. At the same time I also want to show environment to the user. So I did something like below (passed environment as an argument). I get that while the redirect happens, it tries to find something like success and the environment argument match which it is not able to get. Probably I need
 right regular expression to handle this and I am not sure how to handle this.

def order_create(request):
    cart = ItemObject.objects.all()

    if request.method == 'POST':
        ...
            environment = envi_dict1.difference(item_dict1)
            return HttpResponseRedirect(reverse('success', {'environment': environment}))

    else:
        form = ItemObjectCreateForm()
    return render(request,
                  'index.html',
                  {'form': form})

def successView(request):

    return render(request, 'success.html', {'items': ItemObject.objects.filter(gp_code='Unknown')[:5]})

urls.py

urlpatterns = [

    url(r'^admin/', admin.site.urls),
    url(r'^export_action/', include("export_action.urls", namespace="export_action")),
    url('^business-logic/', include('business_logic.urls')),
    url('^index/', views.order_create),
    url(r'^success/', views.successView, name='success')
]

The error I am getting is this

NoReverseMatch at /index/
Reverse for 'success' with keyword arguments '{u'environment': set([u'Test1'])}' not found. 1 pattern(s) tried: ['success/']


问:
how to Change image height and width in google maps icon
In this code i m displaying the multi-pointers in my google map but the image dosnt work properly    </p>

```<code><script type="text/javascript">
       var locations = <?php print_r(json_encode($deliverer)) ?>;
       var mymap = new GMaps({
         el: '#mymap',
         lat: 30.375321,
         lng: 69.345116,
         zoom:6
       });

       $.each( locations, function( index, value ){
            mymap.addMarker({
              lat: value.latitude,
              lng: value.longitude,

>  **icon: "car_marker.png";**

    icon: "car_marker.png";   ,,,,this is my image i just want to display in google map ,so how can i change the height and width in it ???
            });
      });
     </script>
</code>```

答:
You can do like this, make and object of map marker icon, with their configurations,

```<code>      var ico = '<?php echo asset("assets/images/map_marker.png"); ?>';
        var image = {
          url: ico,
          size: new google.maps.Size(71, 71),
          origin: new google.maps.Point(0, 0),
          anchor: new google.maps.Point(17, 34),
          scaledSize: new google.maps.Size(50, 50)
        };
</code>```

Its make an marker icon of size passed into it you can change as per your need and see what happen.

Then you can pass this to marker like this,

```<code>var marker = new google.maps.Marker({
            position: {lat: location.lat + (Math.random() -.5) / 1500, lng: location.lon + (Math.random() -.5) / 1500 },
            title: location.title,
            icon:image,
        });
</code>```

Thank you.
I hope it helps.

Body:
You can do like this, make and object of map marker icon, with their configurations,

      var ico = '<?php echo asset("assets/images/map_marker.png"); ?>';
        var image = {
          url: ico,
          size: new google.maps.Size(71, 71),
          origin: new google.maps.Point(0, 0),
          anchor: new google.maps.Point(17, 34),
          scaledSize: new google.maps.Size(50, 50)
        };

Its make an marker icon of size passed into it you can change as per your need and see what happen.

Then you can pass this to marker like this,

var marker = new google.maps.Marker({
            position: {lat: location.lat + (Math.random() -.5) / 1500, lng: location.lon + (Math.random() -.5) / 1500 },
            title: location.title,
            icon:image,
        });

Thank you.
I hope it helps.


问:
nullable fields in swagger on node.js
I've spent a bunch of time trying to find a solution for creating swagger docs in Node.JS. The main library is swagger-node, in which you create a swagger yaml file and then add your controllers to it. It automatically provides swagger ui docs in your app and does validation on the request & response against the models you specify in your yaml.

This is neat, however I have a requirement that some fields I want to explicitly be able to return or accept null as a value, for instance:

```<code>{
  id: 123,
  description: "string",
  date_sent: null
}
</code>```

I don't want to delete the date_sent key, I want to explicitly state it as null.

The swagger spec does not support anyOf which is how JSON schema normally does this I believe.

I'm wondering if there's a workaround? Perhaps some library available for node that has a x-nullable vendor specific flag you can add, or some way of specifying that my not-required fields should all be nullable.

Am I going to have to write something myself that takes my swagger file and then modifies it before the validator middleware runs, or is there some workaround someone can suggest?

答:
Instead of add null in type property, you can use default property instead.

Swagger.json property definition example:

```<code>"due_date": {
  "type": "string",
  "description": "Due date",
  "default": "null"
},
</code>```

It's a valid Swagger type definition, and still appears as expected in Swagger UI.

Title: nullable fields in swagger on node.js

Body:
I've spent a bunch of time trying to find a solution for creating swagger docs in Node.JS. The main library is swagger-node, in which you create a swagger yaml file and then add your controllers to it. It automatically provides swagger ui docs in your app and does validation on the request & response against the models you specify in your yaml.

This is neat, however I have a requirement that some fields I want to explicitly be able to return or accept null as a value, for instance:

{
  id: 123,
  description: "string",
  date_sent: null
}

I don't want to delete the date_sent key, I want to explicitly state it as null.

The swagger spec does not support anyOf which is how JSON schema normally does this I believe.

I'm wondering if there's a workaround? Perhaps some library available for node that has a x-nullable vendor specific flag you can add, or some way of specifying that my not-required fields should all be nullable.

Am I going to have to write something myself that takes my swagger file and then modifies it before the validator middleware runs, or is there some workaround someone can suggest?

Body:
Instead of add null in type property, you can use default property instead.

Swagger.json property definition example:

"due_date": {
  "type": "string",
  "description": "Due date",
  "default": "null"
},

It's a valid Swagger type definition, and still appears as expected in Swagger UI.


问:
Get File Extension C#
I have a dropdown with list of file names. When a file name is selected in the dropdown I do the following

```<code>string filename = ddl.SelectedItem.Text;
string path = "F:\\WorkingCopy\\files\\" + filename +".docx";
DownloadFile(path,filename);
</code>```

In the file folder files may contain any extension . Since i have hard coded ".docx" in string path everything works fine. But I need to get the extension of the file name with the ddl.SelectedItem.Text alone. Can you tell me how to do this?

Things  I have
1.) File name without extension in

```<code>string filename = ddl.SelectedItem.Text;
</code>```

2.) Path where the file is located

```<code>string path = "F:\\WorkingCopy\\files\\" + filename
</code>```

I am trying to get the file extension with these . Can any one suggest on this?

答:
you can achieve that with followed by line

```<code> try
 {
    var extensions = new List<string>();
    var files = Directory.GetFiles("F:\\WorkingCopy\\files\\", filename + ".*", System.IO.SearchOption.TopDirectoryOnly);

    foreach (var tmpfile in files)
       extensions.Add(Path.GetExtension(tmpfile));

}
catch (Exception ex)
{
            throw ex;
}
</code>```

will this help you?

Title: Get File Extension C#

Body:
I have a dropdown with list of file names. When a file name is selected in the dropdown I do the following

string filename = ddl.SelectedItem.Text;
string path = "F:\\WorkingCopy\\files\\" + filename +".docx";
DownloadFile(path,filename);

In the file folder files may contain any extension . Since i have hard coded ".docx" in string path everything works fine. But I need to get the extension of the file name with the ddl.SelectedItem.Text alone. Can you tell me how to do this?

Things  I have
1.) File name without extension in

string filename = ddl.SelectedItem.Text;

2.) Path where the file is located

string path = "F:\\WorkingCopy\\files\\" + filename

I am trying to get the file extension with these . Can any one suggest on this?

Body:
you can achieve that with followed by line

 try
 {
    var extensions = new List<string>();
    var files = Directory.GetFiles("F:\\WorkingCopy\\files\\", filename + ".*", System.IO.SearchOption.TopDirectoryOnly);

    foreach (var tmpfile in files)
       extensions.Add(Path.GetExtension(tmpfile));

}
catch (Exception ex)
{
            throw ex;
}

will this help you?