问:
How to add dynamic base url in retrofit module with dagger2
I am using dagger2 for my application. I have one module which provides some dependencies like Retrofit, Gson etc.

NetModule.java

```<code>@Module
public class NetModule {

    private String mBaseUrl;

    public NetModule(String baseUrl) {
        this.mBaseUrl = baseUrl;
    }

    @Provides
    @Singleton
    SharedPreferences providesSharedPreferences(Application application) {
        return PreferenceManager.getDefaultSharedPreferences(application);
    }

    @Provides
    @Singleton
    Cache provideOkHttpCache(Application application) {
        int cacheSize = 10 * 1024 * 1024; // 10 MiB
        Cache cache = new Cache(application.getCacheDir(), cacheSize);
        return cache;
    }

    @Provides
    @Singleton
    Gson provideGson() {
        GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
        return gsonBuilder.create();
    }

    @Provides
    @Singleton
    OkHttpClient provideOkHttpClient(Cache cache) {
        OkHttpClient okHttpClient = new OkHttpClient();
        okHttpClient.newBuilder()
                //.addNetworkInterceptor(REWRITE_CACHE_CONTROL_INTERCEPTOR)
                .cache(cache)
                .build();
        return okHttpClient;
    }

    @Provides
    @Singleton
    Retrofit provideRetrofit(Gson gson, OkHttpClient okHttpClient) {
        Retrofit retrofit = new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create(gson))
                .baseUrl(mBaseUrl)
                .client(okHttpClient)
                .build();
        return retrofit;
    }
}
</code>```

NetComponent.java

```<code>@Singleton
@Component(modules = {AppModule.class, NetModule.class, Validator.class})
public interface NetComponent {
    void inject(AuthenticationActivity authenticationActivity);
    void inject(PaymentActivity paymentActivity);
}
</code>```

AppApplication.java

```<code>@Override
public void onCreate() {
    super.onCreate();

    mNetComponent = DaggerNetComponent.builder()
            .appModule(new AppModule(this))
            .netModule(new NetModule("https://corporateapiprojectwar.mybluemix.net/corporate_banking/mybank/"))
            .build();

}
</code>```

This approach was working until I had only one base url for my complete application. Now I have different base Url for AuthenticationActivity and PaymentActivity so I can not send Url in constructor of NetModule in onCreate of Application

Can anyone help me how to add dynamic base Url of retrofit using dagger2.

答:
You can use @Named annotation Dagger2 user guide (see 'Qualifiers' section'):

In your NetModule.java:

```<code>@Provides
@Singleton
@Named("authRetrofit")
public Retrofit provideAuthRetrofit() {
  // setup retrofit for authentication
  return retrofit;
}

@Provides
@Singleton
@Named("paymentRetrofit")
public Retrofit providePaymentRetrofit() {
  // setup retrofit for payments
  return retrofit;
}
</code>```

In your AuthenticationActivity:

```<code>@Inject
@Named("authRetrofit")
Retrofit retrofit;
</code>```

And finally in your PaymentActivity.java:

```<code>@Inject
@Named("paymentRetrofit")
Retrofit retrofit;
</code>```

Then dagger shall automatically inject Retrofit configured for payments into PaymentActivity and Retrofit configured for authentication into AuthenticationActivity

Body:
I am using dagger2 for my application. I have one module which provides some dependencies like Retrofit, Gson etc.

NetModule.java

@Module
public class NetModule {

    private String mBaseUrl;

    public NetModule(String baseUrl) {
        this.mBaseUrl = baseUrl;
    }

    @Provides
    @Singleton
    SharedPreferences providesSharedPreferences(Application application) {
        return PreferenceManager.getDefaultSharedPreferences(application);
    }

    @Provides
    @Singleton
    Cache provideOkHttpCache(Application application) {
        int cacheSize = 10 * 1024 * 1024; // 10 MiB
        Cache cache = new Cache(application.getCacheDir(), cacheSize);
        return cache;
    }

    @Provides
    @Singleton
    Gson provideGson() {
        GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
        return gsonBuilder.create();
    }

    @Provides
    @Singleton
    OkHttpClient provideOkHttpClient(Cache cache) {
        OkHttpClient okHttpClient = new OkHttpClient();
        okHttpClient.newBuilder()
                //.addNetworkInterceptor(REWRITE_CACHE_CONTROL_INTERCEPTOR)
                .cache(cache)
                .build();
        return okHttpClient;
    }

    @Provides
    @Singleton
    Retrofit provideRetrofit(Gson gson, OkHttpClient okHttpClient) {
        Retrofit retrofit = new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create(gson))
                .baseUrl(mBaseUrl)
                .client(okHttpClient)
                .build();
        return retrofit;
    }
}

NetComponent.java

@Singleton
@Component(modules = {AppModule.class, NetModule.class, Validator.class})
public interface NetComponent {
    void inject(AuthenticationActivity authenticationActivity);
    void inject(PaymentActivity paymentActivity);
}

AppApplication.java

@Override
public void onCreate() {
    super.onCreate();

    mNetComponent = DaggerNetComponent.builder()
            .appModule(new AppModule(this))
            .netModule(new NetModule("https://corporateapiprojectwar.mybluemix.net/corporate_banking/mybank/"))
            .build();

}

This approach was working until I had only one base url for my complete application. Now I have different base Url for AuthenticationActivity and PaymentActivity so I can not send Url in constructor of NetModule in onCreate of Application

Can anyone help me how to add dynamic base Url of retrofit using dagger2.

Body:
You can use @Named annotation Dagger2 user guide (see 'Qualifiers' section'):

In your NetModule.java:

@Provides
@Singleton
@Named("authRetrofit")
public Retrofit provideAuthRetrofit() {
  // setup retrofit for authentication
  return retrofit;
}

@Provides
@Singleton
@Named("paymentRetrofit")
public Retrofit providePaymentRetrofit() {
  // setup retrofit for payments
  return retrofit;
}

In your AuthenticationActivity:

@Inject
@Named("authRetrofit")
Retrofit retrofit;

And finally in your PaymentActivity.java:

@Inject
@Named("paymentRetrofit")
Retrofit retrofit;

Then dagger shall automatically inject Retrofit configured for payments into PaymentActivity and Retrofit configured for authentication into AuthenticationActivity


来源: stackexchange

问:
ReceivePaymentAddRq in QBXML - Object TxnID specified in request cannot be found
I'm working in QBXML and trying to apply a payment to specific invoice in a ReceivePaymentAddRq.  I'm getting the, apparently quite common, "Object TxnID specified in the request cannot be found".   Most other forums threads on this topic are resolved once the ARAccountRef field is added to the request, that didn't seem to make a difference for me.

I've queried the invoice for TxnID  68B4-1290718970 and verified the following:

My request's ARAccountRef ListID matches what is in the QueryRet

My request's CustomerRef ListID matches what is in the QueryRet

My XML request is below. What am I missing?

Thanks

```<code><QBXML>
    <QBXMLMsgsRq onError = "continueOnError">
    <ReceivePaymentAddRq requestID = "0">
        <ReceivePaymentAdd>
            <CustomerRef>
                <ListID>80000111-1286514304</ListID>
            </CustomerRef>
            <ARAccountRef>
                <ListID>80000091-1273734429</ListID>
            </ARAccountRef>
            <TxnDate>2010-11-10</TxnDate>
            <RefNumber>2999      </RefNumber>
            <TotalAmount>15.95</TotalAmount>
            <PaymentMethodRef>
                <ListID>80000002-1273560098</ListID>
            </PaymentMethodRef>
            <Memo>_32T0DE94J</Memo>
            <DepositToAccountRef>
                <ListID>80000090-1273734138</ListID>
            </DepositToAccountRef>
            <AppliedToTxnAdd>
                <TxnID>68B4-1290718970</TxnID>
                <PaymentAmount>15.95</PaymentAmount>
            </AppliedToTxnAdd>
        </ReceivePaymentAdd>
    </ReceivePaymentAddRq>
    </QBXMLMsgsRq>
</QBXML>
</code>```

答:
For anyone else's reference, the question was already answered over here:

https://idnforums.intuit.com/messageview.aspx?catid=7&threadid=14923&enterthread=y

Updated answer now that Intuit have taken down their own forums:

There are a couple of common reasons for the error you're seeing:

The object you're referring to (68B4-1290718970) might not exist. Are you 100% positive this transaction exists?

The object you're referring to might not be something you can apply a payment to. You apply payments to Invoices. Is the object you're referring to an invoice?

The object you're referring to might not have the same currency that the payment has. Are you using multi-currency with QuickBooks, and do the currencies match?

The object you're referring to may not have a matching A/R account with the payment. This is especially common if you have multiple A/R accounts in QuickBooks, and you're not explicitly specifying which A/R account to use when creating the invoice or payment. Do the A/R accounts for the invoice and the payment match?

The object that you're referring to might not have an open balance (e.g. it might already be paid). Does the object that you're referring to have a balance of at least 15.95? (the amount you tried to apply)

ContentLicense: CC BY-SA 2.5

Body:
I'm working in QBXML and trying to apply a payment to specific invoice in a ReceivePaymentAddRq.  I'm getting the, apparently quite common, "Object TxnID specified in the request cannot be found".   Most other forums threads on this topic are resolved once the ARAccountRef field is added to the request, that didn't seem to make a difference for me.

I've queried the invoice for TxnID  68B4-1290718970 and verified the following:

My request's ARAccountRef ListID matches what is in the QueryRet

My request's CustomerRef ListID matches what is in the QueryRet

My XML request is below. What am I missing?

Thanks

<QBXML>
    <QBXMLMsgsRq onError = "continueOnError">
    <ReceivePaymentAddRq requestID = "0">
        <ReceivePaymentAdd>
            <CustomerRef>
                <ListID>80000111-1286514304</ListID>
            </CustomerRef>
            <ARAccountRef>
                <ListID>80000091-1273734429</ListID>
            </ARAccountRef>
            <TxnDate>2010-11-10</TxnDate>
            <RefNumber>2999      </RefNumber>
            <TotalAmount>15.95</TotalAmount>
            <PaymentMethodRef>
                <ListID>80000002-1273560098</ListID>
            </PaymentMethodRef>
            <Memo>_32T0DE94J</Memo>
            <DepositToAccountRef>
                <ListID>80000090-1273734138</ListID>
            </DepositToAccountRef>
            <AppliedToTxnAdd>
                <TxnID>68B4-1290718970</TxnID>
                <PaymentAmount>15.95</PaymentAmount>
            </AppliedToTxnAdd>
        </ReceivePaymentAdd>
    </ReceivePaymentAddRq>
    </QBXMLMsgsRq>
</QBXML>

ContentLicense: CC BY-SA 3.0


问:
How to match an npm package with another version if the default doesn't work?
Using a React Redux Starter template, I saw that it is using

```<code>"react": "^0.14.3"
</code>```

and if I npm install --save country-data, it would install:

```<code>"country-data": "0.0.31"
</code>```

and this version of country-data doesn't work -- however, it can work with the current version of react version 15.4.2.  So I am thinking to check the date of the release date of react 0.14.3, and use a version of country-data which is slightly before or after the release date of react 0.14.3

How can you check the release date of react 0.14.3 and a list of release dates of the different versions of country-data, perhaps using npm?

答:
If I understand your question. The npm view command may be used for that. It show data about package in json format. For example to know info about 'react' package run:

```<code>npm view react
</code>```

or only for release dates:

```<code>npm view react time
</code>```

Also release date for some project may be found in its repo. For example git repo releases most time is tagged, so use git tag. If repo on github go to tab releases.

Body:
Using a React Redux Starter template, I saw that it is using

"react": "^0.14.3"

and if I npm install --save country-data, it would install:

"country-data": "0.0.31"

and this version of country-data doesn't work -- however, it can work with the current version of react version 15.4.2.  So I am thinking to check the date of the release date of react 0.14.3, and use a version of country-data which is slightly before or after the release date of react 0.14.3

How can you check the release date of react 0.14.3 and a list of release dates of the different versions of country-data, perhaps using npm?

Body:
If I understand your question. The npm view command may be used for that. It show data about package in json format. For example to know info about 'react' package run:

npm view react

or only for release dates:

npm view react time

Also release date for some project may be found in its repo. For example git repo releases most time is tagged, so use git tag. If repo on github go to tab releases.


问:
Regular exp file iteration
i have got  2 files ,one with some  keywords and other with plain text i.e myfile.txt , i need to open a myfile.txt and extract the specific text starting with each keyword (mentioned in keyword file) and ends with "!"
example:

keyword file :

vrf-a

vrf-b

myfile.txt:

hello

how are you

!

x vrf-a

number 1

!

hi

howa are you

!

x vrf-b

number 2

!

Output should be:

x vrf-a

number 1

!

x vrf-b

number 2

I tried the below code:

```<code>import re
crazy = open("keyword.txt","r+")
lines  = crazy.readlines()
for word in lines:
    #print(word)
    with open('mytext.txt', 'r') as fh:
        result = re.findall(r'word[^!]+', fh.read(), re.M)
        print(result)
fh.close()
crazy.close()
</code>```

output getting as :
[]
[]
means no match

答:
r'word[^!]+' is looking for the substring "word" followed by any number of characters which aren't "!". It doesn't look for the string defined in the word variable.

Here's a working code :

```<code>import re

with open('mytext.txt') as fh:
    mytext = fh.read()

with open("keyword.txt") as crazy:
  for word in crazy:
      word = word.strip()
      results = re.findall(word+'[^!]+!', mytext, re.M)
      for result in results:
          print(result)
</code>```

It outputs :

```<code>vrf-a
number 1
!
vrf-b
number 2
!
</code>```

Title: Regular exp file iteration

Body:
i have got  2 files ,one with some  keywords and other with plain text i.e myfile.txt , i need to open a myfile.txt and extract the specific text starting with each keyword (mentioned in keyword file) and ends with "!"
example:

keyword file :

vrf-a

vrf-b

myfile.txt:

hello

how are you

!

x vrf-a

number 1

!

hi

howa are you

!

x vrf-b

number 2

!

Output should be:

x vrf-a

number 1

!

x vrf-b

number 2

I tried the below code:

import re
crazy = open("keyword.txt","r+")
lines  = crazy.readlines()
for word in lines:
    #print(word)
    with open('mytext.txt', 'r') as fh:
        result = re.findall(r'word[^!]+', fh.read(), re.M)
        print(result)
fh.close()
crazy.close()

output getting as :
[]
[]
means no match

Body:
r'word[^!]+' is looking for the substring "word" followed by any number of characters which aren't "!". It doesn't look for the string defined in the word variable.

Here's a working code :

import re

with open('mytext.txt') as fh:
    mytext = fh.read()

with open("keyword.txt") as crazy:
  for word in crazy:
      word = word.strip()
      results = re.findall(word+'[^!]+!', mytext, re.M)
      for result in results:
          print(result)

It outputs :

vrf-a
number 1
!
vrf-b
number 2
!


问:
VueJS: one component for many routes
I'm a newbie to the world of VueJS.

My app uses vue-router to handle with routes changing. This's how it's configured:

```<code>new Router({
  routes: [{
    path: "/",
    component: Articles
  }, {
    path: "/articles/:category",
    component: Articles
  }]
});
</code>```

As you can see, I've got 2 routes handled by the same component. The idea is very simple. When we're on a home page, show articles from any category. When we're on a category page, show articles from that category.

The question is, how a component can detect whether the route's changed, e.g, from home page to category page?

I've come with this solution:

```<code>function loadArticles() {};

Vue.component("Articles", {
  mounted: loadArticles,
  watch: { "$route": loadArticles }
});
</code>```

But I think, that's a bad solution.

答:
It should look something like this: </p>

```<code>watch: {
    '$route' (to, from) {
        if (this.$route.params.category) {
            this.loadArticles(category);
        } else {
            this.loadArticles();
        }
    }
}
</code>```

<p>'watch' is recommended here, in docs.</p>

Title: VueJS: one component for many routes

Body:
I'm a newbie to the world of VueJS.

My app uses vue-router to handle with routes changing. This's how it's configured:

new Router({
  routes: [{
    path: "/",
    component: Articles
  }, {
    path: "/articles/:category",
    component: Articles
  }]
});

As you can see, I've got 2 routes handled by the same component. The idea is very simple. When we're on a home page, show articles from any category. When we're on a category page, show articles from that category.

The question is, how a component can detect whether the route's changed, e.g, from home page to category page?

I've come with this solution:

function loadArticles() {};

Vue.component("Articles", {
  mounted: loadArticles,
  watch: { "$route": loadArticles }
});

But I think, that's a bad solution.

Body:
It should look something like this:

watch: {
    '$route' (to, from) {
        if (this.$route.params.category) {
            this.loadArticles(category);
        } else {
            this.loadArticles();
        }
    }
}

'watch' is recommended here, in docs.


问:
How to mock Push notification native module in React native jest tests?
When using the module react-native-push-notification, I had this error:

```<code> FAIL  __tests__/index.android.js
  ● Test suite failed to run

    Invariant Violation: Native module cannot be null.

      at invariant (node_modules/fbjs/lib/invariant.js:44:15)
      at new NativeEventEmitter (node_modules/react-native/Libraries/EventEmitter/NativeEventEmitter.js:32:1)
      at Object.<anonymous> (node_modules/react-native/Libraries/PushNotificationIOS/PushNotificationIOS.js:18:29)
      at Object.get PushNotificationIOS [as PushNotificationIOS] (node_modules/react-native/Libraries/react-native/react-native.js:97:34)
      at Object.<anonymous> (node_modules/react-native-push-notification/component/index.ios.js:10:23)
</code>```

I tried to mock the module by creating __mocks__/react-native.js and putting this code within it:

```<code>const rn = require('react-native')

jest.mock('PushNotificationIOS', () => ({
  addEventListener: jest.fn(),
  requestPermissions: jest.fn(),
  then: jest.fn()
}));

module.exports = rn
</code>```

Now, I have this error:

```<code> FAIL  __tests__/index.android.js
  ● Test suite failed to run

    TypeError: Cannot read property 'then' of null

      at Object.<anonymous>.Notifications.popInitialNotification (node_modules/react-native-push-notification/index.js:278:42)
      at Object.<anonymous>.Notifications.configure (node_modules/react-native-push-notification/index.js:93:6)
      at Object.<anonymous> (app/utils/localPushNotification.js:4:39)
      at Object.<anonymous> (app/actions/trip.js:5:28)
</code>```

How I could mock fully this module the right way?

答:
I mocked the module PushNotificationIOS by creating a setup file jest/setup.js:

```<code>jest.mock('PushNotificationIOS', () => {
  return {
    addEventListener: jest.fn(),
    requestPermissions: jest.fn(() => Promise.resolve()),
    getInitialNotification: jest.fn(() => Promise.resolve()),
  }
});
</code>```

I've configured jest to run this setup file by adding this line into packages.json:

```<code>  "jest": {
    ...
    "setupFiles": ["./jest/setup.js"],
  }
</code>```

Body:
When using the module react-native-push-notification, I had this error:

 FAIL  __tests__/index.android.js
  ● Test suite failed to run

    Invariant Violation: Native module cannot be null.

      at invariant (node_modules/fbjs/lib/invariant.js:44:15)
      at new NativeEventEmitter (node_modules/react-native/Libraries/EventEmitter/NativeEventEmitter.js:32:1)
      at Object.<anonymous> (node_modules/react-native/Libraries/PushNotificationIOS/PushNotificationIOS.js:18:29)
      at Object.get PushNotificationIOS [as PushNotificationIOS] (node_modules/react-native/Libraries/react-native/react-native.js:97:34)
      at Object.<anonymous> (node_modules/react-native-push-notification/component/index.ios.js:10:23)

I tried to mock the module by creating __mocks__/react-native.js and putting this code within it:

const rn = require('react-native')

jest.mock('PushNotificationIOS', () => ({
  addEventListener: jest.fn(),
  requestPermissions: jest.fn(),
  then: jest.fn()
}));

module.exports = rn

Now, I have this error:

 FAIL  __tests__/index.android.js
  ● Test suite failed to run

    TypeError: Cannot read property 'then' of null

      at Object.<anonymous>.Notifications.popInitialNotification (node_modules/react-native-push-notification/index.js:278:42)
      at Object.<anonymous>.Notifications.configure (node_modules/react-native-push-notification/index.js:93:6)
      at Object.<anonymous> (app/utils/localPushNotification.js:4:39)
      at Object.<anonymous> (app/actions/trip.js:5:28)

How I could mock fully this module the right way?

Body:
I mocked the module PushNotificationIOS by creating a setup file jest/setup.js:

jest.mock('PushNotificationIOS', () => {
  return {
    addEventListener: jest.fn(),
    requestPermissions: jest.fn(() => Promise.resolve()),
    getInitialNotification: jest.fn(() => Promise.resolve()),
  }
});

I've configured jest to run this setup file by adding this line into packages.json:

  "jest": {
    ...
    "setupFiles": ["./jest/setup.js"],
  }


问:
Python Programming on Inheritance
I wrote a code where in I have a base class for SchoolMember and derived two classes : Teacher & Student. Please refer the code below:

```<code>class SchoolMember:
    '''Represents school member'''
    def __init__(self,name,age):
        self.name=name
        self.age=age
        print('Initialised school member is:', format(self.name))

    def tell(self):
        print ('Name: \t Age: ', format(self.name, self.age))

class Teacher(SchoolMember):
    def __init__(self,name,salary,age):
        SchoolMember.__init__(self,name,age)
        self.salary=salary
        print ('Initialised teacher is ', format(self.name))

    def tell(self):
        '''Prints the salary of the teacher'''
        print('Salary of teacher is ', format(self.salary))

class Student(SchoolMember):
    def __init__(self,name,age,fees):
        SchoolMember.__init__(self,name,age)
        self.fees=fees
        print('Initialised student is',format(self.name))

    def tell(self):
        '''Tells the fees of the student'''
        print('Fees  of student is', format(self.fees))

t = Teacher('Richa', 26,4000)
s = Student('Shubh',21, 2000)

print()
members = [t,s]
for member in members:
    member.tell()
</code>```

Output :

```<code>('Initialised school member is:', 'Richa')
('Initialised teacher is ', 'Richa')
('Initialised school member is:', 'Shubh')
('Initialised student is', 'Shubh')
()
('Salary of teacher is ', '4000')
('Fees  of student is', '2000')
</code>```

Now , my question is : how to get the age in output?

答:
You want to read up on the format() function documentation; you are not using it the way it was designed to; the function formats a value according to a specification (the optional second argument).

In fact, you do not need to use it at all.

Use str.format() instead, a method on strings:

```<code>print 'Name: {}\t Age: {}'.format(self.name, self.age)
</code>```

Here the {} placeholders are replaced with the values you pass to the method.

Note that I didn't use print as a function; in Python 2 it is a statement; this is why you see () when you execute print(); that's just print tuple(), really. You could use from __future__ import print_function at the top of your modules, but I'll stick with the old statement for now; it'd be better to just switch to Python 3 entirely.

Next, you want to execute the overridden SchoolMember.tell() method directly from your subclasses:

```<code>def tell(self):
    '''Tells the fees of the student'''
    SchoolMember.tell(self)
    print 'Fees  of student is {}'.format(self.fees)
</code>```

Because you access the method unbound on the class, you need to manually pass in self.

In new-style classes (inheriting from object, the default base class in Python 3), you could also use the super() function; if your tutorial is using super() already but you could not get it to work, you are most likely following a Python 3 tutorial and you want to upgrade, rather than stick with a legacy version of the language.

Title: Python Programming on Inheritance

Body:
I wrote a code where in I have a base class for SchoolMember and derived two classes : Teacher & Student. Please refer the code below:

class SchoolMember:
    '''Represents school member'''
    def __init__(self,name,age):
        self.name=name
        self.age=age
        print('Initialised school member is:', format(self.name))

    def tell(self):
        print ('Name: \t Age: ', format(self.name, self.age))

class Teacher(SchoolMember):
    def __init__(self,name,salary,age):
        SchoolMember.__init__(self,name,age)
        self.salary=salary
        print ('Initialised teacher is ', format(self.name))

    def tell(self):
        '''Prints the salary of the teacher'''
        print('Salary of teacher is ', format(self.salary))

class Student(SchoolMember):
    def __init__(self,name,age,fees):
        SchoolMember.__init__(self,name,age)
        self.fees=fees
        print('Initialised student is',format(self.name))

    def tell(self):
        '''Tells the fees of the student'''
        print('Fees  of student is', format(self.fees))

t = Teacher('Richa', 26,4000)
s = Student('Shubh',21, 2000)

print()
members = [t,s]
for member in members:
    member.tell()

Output :

('Initialised school member is:', 'Richa')
('Initialised teacher is ', 'Richa')
('Initialised school member is:', 'Shubh')
('Initialised student is', 'Shubh')
()
('Salary of teacher is ', '4000')
('Fees  of student is', '2000')

Now , my question is : how to get the age in output?

Body:
You want to read up on the format() function documentation; you are not using it the way it was designed to; the function formats a value according to a specification (the optional second argument).

In fact, you do not need to use it at all.

Use str.format() instead, a method on strings:

print 'Name: {}\t Age: {}'.format(self.name, self.age)

Here the {} placeholders are replaced with the values you pass to the method.

Note that I didn't use print as a function; in Python 2 it is a statement; this is why you see () when you execute print(); that's just print tuple(), really. You could use from __future__ import print_function at the top of your modules, but I'll stick with the old statement for now; it'd be better to just switch to Python 3 entirely.

Next, you want to execute the overridden SchoolMember.tell() method directly from your subclasses:

def tell(self):
    '''Tells the fees of the student'''
    SchoolMember.tell(self)
    print 'Fees  of student is {}'.format(self.fees)

Because you access the method unbound on the class, you need to manually pass in self.

In new-style classes (inheriting from object, the default base class in Python 3), you could also use the super() function; if your tutorial is using super() already but you could not get it to work, you are most likely following a Python 3 tutorial and you want to upgrade, rather than stick with a legacy version of the language.


问:
Looping assets and entries together
I have managed to loop out all content from a specific ContentType and everything works well except that the entries are not followed by their specific assets.

In this specific case it renders as:
Entry 1
Entry 2
Entry 3
Asset 1
Asset 2
Asset 3

I want it to render as: Entry 1 Asset 1, Entry 2 Asset 2 etc...

Putting the asset array loop inside the fields loop didn't help :)

Javascript

```<code>client.getEntries({
    include: 1,
    'content_type': 'posts'
})
.then((response) => {

    var template = $('#myEntries').html();
    var html = Mustache.to_html(template, response.toPlainObject());
    $('.result').html(html);

})
.catch((error) => {
    console.log('Error occured')
    console.log(error)
})
</code>```

HTML

```<code><script id="myEntries" type="text/template">
    {{#items}}
        <h1>{{fields.header}}</h1>
        <p>{{fields.description}}</p>
    {{/items}}

    {{#includes.Asset}}
        <p>File: <img src="https:{{fields.file.url}}?fit=thumb&f=top_left&h=200&w=200" width="100"/></p>
    {{/includes.Asset}}
</script>

<div class="result"></div>
</code>```

JSON
https://jsfiddle.net/pcgn73zf/

Would love your help!

答:
Hi maybe you missed it in the docs but the contentful js SDK already does link resolution, for example, if you have a contentType post that has an image field, when you get an entry you can access directly the fields of the asset. so to get the url from the linked asset you just request myEntry.fields.image.fields.file.url. No need to request it form includes.
the asset part in your code should be (assuming that the asset field is called image)

```<code> <p>File: <img src="https:{{fields.image.fields.file.url}}?fit=thumb&f=top_left&h=200&w=200" width="100"/></p>
</code>```

Please note that link resolution only works when requesting the collection endpoint client.getEntries()
for more infos check this README section

Title: Looping assets and entries together

Body:
I have managed to loop out all content from a specific ContentType and everything works well except that the entries are not followed by their specific assets.

In this specific case it renders as:
Entry 1
Entry 2
Entry 3
Asset 1
Asset 2
Asset 3

I want it to render as: Entry 1 Asset 1, Entry 2 Asset 2 etc...

Putting the asset array loop inside the fields loop didn't help :)

Javascript

client.getEntries({
    include: 1,
    'content_type': 'posts'
})
.then((response) => {

    var template = $('#myEntries').html();
    var html = Mustache.to_html(template, response.toPlainObject());
    $('.result').html(html);

})
.catch((error) => {
    console.log('Error occured')
    console.log(error)
})

HTML

JSON
https://jsfiddle.net/pcgn73zf/

Would love your help!

Body:
Hi maybe you missed it in the docs but the contentful js SDK already does link resolution, for example, if you have a contentType post that has an image field, when you get an entry you can access directly the fields of the asset. so to get the url from the linked asset you just request myEntry.fields.image.fields.file.url. No need to request it form includes.
the asset part in your code should be (assuming that the asset field is called image)

 <p>File: <img src="https:{{fields.image.fields.file.url}}?fit=thumb&f=top_left&h=200&w=200" width="100"/></p>

Please note that link resolution only works when requesting the collection endpoint client.getEntries()
for more infos check this README section


问:
Take input in arrays of pointers
Can someone please let me know why one can't take an input in arrays of pointer to strings using input stream as in the following code: </p>

```<code>char *names[5];

for(int i=0; i<5; i++)
{
cout<<"enter name "<<i+1;
cin>>names[i];
}
</code>```

答:
The variable "names" is an undefined array of char pointers. That's your first problem. The pointers are undefined and have no memory allocated for them.
In your original code example there are five char pointers with undefined values. This is why the program would crash, because it's trying to access memory of the invalid address in the pointers.
Another problem is that there is no memory allocated to hold the array of chars coming in from stdin.

You could do something like this to get your original example working without crash:

```<code>#include <iostream>
#include <string.h>

using namespace std;

int main(int argc, char** argv)
{
    char names[5][128];
    memset(names, 0, sizeof(names));

    for (int i = 0 ; i < 5 ; i++ )
    {
        cout << "enter name " << i+1 << ": ";
        cin >> names[i];
    }

    for (int i = 0 ; i < 5 ; i++ )
    {
        cout << names[i] << "\n";
    }
}
</code>```

This allocates an array of 5 128 character strings. It also clears the arrays with the memset() as well.

Since this is C++ it would seem to make more sense to do it C++ style.

```<code>#include <iostream>
#include <string>
#include <vector>

using namespace std;

const int NUM_NAMES = 5;

int main(int argc, char** argv)
{
    vector<string> names;
    names.resize(NUM_NAMES);

    for (int i = 0 ; i < NUM_NAMES ; i++ )
    {
        cout << "enter name " << i+1 << ": ";
        cin >> names[i];
    }

    for (int i = 0 ; i < NUM_NAMES ; i++ )
    {
        cout << names[i] << "\n";
    }
}
</code>```

Title: Take input in arrays of pointers

Body:
Can someone please let me know why one can't take an input in arrays of pointer to strings using input stream as in the following code:

char *names[5];

for(int i=0; i<5; i++)
{
cout<<"enter name "<>names[i];
}

Body:
The variable "names" is an undefined array of char pointers. That's your first problem. The pointers are undefined and have no memory allocated for them.
In your original code example there are five char pointers with undefined values. This is why the program would crash, because it's trying to access memory of the invalid address in the pointers.
Another problem is that there is no memory allocated to hold the array of chars coming in from stdin.

You could do something like this to get your original example working without crash:

#include <iostream>
#include <string.h>

using namespace std;

int main(int argc, char** argv)
{
    char names[5][128];
    memset(names, 0, sizeof(names));

    for (int i = 0 ; i < 5 ; i++ )
    {
        cout << "enter name " << i+1 << ": ";
        cin >> names[i];
    }

    for (int i = 0 ; i < 5 ; i++ )
    {
        cout << names[i] << "\n";
    }
}

This allocates an array of 5 128 character strings. It also clears the arrays with the memset() as well.

Since this is C++ it would seem to make more sense to do it C++ style.

#include <iostream>
#include <string>
#include <vector>

using namespace std;

const int NUM_NAMES = 5;

int main(int argc, char** argv)
{
    vector<string> names;
    names.resize(NUM_NAMES);

    for (int i = 0 ; i < NUM_NAMES ; i++ )
    {
        cout << "enter name " << i+1 << ": ";
        cin >> names[i];
    }

    for (int i = 0 ; i < NUM_NAMES ; i++ )
    {
        cout << names[i] << "\n";
    }
}


问:
Drawing MultiPolygon with different style for each component in OpenLayers
I have a OpenLayers.Feature.Vector created as follows:

```<code>var multiPol = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.MultiPolygon([polygonGeometry1,polygonGeometry2]));
</code>```

Both polygons represent same logical object (an "entity") on a map, say a cloud. This is why I keep them in one feature.
I would like to draw it so that each component of this multi-polygon (polygonGeometry1, polygonGeometry2) is drawn with different color when it's added to a layer:

```<code>   var layer = new OpenLayers.Layer.Vector("polygonLayer");
   layer.addFeatures([multiPol]);
</code>```

I have taken a look at styles, style maps and rules in OpenLayers but they appear to be insufficient. They do enable me to draw each geometry type with different color but only if they belong to different features (vectors). Is there a way to solve this problem? Do really I have to use separate Vector for each polygon?

答:
As far as I can tell, to get this functionality you will need to extend the classes with your own.

First create an extension to OpenLayers.Feature.Vector, name it YourApp.Feature.MultiVector.  You can see examples on how to extend classes by looking at the OpenLayers code. This class should accept an array of styles and the multiPolygon.  It should have a method that will return a list of OpenLayers.Feature.Vectors each with their own style.

Second create an extension to OpenLayers.Layer.Vector, name it YourApp.Layer.VectorSupportingMultiStyledFeatures.  You will need to override the "drawFeature" method.  In the drawFeature method test to see if the type of the feature is a MultiVector.  If it is, loop through each feature in the MultiVector and call renderer.drawFeature(feature).  Otherwise call the super.drawFeature method.

So your code to call it would look like this:

```<code>var multiPol = new YourApp.Feature.MultiVector(
    new OpenLayers.Geometry.MultiPolygon([polygonGeometry1,polygonGeometry2]),
    [style1,style2,style3,style4]);

var layer = new YourApp.Layer.VectorSupportingMultiStyledFeatures("polygonLayer");
layer.addFeatures([multiPol]);
</code>```

Body:
I have a OpenLayers.Feature.Vector created as follows:

var multiPol = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.MultiPolygon([polygonGeometry1,polygonGeometry2]));

Both polygons represent same logical object (an "entity") on a map, say a cloud. This is why I keep them in one feature.
I would like to draw it so that each component of this multi-polygon (polygonGeometry1, polygonGeometry2) is drawn with different color when it's added to a layer:

   var layer = new OpenLayers.Layer.Vector("polygonLayer");
   layer.addFeatures([multiPol]);

I have taken a look at styles, style maps and rules in OpenLayers but they appear to be insufficient. They do enable me to draw each geometry type with different color but only if they belong to different features (vectors). Is there a way to solve this problem? Do really I have to use separate Vector for each polygon?

Body:
As far as I can tell, to get this functionality you will need to extend the classes with your own.

First create an extension to OpenLayers.Feature.Vector, name it YourApp.Feature.MultiVector.  You can see examples on how to extend classes by looking at the OpenLayers code. This class should accept an array of styles and the multiPolygon.  It should have a method that will return a list of OpenLayers.Feature.Vectors each with their own style.

Second create an extension to OpenLayers.Layer.Vector, name it YourApp.Layer.VectorSupportingMultiStyledFeatures.  You will need to override the "drawFeature" method.  In the drawFeature method test to see if the type of the feature is a MultiVector.  If it is, loop through each feature in the MultiVector and call renderer.drawFeature(feature).  Otherwise call the super.drawFeature method.

So your code to call it would look like this:

var multiPol = new YourApp.Feature.MultiVector(
    new OpenLayers.Geometry.MultiPolygon([polygonGeometry1,polygonGeometry2]),
    [style1,style2,style3,style4]);

var layer = new YourApp.Layer.VectorSupportingMultiStyledFeatures("polygonLayer");
layer.addFeatures([multiPol]);


问:
What should I do if the head of column with space in R?
I import data (daily snow Depth data )from an excel.
But this dataset has a lot of space in it, especially the spaces also contained in the head. Like the heads shows bellow:

```<code>GHCN ID    Station Name     County      Mar 1      Mar 2      Mar 3 ......
</code>```

Thus, when I try to set up a subset by the name of the 2nd column if it is equal to "Station Name", like this:

```<code>Boston_snow <- subset(MA_snow,Station Name == "BOSTON",select =       c(3/1/2017:3/31/2017))
</code>```

R returned me an error:
Error: unexpected symbol in "Boston_snow <- subset(MA_snow,Station Name"

But if I eliminate the space in code:

```<code>Boston_snow <- subset(MA_snow,StationName == "BOSTON",select =       c(3/1/2017:3/31/2017))
</code>```

Still an error occurred:
Error in eval(expr, envir, enclos) : object 'StationName' not found

So, what should I do? I mean, maybe either to eliminate all the spaces in my excel or use some command that can work well with spaces are fine to me. But I have no idea on them, especially the later option.

Sincerely hope can get an answer. Thank you soooo much for your help.

答:
Oh, I found a space replace way for that:

```<code>MA_snow2 <- as.data.frame(apply(MA_snow,2,function(x)gsub('\\s+', '_',x)))
</code>```

This command will replace all the space by _ in my whole data frame.

Meanwhile, I realized that simply use the gsub command as follow does not work, because it just can work on a string:

```<code>MA_snow2 <- gsub("\\s", "_",MA_snow)
</code>```

Thanks to @jwells all the same.

Body:
I import data (daily snow Depth data )from an excel.
But this dataset has a lot of space in it, especially the spaces also contained in the head. Like the heads shows bellow:

GHCN ID    Station Name     County      Mar 1      Mar 2      Mar 3 ......

Thus, when I try to set up a subset by the name of the 2nd column if it is equal to "Station Name", like this:

Boston_snow <- subset(MA_snow,Station Name == "BOSTON",select =       c(3/1/2017:3/31/2017))

R returned me an error:
Error: unexpected symbol in "Boston_snow <- subset(MA_snow,Station Name"

But if I eliminate the space in code:

Boston_snow <- subset(MA_snow,StationName == "BOSTON",select =       c(3/1/2017:3/31/2017))

Still an error occurred:
Error in eval(expr, envir, enclos) : object 'StationName' not found

So, what should I do? I mean, maybe either to eliminate all the spaces in my excel or use some command that can work well with spaces are fine to me. But I have no idea on them, especially the later option.

Sincerely hope can get an answer. Thank you soooo much for your help.

Body:
Oh, I found a space replace way for that:

MA_snow2 <- as.data.frame(apply(MA_snow,2,function(x)gsub('\\s+', '_',x)))

This command will replace all the space by _ in my whole data frame.

Meanwhile, I realized that simply use the gsub command as follow does not work, because it just can work on a string:

MA_snow2 <- gsub("\\s", "_",MA_snow)

Thanks to @jwells all the same.


问:
In emacs org mode, is there a formula I can use to count the number of cells?
I'm new to emacs (spacemacs, actually) and org-mode. I'd like to have a final line in my table that shows how many rows there are in the table. Is there a formula function for that? </p>

答:
This formula should work: vlen(@I..@II).

Example:

```<code>| Title |
|-------|
| one   |
| two   |
| three |
| four  |
|-------|
| 4     |
#+Tblfm: @6$1=vlen(@I..@II)
</code>```

Body:
This formula should work: vlen(@I..@II).

Example:

| Title |
|-------|
| one   |
| two   |
| three |
| four  |
|-------|
| 4     |
#+Tblfm: @6$1=vlen(@I..@II)


问:
Rails - How to add values in seperate objects together
You have an array of objects which contain a key-value reference.

```<code>[{booking_ref: 'w578383', foo: 'bar', price1: 500, price2: 30],
{booking_ref: 'w578383', foo: 'bar', price1: 600, price2: 40},
{booking_ref: 'r123523', foo: 'bar', price1: 699, price2: 4}]
</code>```

I want to:

group objects by key-value reference (booking_ref)

go through those groupings and to each object add the financial values only together (price1 and price2 to the other booking's price1 and price2)

collapse out of groupings back to an array of objects which contain a key-value reference. That would now be:

```<code>[{booking_ref: 'w578383', foo: 'bar', price1: 1100, price2: 70},
{booking_ref: 'r123523', foo: 'bar', price1: 699, price2: 4}]
</code>```

I am thinking:

```<code>objects.group_by(&:booking_ref).each {|group|
  group.merge {|key, value1, value2| value1 + value2 if key == price1 || price2}
}
</code>```

Does that work and if so how do I then return them back out of the group_by state?

答:
Taking an object-oriented approach here, you can get this looking quite neat and elegant. The key is to define the + method on the object. Full example below:

```<code>class Booking
  attr_accessor :booking_ref, :foo, :price1, :price2

  def initialize(params={})
    params.each { |key, value| send "#{key}=", value }
  end

  # add up prices, and return new Booking object
  def +(other)
    new_obj = self.dup
    new_obj.price1 += other.price1
    new_obj.price2 += other.price2
    new_obj
  end
end

# set up example bookings
bookings = [
  Booking.new(booking_ref: 'w578383', foo: 'bar', price1: 500, price2: 30),
  Booking.new(booking_ref: 'w578383', foo: 'bar', price1: 600, price2: 40),
  Booking.new(booking_ref: 'r123523', foo: 'bar', price1: 699, price2: 4)
]

# grouping becomes very simple - potentially a one-liner
bookings.group_by(&:booking_ref).map { |_, values| values.reduce(&:+) }
# => [
        #<Booking:... @booking_ref="w578383", @foo="bar", @price1=1100, @price2=70>,
        #<Booking:... @booking_ref="r123523", @foo="bar", @price1=699, @price2=4>
     ]
</code>```

Body:
You have an array of objects which contain a key-value reference.

[{booking_ref: 'w578383', foo: 'bar', price1: 500, price2: 30],
{booking_ref: 'w578383', foo: 'bar', price1: 600, price2: 40},
{booking_ref: 'r123523', foo: 'bar', price1: 699, price2: 4}]

I want to:

group objects by key-value reference (booking_ref)

go through those groupings and to each object add the financial values only together (price1 and price2 to the other booking's price1 and price2)

collapse out of groupings back to an array of objects which contain a key-value reference. That would now be:

[{booking_ref: 'w578383', foo: 'bar', price1: 1100, price2: 70},
{booking_ref: 'r123523', foo: 'bar', price1: 699, price2: 4}]

I am thinking:

objects.group_by(&:booking_ref).each {|group|
  group.merge {|key, value1, value2| value1 + value2 if key == price1 || price2}
}

Does that work and if so how do I then return them back out of the group_by state?

Body:
Taking an object-oriented approach here, you can get this looking quite neat and elegant. The key is to define the + method on the object. Full example below:

class Booking
  attr_accessor :booking_ref, :foo, :price1, :price2

  def initialize(params={})
    params.each { |key, value| send "#{key}=", value }
  end

  # add up prices, and return new Booking object
  def +(other)
    new_obj = self.dup
    new_obj.price1 += other.price1
    new_obj.price2 += other.price2
    new_obj
  end
end

# set up example bookings
bookings = [
  Booking.new(booking_ref: 'w578383', foo: 'bar', price1: 500, price2: 30),
  Booking.new(booking_ref: 'w578383', foo: 'bar', price1: 600, price2: 40),
  Booking.new(booking_ref: 'r123523', foo: 'bar', price1: 699, price2: 4)
]

# grouping becomes very simple - potentially a one-liner
bookings.group_by(&:booking_ref).map { |_, values| values.reduce(&:+) }
# => [
        #<Booking:... @booking_ref="w578383", @foo="bar", @price1=1100, @price2=70>,
        #<Booking:... @booking_ref="r123523", @foo="bar", @price1=699, @price2=4>
     ]


问:
Can anyone help? Getting "[Errno 13] Permission denied" when I try to install pip on Mac
Thank you in advance for any guidance (I've heard mixed advice on sudo command?). Here is the script from Terminal:

running install

  Checking .pth file support in /Library/Python/2.7/site-packages/

  error: can't create or remove files in install directory

The following error occurred while trying to add or remove files in the
installation directory:

[Errno 13] Permission denied: '/Library/Python/2.7/site-packages/test-easy-install-85961.pth'

答:
Well "sudo" should have worked,

```<code>sudo pip install <package-name>
</code>```

Secondly make sure your pip is updated

```<code>sudo pip install --upgrade pip
</code>```

After running PIP through sudo you might get a warning about "directory is not owned by current user" can be ignored.

Body:
Well "sudo" should have worked,

sudo pip install <package-name>

Secondly make sure your pip is updated

sudo pip install --upgrade pip

After running PIP through sudo you might get a warning about "directory is not owned by current user" can be ignored.


问:
use spring data jpa with ninja java
ninja is an awesome framework but coming from a  spring background, I need to use spring data jpa with ninja.

I want to Autowire a JpaRepository and use it in ninja. Although ninja uses Guice Inject. I keep getting a No implementations found for my class.

the repository:

```<code>public interface PortalUserRepository extends JpaRepository<PortalUser, Long> {

PortalUser getPortalUserByUsername(String username);

PortalUser getPortalUserByEmail(String email);
}
</code>```

the injection

```<code>public class SetupDaoV2 {

@Inject
PortalUserRepository portalUserRepository;

public void setup() {
    try {
        List<PortalUser> portalUsers = portalUserRepository.findAll();
        if (portalUsers.size() == 0) {
            // Create a new user and save it
            PortalUser portalUser = new PortalUser("lsadjfl", "lsdlfs", "kkk lll",
                    "llskfls@gmail.com", "lsdlfss@",
                    "lsdfls@gmail.com",
                    new Timestamp(System.currentTimeMillis()), Boolean.TRUE,
                    Boolean.TRUE, GenericStatusConstant.ACTIVE, Boolean.TRUE
            );
            portalUserRepository.save(portalUser);
        }
    }catch (Exception ex){
        ex.printStackTrace();
    }
}
}
</code>```

the error

com.google.inject.CreationException: Unable to create injector, see
  the following errors:

1) No implementation for com.bw.dd.dsl.repository.PortalUserRepository was bound.

答:
You need to mark PortalUserRepository class with @Repository as shown below:

```<code>@Repository
public interface PortalUserRepository extends JpaRepository<PortalUser, Long> {
   //your methods
}
</code>```

Also, ensure that you have got @EnableJPARepositories so that Spring container can scan for your repository interfaces and provide the implementations for them and then inject them into your SetupDaoV2 bean.

Title: use spring data jpa with ninja java

Body:
ninja is an awesome framework but coming from a  spring background, I need to use spring data jpa with ninja.

I want to Autowire a JpaRepository and use it in ninja. Although ninja uses Guice Inject. I keep getting a No implementations found for my class.

the repository:

public interface PortalUserRepository extends JpaRepository<PortalUser, Long> {

PortalUser getPortalUserByUsername(String username);

PortalUser getPortalUserByEmail(String email);
}

the injection

public class SetupDaoV2 {

@Inject
PortalUserRepository portalUserRepository;

public void setup() {
    try {
        List<PortalUser> portalUsers = portalUserRepository.findAll();
        if (portalUsers.size() == 0) {
            // Create a new user and save it
            PortalUser portalUser = new PortalUser("lsadjfl", "lsdlfs", "kkk lll",
                    "llskfls@gmail.com", "lsdlfss@",
                    "lsdfls@gmail.com",
                    new Timestamp(System.currentTimeMillis()), Boolean.TRUE,
                    Boolean.TRUE, GenericStatusConstant.ACTIVE, Boolean.TRUE
            );
            portalUserRepository.save(portalUser);
        }
    }catch (Exception ex){
        ex.printStackTrace();
    }
}
}

the error

com.google.inject.CreationException: Unable to create injector, see
  the following errors:

1) No implementation for com.bw.dd.dsl.repository.PortalUserRepository was bound.

Body:
You need to mark PortalUserRepository class with @Repository as shown below:

@Repository
public interface PortalUserRepository extends JpaRepository<PortalUser, Long> {
   //your methods
}

Also, ensure that you have got @EnableJPARepositories so that Spring container can scan for your repository interfaces and provide the implementations for them and then inject them into your SetupDaoV2 bean.


问:
How should I pass my s3 credentials to Python lambda function on AWS?
I'd like to write a file to S3 from my lambda function written in Python.  But I’m struggling to pass my S3 ID and Key.

The following works on my local machine after I set my local Python environment variables AWS_SHARED_CREDENTIALS_FILE and AWS_CONFIG_FILE to point to the local files I created with the AWS CLI.

```<code>session = boto3.session.Session(region_name='us-east-2')
s3 = session.client('s3',
     config=boto3.session.Config(signature_version='s3v4'))
</code>```

And the following works on Lambda where I hand code my ID and Key (using *** here):

```<code>AWS_ACCESS_KEY_ID = '***'
AWS_SECRET_ACCESS_KEY = '***'
session = boto3.session.Session(region_name='us-east-2')
s3 = session.client('s3',
     config=boto3.session.Config(signature_version='s3v4'),
     aws_access_key_id=AWS_ACCESS_KEY_ID,
     aws_secret_access_key=AWS_SECRET_ACCESS_KEY)
</code>```

But I understand this is insecure after reading best practices from Amazon. So I try:

```<code>AWS_ACCESS_KEY_ID = os.environ['AWS_ACCESS_KEY_ID']
AWS_SECRET_ACCESS_KEY = os.environ['AWS_SECRET_ACCESS_KEY']
session = boto3.session.Session(region_name='us-east-2')
s3 = session.client('s3',
     config=boto3.session.Config(signature_version='s3v4'),
     aws_access_key_id=AWS_ACCESS_KEY_ID,
     aws_secret_access_key=AWS_SECRET_ACCESS_KEY)
</code>```

But I get an error: “The AWS Access Key Id you provided does not exist in our records.” I also tried to define these variables in the Lambda console, but I then I get: "Lambda was unable to configure your environment variables because the environment variables you have provided contains reserved keys."

I am a little surprised I need to pass an ID or Key at all since I believe my account for authoring the Lambda function also has permission to write to the S3 account (the key and secret I hand code are from IAM for this same account). I got the same sense from reading the following post:
AWS Lambda function write to S3

答:
The fact that your account has permissions to "write" to the S3 account does not mean that you can do it. AWS has a service called IAM which will handle the permissions that your lambda (among many other services) have to perform actions against other AWS resources.

Most probably you are lacking the relevant IAM role/policy associated to your lambda to write to the S3 bucket.

As pointed in AWS Lambda Permissions Model you need to create and associate an IAM role when creating the lambda. You can do this from the console or using CloudFormation.

Once you have the relevant permissions in place for your lambda you do not need to deal with keys or authentication.

Body:
I'd like to write a file to S3 from my lambda function written in Python.  But I’m struggling to pass my S3 ID and Key.

The following works on my local machine after I set my local Python environment variables AWS_SHARED_CREDENTIALS_FILE and AWS_CONFIG_FILE to point to the local files I created with the AWS CLI.

session = boto3.session.Session(region_name='us-east-2')
s3 = session.client('s3',
     config=boto3.session.Config(signature_version='s3v4'))

And the following works on Lambda where I hand code my ID and Key (using *** here):

AWS_ACCESS_KEY_ID = '***'
AWS_SECRET_ACCESS_KEY = '***'
session = boto3.session.Session(region_name='us-east-2')
s3 = session.client('s3',
     config=boto3.session.Config(signature_version='s3v4'),
     aws_access_key_id=AWS_ACCESS_KEY_ID,
     aws_secret_access_key=AWS_SECRET_ACCESS_KEY)

But I understand this is insecure after reading best practices from Amazon. So I try:

AWS_ACCESS_KEY_ID = os.environ['AWS_ACCESS_KEY_ID']
AWS_SECRET_ACCESS_KEY = os.environ['AWS_SECRET_ACCESS_KEY']
session = boto3.session.Session(region_name='us-east-2')
s3 = session.client('s3',
     config=boto3.session.Config(signature_version='s3v4'),
     aws_access_key_id=AWS_ACCESS_KEY_ID,
     aws_secret_access_key=AWS_SECRET_ACCESS_KEY)

But I get an error: “The AWS Access Key Id you provided does not exist in our records.” I also tried to define these variables in the Lambda console, but I then I get: "Lambda was unable to configure your environment variables because the environment variables you have provided contains reserved keys."

I am a little surprised I need to pass an ID or Key at all since I believe my account for authoring the Lambda function also has permission to write to the S3 account (the key and secret I hand code are from IAM for this same account). I got the same sense from reading the following post:
AWS Lambda function write to S3


问:
Bash code to check for SSH/Samba connections?
I currently use the following cron job to put the computer in suspend mode and wake it up the following day:

```<code>0 13 * * * /usr/sbin/rtcwake -m standby -u -t $(date +\%s -d 'tomorrow 1145')
</code>```

I'd like to replace this with a call to a Bash script that will
be called every hour…

```<code>check if anyone is currently connected through SSH or Samba (backup job)
If no one is connected, go into suspend mode
else try again the next hour.
</code>```

Does someone have some working code I could use?

Thank you.

答:
w:

Show who is logged on and what they are doing.

Body:
I currently use the following cron job to put the computer in suspend mode and wake it up the following day:

0 13 * * * /usr/sbin/rtcwake -m standby -u -t $(date +\%s -d 'tomorrow 1145')

I'd like to replace this with a call to a Bash script that will
be called every hour…

check if anyone is currently connected through SSH or Samba (backup job)
If no one is connected, go into suspend mode
else try again the next hour.

Does someone have some working code I could use?

Thank you.


问:
React render component containing only function
I'm very very new to react (still learning). One thing I noticed is that component always have a return with HTML (jsx) as content.

But I was wondering if it's possible to create a component containing only functions. For example, in my footer I only have static content. Just plain text and a button to go to the homepage. So this is what I'm trying to do:

index.html

```<code><body>
    <main id="app"></main>

    <footer id="footer">
        <!-- Some other content -->
        <button onClick={this.onButton}>Home</button>
    </footer>

    <script src="/app/bundle.js"></script>
</body>
</code>```

Footer.js

```<code>class Footer extends React.Component {
    onButton() {
        console.log('Button clicked');
    }

    render() {
        console.log('render');
        return null;
    }
}

render(<Footer/>, window.document.getElementById("footer"));
</code>```

This way, the component gets executed and I can see the log, however, the button defined in the index.html is removed.

On the other hand, if I remove the render() from the component, I get this error:

Footer(...): No render method found on the returned component instance: you may have forgotten to define render.

One thing I forgot to mention before, and also based on the item 2 of @aks answer, about using plaing html to create the links is that it's going to reload the whole page if I don't use the React router I'm currently using.

So, for example, If I create a link on the fotter with plain html like this:

```<code><a href="/contact">Contact</a>
</code>```

When clicking on the link everything else is going to reset, because the page is going to refresh.

This is why it would be better to just use a function from a component instead of using the whole html declared inside the component.

答:
Nice question. I will answer your question in points:

Render method is a required method, you cannot do without it, it can return null, as you are already doing.

If you say that your footer is static markup and links to some part, You don't even need the js file. It is not required.

In case you have components for most other parts, the static content may look too verbose. You can put those content in the render method of the Footer component as make the index.html very clean. Then in case you need more features in future, you can add them safely.

I hope that helps!

Body:
I'm very very new to react (still learning). One thing I noticed is that component always have a return with HTML (jsx) as content.

But I was wondering if it's possible to create a component containing only functions. For example, in my footer I only have static content. Just plain text and a button to go to the homepage. So this is what I'm trying to do:

index.html

        <button onClick={this.onButton}>Home</button>

Footer.js

class Footer extends React.Component {
    onButton() {
        console.log('Button clicked');
    }

    render() {
        console.log('render');
        return null;
    }
}

render(, window.document.getElementById("footer"));

This way, the component gets executed and I can see the log, however, the button defined in the index.html is removed.

On the other hand, if I remove the render() from the component, I get this error:

Footer(...): No render method found on the returned component instance: you may have forgotten to define render.

One thing I forgot to mention before, and also based on the item 2 of @aks answer, about using plaing html to create the links is that it's going to reload the whole page if I don't use the React router I'm currently using.

So, for example, If I create a link on the fotter with plain html like this:

Contact

When clicking on the link everything else is going to reset, because the page is going to refresh.

This is why it would be better to just use a function from a component instead of using the whole html declared inside the component.


问:
How to get pitches from a wav buffer in JAVA - Fast Fourier Transform
I am new to signal processing and am trying to detect the pitches in a wav file. I generated a 2-channel wav file that plays 3 distinct notes in 1 second. I was able to read the wave using a class a java and have a double array:

```<code>-0.12847900390625
-0.161651611328125
-0.161651611328125
-0.1907958984375
-0.1907958984375
-0.215179443359375
-0.215179443359375
       .
       .
       .
</code>```

I was to get the notes that are being played in the double array. I have googled around and believe a Fast Fourier Transform is the way to go. However, I am a bit unsure what this Transformation does.

Does FFT return the frequency at a given time period?

Any help is appreciated. Thankyou

答:
The Discrete Fourier Transform is used to map any discrete time-domain signal into frequency domain to reduce computation while performing operations like  convolution, co-relation etc since it is easier to compute in frequency domain and take the inverse transform and convert back into time domain compared to direct operation in time domain.
FFT is the simpler algorithmic implementation of DFT with reduced time complexity of  O(nlogn)compared to time complexity of DFT O(n^2).

You can find more details here:

http://www.dspguide.com/ch12/2.htm

Body:
I am new to signal processing and am trying to detect the pitches in a wav file. I generated a 2-channel wav file that plays 3 distinct notes in 1 second. I was able to read the wave using a class a java and have a double array:

-0.12847900390625
-0.161651611328125
-0.161651611328125
-0.1907958984375
-0.1907958984375
-0.215179443359375
-0.215179443359375
       .
       .
       .

I was to get the notes that are being played in the double array. I have googled around and believe a Fast Fourier Transform is the way to go. However, I am a bit unsure what this Transformation does.

Does FFT return the frequency at a given time period?

Any help is appreciated. Thankyou


问:
Why is using JavaScript to plan Q1 year 22034 unreliable in Safari?
There is something fishy about the calculation of far future dates when done on the browser side (Safari 5.0.1), passing strings into the Date() constructor:

I narrowed it down to the February-March transition in year 22034:

```<code>d = new Date('1 Mar 22034')
Tue Feb 28 22034 00:00:00 GMT+0000 (GMT)
</code>```

Feeding it any later date, the constructor always returns a Date object off-by-one day!

What about earlier dates? The last day in February looks good:

```<code>d=new Date('28 Feb 22034')
Tue Feb 28 22034 00:00:00 GMT+0000 (GMT)
</code>```

My gut-feeling tells me that looks like a leap-year related bug. But what is the pattern in play here, what could be the explanation of the bug?

Edit:

How about if we ask for February 29th?

```<code>d=new Date('29 Feb 22034')
Wed Mar 01 22034 00:00:00 GMT+0000 (GMT)
</code>```

That returns the last of Feb + 1 day (its standard behavior).

答:
It's because the date format you're giving new Date() is non-standard. The fact you're getting anything is because Safari is doing you a favor. (See section 15.9.1.15 of the spec for valid formats; basically a simplified ISO-8601. And having any standard for parsing date/time strings is relatively new [5th edition].)

If you use a standard constructor, e.g., new Date (22034, 2, 1) (months start at zero, so that's March 1, 22034), it works fine. You can test it like this (live copy):

```<code>display("With non-standard string: " + new Date("1 Mar 22034"));
display("Using standard constructor: " + new Date(22034, 2, 1));
</code>```

Which for me using Safari for Windows results in:

With non-standard string: Tue Feb 28 22034 00:00:00 GMT+0000 (GMT Standard Time)

Using standard constructor: Wed Mar 01 22034 00:00:00 GMT+0000 (GMT Standard Time)

As you can see, the first line shows the incorrect date, while the second line shows the correct one.

The standard constructor also works correctly in Chrome, Opera, and Firefox (all under Ubuntu), IE6, IE7, and IE8: http://jsbin.com/ogiqu

If it were really true that Safari couldn't handle that date (as opposed to not parsing the non-standard string you gave it reliably), it would be a surprising Safari-specific bug. From section 15.9.1.1 of the spec:

Time is measured in ECMAScript in milliseconds since 01 January, 1970 UTC. In time values leap seconds
  are ignored. It is assumed that there are exactly 86,400,000 milliseconds per day. ECMAScript Number values
  can represent all integers from –9,007,199,254,740,991 to 9,007,199,254,740,991; this range suffices to
  measure times to millisecond precision for any instant that is within approximately 285,616 years, either
  forward or backward, from 01 January, 1970 UTC.

But as Safari seems to handle it fine when you don't ask it to go off-piste, apparently the problem is in the parsing code for non-standard strings.

Body:
There is something fishy about the calculation of far future dates when done on the browser side (Safari 5.0.1), passing strings into the Date() constructor:

I narrowed it down to the February-March transition in year 22034:

d = new Date('1 Mar 22034')
Tue Feb 28 22034 00:00:00 GMT+0000 (GMT)

Feeding it any later date, the constructor always returns a Date object off-by-one day!

What about earlier dates? The last day in February looks good:

d=new Date('28 Feb 22034')
Tue Feb 28 22034 00:00:00 GMT+0000 (GMT)

My gut-feeling tells me that looks like a leap-year related bug. But what is the pattern in play here, what could be the explanation of the bug?

Edit:

How about if we ask for February 29th?

d=new Date('29 Feb 22034')
Wed Mar 01 22034 00:00:00 GMT+0000 (GMT)

That returns the last of Feb + 1 day (its standard behavior).

Body:
It's because the date format you're giving new Date() is non-standard. The fact you're getting anything is because Safari is doing you a favor. (See section 15.9.1.15 of the spec for valid formats; basically a simplified ISO-8601. And having any standard for parsing date/time strings is relatively new [5th edition].)

If you use a standard constructor, e.g., new Date (22034, 2, 1) (months start at zero, so that's March 1, 22034), it works fine. You can test it like this (live copy):

display("With non-standard string: " + new Date("1 Mar 22034"));
display("Using standard constructor: " + new Date(22034, 2, 1));

Which for me using Safari for Windows results in:

With non-standard string: Tue Feb 28 22034 00:00:00 GMT+0000 (GMT Standard Time)

Using standard constructor: Wed Mar 01 22034 00:00:00 GMT+0000 (GMT Standard Time)

As you can see, the first line shows the incorrect date, while the second line shows the correct one.

The standard constructor also works correctly in Chrome, Opera, and Firefox (all under Ubuntu), IE6, IE7, and IE8: http://jsbin.com/ogiqu

If it were really true that Safari couldn't handle that date (as opposed to not parsing the non-standard string you gave it reliably), it would be a surprising Safari-specific bug. From section 15.9.1.1 of the spec:

Time is measured in ECMAScript in milliseconds since 01 January, 1970 UTC. In time values leap seconds
  are ignored. It is assumed that there are exactly 86,400,000 milliseconds per day. ECMAScript Number values
  can represent all integers from –9,007,199,254,740,991 to 9,007,199,254,740,991; this range suffices to
  measure times to millisecond precision for any instant that is within approximately 285,616 years, either
  forward or backward, from 01 January, 1970 UTC.

But as Safari seems to handle it fine when you don't ask it to go off-piste, apparently the problem is in the parsing code for non-standard strings.


问:
How do i make vector usable in subprograms? (C)
This is a subprogram which should to take the values from a main program, but "intervalo" is a vector, doesn't seem to work the same way as the variables.

```<code>void valores(min, max, intrevalo)
{
    int i=0;

    while (intrevalo[i] >= min && intrevalo[i] <= max)
    {
        i++;
    }
}
main()
{
int v_numeros[700];
int numero;
int min=0;
int max=500;
int i=0;

FILE*f_Numeros;

f_Numeros = fopen("numeros.txt", "r");
if (f_Numeros == NULL)
    perror("Erro, nao foi possivel abrir o ficheiro \n");
else
    while((fscanf (f_Numeros, "%d \n", &numero)) != EOF)
    {
        v_numeros[i] = numero;
        i++;
    }
    scanf("%d", &min);
    scanf("%d", &max);

 valores(min, max,v_numeros);
 fclose(f_Numeros);
 return 0;
 }
</code>```

Here is the full code, needed to create those sub programs, I just don't know how to use the vector in the subprogram.

答:
It looks like instead of the syntactically invalid (types are missing)

```<code>void valores(min, max, intrevalo)
</code>```

you need

```<code>void valores(int min, int max, int *intrevalo)
</code>```

Body:
This is a subprogram which should to take the values from a main program, but "intervalo" is a vector, doesn't seem to work the same way as the variables.

void valores(min, max, intrevalo)
{
    int i=0;

    while (intrevalo[i] >= min && intrevalo[i] <= max)
    {
        i++;
    }
}
main()
{
int v_numeros[700];
int numero;
int min=0;
int max=500;
int i=0;

FILE*f_Numeros;

f_Numeros = fopen("numeros.txt", "r");
if (f_Numeros == NULL)
    perror("Erro, nao foi possivel abrir o ficheiro \n");
else
    while((fscanf (f_Numeros, "%d \n", &numero)) != EOF)
    {
        v_numeros[i] = numero;
        i++;
    }
    scanf("%d", &min);
    scanf("%d", &max);

 valores(min, max,v_numeros);
 fclose(f_Numeros);
 return 0;
 }

Here is the full code, needed to create those sub programs, I just don't know how to use the vector in the subprogram.

Body:
It looks like instead of the syntactically invalid (types are missing)

void valores(min, max, intrevalo)

you need

void valores(int min, int max, int *intrevalo)


问:
Codeigniter object not found error
I have made a login system, but when i click on "login" i got this error message:
"error 404 object not found".

I do not know whatto do now :S.

Here is my code:

My login file (the main file with the buttons)

```<code><!DOCTYPE html>
<html lang="">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>WELCOME! » Jaranguda.com</title>
<link rel="stylesheet" href="https://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>

</head>

    <body>
        <div class="container">
        <h3>Login</h3>
        <hr>
        <form action="<?php echo base_url('Login/user')?>" method="POST">
            <div class="form-group">
                <label for="cari">USERNAME</label>
                <input type="text" name="usuario" id="usuario" class="form-control">

            </div>

            <div class="form-group">
                <label for="cari">PASSWORD</label>
                <input type="password" name="contrasena" id="contrasena" class="form-control">

            </div>

            <input class="btn btn-primary" type="submit" value="Login">
            <input class="btn btn-primary" type="reset" value="Reset">

        </form>
            </div>

    </body>
</code>```

The controller file:

```<code><?php

    class Login extends CI_Controller{

     public function __construct(){
         parent::__construct();
         $this->load->model("Login_model");

    }

    public function index(){

        $this->load->view("login");

    }

    public function user(){

        $data['login']=$this->Login_model->login();
        $this->load->view('user', $data);

    }

    }

?>
</code>```

The model file:

```<code><?php

class Login_model extends CI_Model{

    public function __construct(){

     $this->load->database();

    }

    public function login(){

        $usuario=$this->input->POST('usuario', TRUE);
        $contrasena=md5($this->input->POST('contrasena', TRUE));
        $data=$this->db->query("SELECT * from usuarios where usuario=$usuario and contrasena=$contrasena LIMIT 1");
        return $data=row();

      }

}

?>
</code>```

The user file:

```<code>    <!DOCTYPE html>
    <html lang="">

    <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>BIENVENIDO! » Jaranguda.com</title>
    <link rel="stylesheet" href="https://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css">
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js">
    </script>

    </head>

        <body>
            <div class="container">
            <h3>Login</h3>
            <hr>

<?php
if(count($login)>0)
{
    if($login->tipo=='0')
        echo "<p>YOU LOGGED AS: <b>".$login->tipo."</p>"

}

    elseif($login->tipo =='1'){

        echo "<p>usuario <b>".$login->usuario."</b> LOGGED AS: <b>".$login->tipo."</p>"

    }

    else{

        echo "<p>usuario <b>".$login->usuario."</b> SOMETHING WENT WRONG WHILE LOGGING</p>"

    }

?>

<?php

}
else
{

    echo "<p>USERNAME/PASSWORD INVALID.</p>"

}

?>

    </div>

<script src="//code.jquery.com/jquery.js"></script>

<script src="//netdna.bootstrapcdn.com/bootstrap/3.0.3/js/bootstrap.min.js"></script>

</body>

</html>
</code>```

Hope you can help me :S

答:
Your login method should in Login_model return :

```<code> return $data->row();
</code>```

not :

```<code>return $data = row();
</code>```

Edit

You need to pass the user info to your mode:

this two line should be in your controller:

```<code>  public function user(){
        $usuario=$this->input->post('usuario', TRUE);
        $contrasena=md5($this->input->post('contrasena', TRUE));
        $data['login']=$this->Login_model->login($usuario, $contrasena);
        $this->load->view('user', $data);
    }
</code>```

and your model :

```<code> public function login($usuario, $contrasena) {
   $this->db->where('usuario',$usuario);
   $this->db->where('contrasena',$contrasena);
   $query = $this->db->get("your_table_name");
   return $query->row_array();
}
</code>```

Title: Codeigniter object not found error

Body:
I have made a login system, but when i click on "login" i got this error message:
"error 404 object not found".

I do not know whatto do now :S.

Here is my code:

My login file (the main file with the buttons)

<!DOCTYPE html>

<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>WELCOME! » Jaranguda.com</title>
<link rel="stylesheet" href="https://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css">

Login

        <form action="<?php echo base_url('Login/user')?>" method="POST">

                USERNAME
                <input type="text" name="usuario" id="usuario" class="form-control">

                PASSWORD
                <input type="password" name="contrasena" id="contrasena" class="form-control">

            <input class="btn btn-primary" type="submit" value="Login">
            <input class="btn btn-primary" type="reset" value="Reset">

        </form>

The controller file:

<?php

    class Login extends CI_Controller{

     public function __construct(){
         parent::__construct();
         $this->load->model("Login_model");

    }

    public function index(){

        $this->load->view("login");

    }

    public function user(){

        $data['login']=$this->Login_model->login();
        $this->load->view('user', $data);

    }

    }

?>

The model file:

<?php

class Login_model extends CI_Model{

    public function __construct(){

     $this->load->database();

    }

    public function login(){

        $usuario=$this->input->POST('usuario', TRUE);
        $contrasena=md5($this->input->POST('contrasena', TRUE));
        $data=$this->db->query("SELECT * from usuarios where usuario=$usuario and contrasena=$contrasena LIMIT 1");
        return $data=row();

      }

}

?>

The user file:

    <!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>BIENVENIDO! » Jaranguda.com</title>
    <link rel="stylesheet" href="https://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css">

Login

<?php
if(count($login)>0)
{
    if($login->tipo=='0')
        echo "
YOU LOGGED AS: ".$login->tipo."
"

}

    elseif($login->tipo =='1'){

        echo "
usuario ".$login->usuario." LOGGED AS: ".$login->tipo."
"

    }

    else{

        echo "
usuario ".$login->usuario." SOMETHING WENT WRONG WHILE LOGGING
"

    }

?>

<?php

}
else
{

    echo "
USERNAME/PASSWORD INVALID.
"

}

?>

Hope you can help me :S

Body:
Your login method should in Login_model return :

 return $data->row();

not :

return $data = row();

Edit

You need to pass the user info to your mode:

this two line should be in your controller:

  public function user(){
        $usuario=$this->input->post('usuario', TRUE);
        $contrasena=md5($this->input->post('contrasena', TRUE));
        $data['login']=$this->Login_model->login($usuario, $contrasena);
        $this->load->view('user', $data);
    }

and your model :

 public function login($usuario, $contrasena) {
   $this->db->where('usuario',$usuario);
   $this->db->where('contrasena',$contrasena);
   $query = $this->db->get("your_table_name");
   return $query->row_array();
}


问:
Join/Merge data frames on inconsistent time stamps with long and wide data
I have two data frames,

df3 has a time stamp with date and time, user id, and heart rate with multiple observations (long data)

df4 has a time stamp with date only, user id, calories and sleep (wide data)

I would like to combine them so that the data frame with long data can be filled in with the data frame with wide data based on the date and user id

Here is the code for a toy data set with a similar layout

```<code>df3 <- data.frame(  time_stamp=c('2016-11-01 10:29:41','2016-11-01 10:53:11','2016-11-02 01:07:54','2016-11-02 02:00:40','2016-11-02 04:01:33','2016-11-02 05:23:53','2016-11-02 13:20:17'),
               users_user_id=c(7,7,7,7,7,7,7),
               avg_heart_rate=c(94,90,88,85,91,89,95))
df4 <- data.frame(  time_stamp=c('2016-11-01','2016-11-02'), users_user_id=c(7,7), calories=c(1800,2000), sleep=c(480,560))
df3$time_stamp <- as.POSIXct(df3$time_stamp)
df4$time_stamp <- as.POSIXct(df4$time_stamp)
</code>```

I tried splitting the time from the date, but then when I did a full_join on dplyr using the time stamp and userID I was left with a lot of NAs. I tried looking up how to use reshape2 to melt my data? but I'm lost as to how it could help me...

Body:
I have two data frames,

df3 has a time stamp with date and time, user id, and heart rate with multiple observations (long data)

df4 has a time stamp with date only, user id, calories and sleep (wide data)

I would like to combine them so that the data frame with long data can be filled in with the data frame with wide data based on the date and user id

Here is the code for a toy data set with a similar layout

df3 <- data.frame(  time_stamp=c('2016-11-01 10:29:41','2016-11-01 10:53:11','2016-11-02 01:07:54','2016-11-02 02:00:40','2016-11-02 04:01:33','2016-11-02 05:23:53','2016-11-02 13:20:17'),
               users_user_id=c(7,7,7,7,7,7,7),
               avg_heart_rate=c(94,90,88,85,91,89,95))
df4 <- data.frame(  time_stamp=c('2016-11-01','2016-11-02'), users_user_id=c(7,7), calories=c(1800,2000), sleep=c(480,560))
df3$time_stamp <- as.POSIXct(df3$time_stamp)
df4$time_stamp <- as.POSIXct(df4$time_stamp)

I tried splitting the time from the date, but then when I did a full_join on dplyr using the time stamp and userID I was left with a lot of NAs. I tried looking up how to use reshape2 to melt my data? but I'm lost as to how it could help me...

Body:
A tidyverse way:

library(tidyr)
library(dplyr)

df3 <- separate(df3, time_stamp, into = c("date_stamp", "time_stamp"), sep = " ")
df3$date_stamp <- as.POSIXct(df3$date_stamp)

left_join(df3, df4, by = c("date_stamp" = "time_stamp", "users_user_id"))

  date_stamp time_stamp users_user_id avg_heart_rate calories sleep
  1 2016-11-01   10:29:41             7             94     1800   480
  2 2016-11-01   10:53:11             7             90     1800   480
  3 2016-11-02   01:07:54             7             88     2000   560
  4 2016-11-02   02:00:40             7             85     2000   560
  5 2016-11-02   04:01:33             7             91     2000   560
  6 2016-11-02   05:23:53             7             89     2000   560
  7 2016-11-02   13:20:17             7             95     2000   560


问:
RuntimeException : only ACLs can be stored in the ACL key in android
In android i am using Parse and back4app.com for my back-end, whenever i use myParseobject.saveInBackground() in the return Save Callback i am getting error message that ParseException : only ACLs can be stored in the ACL key If anyone have idea about this please share.

答:
To avoid this error, I set ACLs for currentUser after its login. Surprisingly, it does help and I don't see any errors on that session when saving objects.</p>

```<code>// default ACLs for User object
ParseACL parseACL = new ParseACL(ParseUser.getCurrentUser());
parseACL.setPublicReadAccess(true);

ParseUser.getCurrentUser().setACL(parseACL);
</code>```

Body:
To avoid this error, I set ACLs for currentUser after its login. Surprisingly, it does help and I don't see any errors on that session when saving objects.

// default ACLs for User object
ParseACL parseACL = new ParseACL(ParseUser.getCurrentUser());
parseACL.setPublicReadAccess(true);

ParseUser.getCurrentUser().setACL(parseACL);


问:
karma Test : TypeError: Cannot read property 'map' of undefined
I'm trying to test a ReactiveFormsControle with a separate formControle file dependency that contain the control form function. I need to use an observable to pass the form controls and returning messages errors after that. But when I tried to test that I have this error: TypeError: Cannot read property 'map' of undefined

Can any one help me please.

this is my code :

This is how can I call the Form control function(process Message) :

```<code>ngAfterViewInit(): void {
// Watch for the blur event from any input element on the form.
let controlBlurs: Observable<any>[] = this.formInputElements
  .map((formControl: ElementRef) => Observable.fromEvent(formControl.nativeElement, 'blur'));
// Merge the blur event observable with the valueChanges observable
Observable.merge(this.signUpForm.valueChanges, ...controlBlurs).debounceTime(1000).subscribe(value => {
  this.displayeErrorMessage = this.formValidator.processMessages(this.signUpForm);
});
</code>```

}

processMessage function:

```<code>  processMessages(container : FormGroup) : {[key : string]: string}{

let messages = {};

for(let controlKey in container.controls){
  if(container.controls.hasOwnProperty(controlKey)){
    let c = container.controls[controlKey];

    if(c instanceof FormGroup){
      let childMessages = this.processMessages(c);
      Object.assign(messages, childMessages);
    }else {

      if(this.validationErrorMessages[controlKey]){
        messages[controlKey]='';
        if((c.dirty || c.touched) && c.errors){
          Object.keys(c.errors).map(messageKey =>{
            if(this.validationErrorMessages[controlKey][messageKey]){
              messages[controlKey] += this.validationErrorMessages[controlKey][messageKey] + ' '
            }
          })
        }
      }
    }
  }
}
return messages;
</code>```

}

* this the test code that handle the error *

```<code> beforeEach(() => {
fixture = TestBed.createComponent(SignUpComponent);
component = fixture.componentInstance;
debugHelpblck = fixture.debugElement.queryAll(By.css('.help-block'));
component.ngOnInit();
component.ngAfterViewInit(); // this handle the error
fixture.detectChanges();
</code>```

});

答:
Add filter(Boolean) before map(), or be more careful with your data (;

Not sure where your error appears, if this is all the code then:

```<code>let controlBlurs: Observable<any>[] = this.formInputElements
  .filter(Boolean)
  .map(...)
</code>```

or

```<code>Object.keys(c.errors).filter(Boolean).map(messageKey =>{...})
</code>```

should fix the error...

Body:
I'm trying to test a ReactiveFormsControle with a separate formControle file dependency that contain the control form function. I need to use an observable to pass the form controls and returning messages errors after that. But when I tried to test that I have this error: TypeError: Cannot read property 'map' of undefined

Can any one help me please.

this is my code :

This is how can I call the Form control function(process Message) :

ngAfterViewInit(): void {
// Watch for the blur event from any input element on the form.
let controlBlurs: Observable<any>[] = this.formInputElements
  .map((formControl: ElementRef) => Observable.fromEvent(formControl.nativeElement, 'blur'));
// Merge the blur event observable with the valueChanges observable
Observable.merge(this.signUpForm.valueChanges, ...controlBlurs).debounceTime(1000).subscribe(value => {
  this.displayeErrorMessage = this.formValidator.processMessages(this.signUpForm);
});

}

processMessage function:

  processMessages(container : FormGroup) : {[key : string]: string}{

let messages = {};

for(let controlKey in container.controls){
  if(container.controls.hasOwnProperty(controlKey)){
    let c = container.controls[controlKey];

    if(c instanceof FormGroup){
      let childMessages = this.processMessages(c);
      Object.assign(messages, childMessages);
    }else {

      if(this.validationErrorMessages[controlKey]){
        messages[controlKey]='';
        if((c.dirty || c.touched) && c.errors){
          Object.keys(c.errors).map(messageKey =>{
            if(this.validationErrorMessages[controlKey][messageKey]){
              messages[controlKey] += this.validationErrorMessages[controlKey][messageKey] + ' '
            }
          })
        }
      }
    }
  }
}
return messages;

}

* this the test code that handle the error *

 beforeEach(() => {
fixture = TestBed.createComponent(SignUpComponent);
component = fixture.componentInstance;
debugHelpblck = fixture.debugElement.queryAll(By.css('.help-block'));
component.ngOnInit();
component.ngAfterViewInit(); // this handle the error
fixture.detectChanges();

});

Body:
Add filter(Boolean) before map(), or be more careful with your data (;

Not sure where your error appears, if this is all the code then:

let controlBlurs: Observable<any>[] = this.formInputElements
  .filter(Boolean)
  .map(...)

or

Object.keys(c.errors).filter(Boolean).map(messageKey =>{...})

should fix the error...


问:
Choose default file onchange JavaScript
I got a HTML file which just asks to choose a XML file onchange
How can I change this to choose a single file on default</p>

```<code><form id='fileSelection' action="">
<center>
<input type='file' id='ipfile'
name='selectedFileName'
accept='text/xml'
onchange='javascript:selectXmlFile();'>
</center>
</form>
</code>```

答:
You can put your default file in the value property of the input:

```<code><input type="file" value="defaultpath/defaultfile.xml">
</code>```

Title: Choose default file onchange JavaScript

Body:
I got a HTML file which just asks to choose a XML file onchange
How can I change this to choose a single file on default

<form id='fileSelection' action="">

<input type='file' id='ipfile'
name='selectedFileName'
accept='text/xml'
onchange='javascript:selectXmlFile();'>

</form>

Body:
You can put your default file in the value property of the input:

<input type="file" value="defaultpath/defaultfile.xml">


问:
UIBarButtonItem - Argument of '#selector' cannot refer to local function - Swift 3
I am having a problem with creating a nav button that would call handleSearch function. I receive a message Argument of '#selector' cannot refer to local function. Any help would be appreciated!

```<code>override func viewDidLoad() {
   // various code

   func setupNavBarButtons() {
       let searchImage = UIImage(named:"search_icon")
       let searchBarButtonItem = UIBarButtonItem(image: searchImage, style: .plain, target: self, action: #selector(handleSearch(sender:)))
        navigationItem.rightBarButtonItems = [searchBarButtonItem]

    }

    func handleSearch(sender: UIBarButtonItem) {
        print(123)
    }
}
</code>```

答:
#selector can only reference a top-level function, not a local function (one inside another function).

Simply move handleSearch out of viewDidLoad and your problem will be solved.

Body:
I am having a problem with creating a nav button that would call handleSearch function. I receive a message Argument of '#selector' cannot refer to local function. Any help would be appreciated!

override func viewDidLoad() {
   // various code

   func setupNavBarButtons() {
       let searchImage = UIImage(named:"search_icon")
       let searchBarButtonItem = UIBarButtonItem(image: searchImage, style: .plain, target: self, action: #selector(handleSearch(sender:)))
        navigationItem.rightBarButtonItems = [searchBarButtonItem]

    }

    func handleSearch(sender: UIBarButtonItem) {
        print(123)
    }
}


问:
mongoose Getting a nested field value from a queried document
I am new to Node js and Mongoose and I am stuck with this one query.

```<code>exports.getIndividual=(matchId,phone)=>
 new Promise((resolve,reject)=>{
 var e="matchPersonal.m"+matchId+".bo1";
 query={};
 query[e]=1;

 var quer=usersc.findOne({phone:"8989898980"}).select(query);
 quer.exec(function (err, matc) {

 var m=matc.toObject();

 console.log('',m);
</code>```

When I Run this query I get on my console this thing

```<code>        {matchPersonal:{m1:{bo1:3}}}
</code>```

But I just need 3 as my output and I cant use dot operator to read the object properties directly because

```<code>   var b=matchPersonal.m+matchId.bo1
</code>```

doesnt work as '+' cant be used here so please help

答:
Try:

```<code>var mNum = m+matchId;
var b=matchPersonal[mNum].bo1
</code>```

Because you can select properties with dot and with brackets, but brackets also can be used with variables.

Body:
I am new to Node js and Mongoose and I am stuck with this one query.

exports.getIndividual=(matchId,phone)=>
 new Promise((resolve,reject)=>{
 var e="matchPersonal.m"+matchId+".bo1";
 query={};
 query[e]=1;

 var quer=usersc.findOne({phone:"8989898980"}).select(query);
 quer.exec(function (err, matc) {

 var m=matc.toObject();

 console.log('',m);

When I Run this query I get on my console this thing

        {matchPersonal:{m1:{bo1:3}}}

But I just need 3 as my output and I cant use dot operator to read the object properties directly because

   var b=matchPersonal.m+matchId.bo1

doesnt work as '+' cant be used here so please help

Body:
Try:

var mNum = m+matchId;
var b=matchPersonal[mNum].bo1

Because you can select properties with dot and with brackets, but brackets also can be used with variables.


问:
Apply patch to JBoss 5.1.0 GA
I would like to add the patch to a JBoss 5.1.0 GA installation in order to do some tests.

My question : How can I add this patch? Couldn't find anything revlevant so far.

Thank you.

答:
You need to get the JBoss EJB3 source code, apply the patch to it, build the patched source code, and replace the existing code in your JBoss implementation.

This is not for the faint of heart! However, JBoss do provide instructions for getting the source and building, so give it a try.

Title: Apply patch to JBoss 5.1.0 GA


问:
Copy Value of Local into Pointer
Trying to find the correct way to do this, but can't seem to find the correct syntax anywhere..

all I want to do is copy the the value of a local variable into a pointer, so I may use that pointer anywhere. Otherwise when the method returns the value of the that pointer will be unpredictable.. Heres what I have but it seems to still just reference the address of the local variable

```<code>void method(){

 unsigned int localValue = 0x00FF00AA;
 unsigned int *point = (unsigned int *) 0x00000000;
 *point = localValue;
}
</code>```

but this code just seg faults. Is there a way to do this?

答:
```<code>point = (unsigned int*) localValue;
</code>```

The variable "point" (being a pointer) is set to the value of the variable "localValue".

To do that, a type cast is recommended, to tell the compiler that this unsigned integer value is now the address to an unsigned integer. Accepting input from a comment: the cast is required.

If you use the pointer later be careful.

Make sure that the integer value is an address of a part of memory which you really want to use; especially when writing.

It is probably OK if it happens for example to be a writeable memory-mapped peripheral register on a microcontroller.

Title: Copy Value of Local into Pointer

Body:
Trying to find the correct way to do this, but can't seem to find the correct syntax anywhere..

all I want to do is copy the the value of a local variable into a pointer, so I may use that pointer anywhere. Otherwise when the method returns the value of the that pointer will be unpredictable.. Heres what I have but it seems to still just reference the address of the local variable

void method(){

 unsigned int localValue = 0x00FF00AA;
 unsigned int *point = (unsigned int *) 0x00000000;
 *point = localValue;
}

but this code just seg faults. Is there a way to do this?

Body:
point = (unsigned int*) localValue;

The variable "point" (being a pointer) is set to the value of the variable "localValue".

To do that, a type cast is recommended, to tell the compiler that this unsigned integer value is now the address to an unsigned integer. Accepting input from a comment: the cast is required.

If you use the pointer later be careful.

Make sure that the integer value is an address of a part of memory which you really want to use; especially when writing.

It is probably OK if it happens for example to be a writeable memory-mapped peripheral register on a microcontroller.


问:
Change the definition of a word in Python Tkinter?
When double clicking a word in a Text-widget the clicked word is selected. Tkinter's understanding of what a word is, however, is impractical for my use case.

Effbot explains what Tkinter considers to be a word but not how to change that. Is it possible to change Tkinter's definition of a word so that it recognizes hyphens as part of a word? I.e. I would like to select a text like --help or --version or -U with a double click.

答:
In the answer that curtisk has provided a link to Bryan Oakley states that this is not possible:

You can't modify how "wordstart" defines "words".

But based on his answer I have developed the following method select_current_word, the code around is just to illustrate it's usage.

```<code>import Tkinter as tk

class MyText(tk.Text):

     def __init__(self, **kw):
         tk.Text.__init__(self, **kw)
         self.bind('<Double-Button-1>', self.select_current_word)

     def select_current_word(self, event):
         i0 = self.search(r'[-\w]+', tk.CURRENT+'+1c', backwards=True, regexp=True)
         i1 = self.search(r'[^-\w]+', i0, forwards=True, regexp=True)
         self.tag_remove(tk.SEL, '1.0', tk.END)
         self.tag_add(tk.SEL, i0, i1)
         self.update()
         return 'break'

if __name__=='__main__':
     t = MyText()
     t.pack(expand=True, fill=tk.BOTH)
     t.insert('1.0', """
Options:
  General Options:
     -h, --help                       Print this help text and exit
     --version                        Print program version and exit
     -U, --update                     Update this program to latest version.
""".strip())
     t.mainloop()
</code>```

Body:
In the answer that curtisk has provided a link to Bryan Oakley states that this is not possible:

You can't modify how "wordstart" defines "words".

But based on his answer I have developed the following method select_current_word, the code around is just to illustrate it's usage.

import Tkinter as tk

class MyText(tk.Text):

     def __init__(self, **kw):
         tk.Text.__init__(self, **kw)
         self.bind('<Double-Button-1>', self.select_current_word)

     def select_current_word(self, event):
         i0 = self.search(r'[-\w]+', tk.CURRENT+'+1c', backwards=True, regexp=True)
         i1 = self.search(r'[^-\w]+', i0, forwards=True, regexp=True)
         self.tag_remove(tk.SEL, '1.0', tk.END)
         self.tag_add(tk.SEL, i0, i1)
         self.update()
         return 'break'

if __name__=='__main__':
     t = MyText()
     t.pack(expand=True, fill=tk.BOTH)
     t.insert('1.0', """
Options:
  General Options:
     -h, --help                       Print this help text and exit
     --version                        Print program version and exit
     -U, --update                     Update this program to latest version.
""".strip())
     t.mainloop()