问:
Create a bean in blueprint from an external bundle
I am using Camel in Karaf with blueprint xml and I want to create a bean with the class coming from a different bundle.

```<code><blueprint>
   ...
   <bean id="token-validation" class="com.xxx.security.JwtTokenValidator" init-method="init" >
      <property name="realm" value="${auth.realm}"/>
   </bean>
   ...
   <camelContext>
      <route id="route.EventsNotify" routePolicyRef="token-validation">
      ...
   </camelContext>
</blueprint>
</code>```

JwtTokenValidator class is located in another bundle, that extends the Camel's RoutePolicySupport, that's why it is applied in route route.EventsNotify.

```<code>    public class JwtTokenValidator extends RoutePolicySupport {
       @Override
       public void onExchangeBegin(Route route, Exchange exchange) {
          super.onExchangeBegin(route, exchange);
          checkAuthorizationHeader(exchange);
       }
      ...
   }
</code>```

This bundle has some dependencies and classes like the aforementioned one, in order to be used in many projects. Write once and applied in many projects instead of coping the same code again and again.

Unfortunately this is not working, I am getting the following error in stacktrace

```<code>Caused by: java.lang.ClassCastException: Cannot cast com.xxx.security.JwtTokenValidator to org.apache.camel.spi.RoutePolicy
</code>```

I cannot understand why, because the class is extending RoutePolicySupport which in terms implements the desired RoutePolicy interface.

If I move the class to the same bundle it is working, but I need to have it in a seperate bundle for the reasons that I explained before.

Could someone tells me where I am wrong?

Thanks a lot!

答:
Try to import all required Classes (org.apache.camel.spi.RoutePolicy, ...) to current Bundle's classLoader. If you are building your bundle with maven-bundle plugin, you can do it like this:</p>

```<code>     <plugin>
        <groupId>org.apache.felix</groupId>
        <artifactId>maven-bundle-plugin</artifactId>
        ...
        <configuration>
          <instructions>
            ...
            <Import-Package>
              ...,
              org.apache.camel.spi*;version=[min_version, max_version),
              ...
            </Import-Package>
          </instructions>
        </configuration>
      </plugin>
</code>```

Body:
I am using Camel in Karaf with blueprint xml and I want to create a bean with the class coming from a different bundle.

<blueprint>
   ...
   <bean id="token-validation" class="com.xxx.security.JwtTokenValidator" init-method="init" >
      <property name="realm" value="${auth.realm}"/>
   </bean>
   ...
   <camelContext>
      <route id="route.EventsNotify" routePolicyRef="token-validation">
      ...
   </camelContext>
</blueprint>

JwtTokenValidator class is located in another bundle, that extends the Camel's RoutePolicySupport, that's why it is applied in route route.EventsNotify.

    public class JwtTokenValidator extends RoutePolicySupport {
       @Override
       public void onExchangeBegin(Route route, Exchange exchange) {
          super.onExchangeBegin(route, exchange);
          checkAuthorizationHeader(exchange);
       }
      ...
   }

This bundle has some dependencies and classes like the aforementioned one, in order to be used in many projects. Write once and applied in many projects instead of coping the same code again and again.

Unfortunately this is not working, I am getting the following error in stacktrace

Caused by: java.lang.ClassCastException: Cannot cast com.xxx.security.JwtTokenValidator to org.apache.camel.spi.RoutePolicy

I cannot understand why, because the class is extending RoutePolicySupport which in terms implements the desired RoutePolicy interface.

If I move the class to the same bundle it is working, but I need to have it in a seperate bundle for the reasons that I explained before.

Could someone tells me where I am wrong?

Thanks a lot!

Body:
Try to import all required Classes (org.apache.camel.spi.RoutePolicy, ...) to current Bundle's classLoader. If you are building your bundle with maven-bundle plugin, you can do it like this:

     <plugin>
        <groupId>org.apache.felix</groupId>
        <artifactId>maven-bundle-plugin</artifactId>
        ...
        <configuration>
          <instructions>
            ...
            <Import-Package>
              ...,
              org.apache.camel.spi*;version=[min_version, max_version),
              ...
            </Import-Package>
          </instructions>
        </configuration>
      </plugin>


来源: stackexchange

问:
Remove trailing whitespace recursively only at end of file using grep/sed?
Basically, I've got about 1,500 files and the last character of any of these files should not be any type of white space.

How do I check a bunch of files to make sure that they don't end in some form of whitespace?(newline, space, carriage return, tab, etc.)?

答:
Just for fun, here's a plain C answer:

```<code>#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>

int main(int argc, char **argv) {
    int c, bufsize = 100, ns = 0;
    char *buf = malloc(bufsize);

    while ((c = getchar()) != EOF) {
        if (isspace(c)) {
            if (ns == bufsize) buf = realloc(buf, bufsize *= 2);
            buf[ns++] = c;
        } else {
            fwrite(buf, 1, ns, stdout);
            ns = 0;
            putchar(c);
        }
    }

    free(buf);
    return 0;
}
</code>```

Not much longer than Dennis's awk solution, and, dare I say, it, easier to understand!  :-P

ContentLicense: CC BY-SA 2.5

Body:
Just for fun, here's a plain C answer:

#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>

int main(int argc, char **argv) {
    int c, bufsize = 100, ns = 0;
    char *buf = malloc(bufsize);

    while ((c = getchar()) != EOF) {
        if (isspace(c)) {
            if (ns == bufsize) buf = realloc(buf, bufsize *= 2);
            buf[ns++] = c;
        } else {
            fwrite(buf, 1, ns, stdout);
            ns = 0;
            putchar(c);
        }
    }

    free(buf);
    return 0;
}

Not much longer than Dennis's awk solution, and, dare I say, it, easier to understand!  :-P


问:
Update int column in table with unique incrementing values
I am trying to populate any rows missing a value in their InterfaceID (INT) column with a unique value per row.

I'm trying to do this query:

```<code>UPDATE prices SET interfaceID = (SELECT ISNULL(MAX(interfaceID),0) + 1 FROM prices)
       WHERE interfaceID IS null
</code>```

I was hoping the the (SELECT ISNULL(MAX(interfaceID),0) + 1 FROM prices) would be evaluated for every row, but its only done once and so all my affected rows are getting the same value instead of different values.

Can this be done in a single query?

答:
Assuming that you have a primary key for this table (you should have), as well as using a CTE or a WITH, it is also possible to use an update with a self-join to the same table:

```<code>UPDATE a
SET a.interfaceId = b.sequence
FROM prices a
INNER JOIN
(
   SELECT ROW_NUMBER() OVER ( ORDER BY b.priceId ) + ( SELECT MAX( interfaceId ) + 1 FROM prices ) AS sequence, b.priceId
   FROM prices b
   WHERE b.interfaceId IS NULL
) b ON b.priceId = a.priceId
</code>```

I have assumed that the primary key is price-id.

The derived table, alias b, is used to generated the sequence via the ROW_NUMBER() function together with the primary key column(s). For each row where the column interface-id is NULL, this will generate a row with a unique sequence value together with the primary key value.

It is possible to order the sequence in some other order rather than the primary key.

The sequence is offset by the current MAX interface-id + 1 via a sub-query. The MAX() function ignores NULL values.

The WHERE clause limits the update to those rows that are NULL.

The derived table is then joined to the same table, alias a, joining on the primary key column(s) with the column to be updated set to the generated sequence.

ContentLicense: CC BY-SA 3.0

Body:
I am trying to populate any rows missing a value in their InterfaceID (INT) column with a unique value per row.

I'm trying to do this query:

UPDATE prices SET interfaceID = (SELECT ISNULL(MAX(interfaceID),0) + 1 FROM prices)
       WHERE interfaceID IS null

I was hoping the the (SELECT ISNULL(MAX(interfaceID),0) + 1 FROM prices) would be evaluated for every row, but its only done once and so all my affected rows are getting the same value instead of different values.

Can this be done in a single query?

Body:
Assuming that you have a primary key for this table (you should have), as well as using a CTE or a WITH, it is also possible to use an update with a self-join to the same table:

UPDATE a
SET a.interfaceId = b.sequence
FROM prices a
INNER JOIN
(
   SELECT ROW_NUMBER() OVER ( ORDER BY b.priceId ) + ( SELECT MAX( interfaceId ) + 1 FROM prices ) AS sequence, b.priceId
   FROM prices b
   WHERE b.interfaceId IS NULL
) b ON b.priceId = a.priceId

I have assumed that the primary key is price-id.

The derived table, alias b, is used to generated the sequence via the ROW_NUMBER() function together with the primary key column(s). For each row where the column interface-id is NULL, this will generate a row with a unique sequence value together with the primary key value.

It is possible to order the sequence in some other order rather than the primary key.

The sequence is offset by the current MAX interface-id + 1 via a sub-query. The MAX() function ignores NULL values.

The WHERE clause limits the update to those rows that are NULL.

The derived table is then joined to the same table, alias a, joining on the primary key column(s) with the column to be updated set to the generated sequence.


问:
Jmeter Pre-request Script to set value of HTTP Headers
I am trying to execute a pre-request script in Jmeter (similar to what you can do in postman) in order to set Header values at the beginning of every request.
How I can do it?

I am trying to set some Header values in my HTTP Header Manager when the request is made with the pre-request script script below. The values for these headers should be set by this script.

This is the script that I use in postman:

```<code>var client = "SHA256 Credential=" + environment["id"];
var timestamp = Math.floor(Date.now() / 1000);

postman.setEnvironmentVariable('client', client);
postman.setEnvironmentVariable('timestamp', timestamp);
</code>```

(environment["id"] being a preset header).

答:
Postman have 4 variable scopes:

Global

Environment

Local

Data

JMeter have 3 variable scopes:

Global

Thread Local

Data

check JMeter environment specific configuration answers for more info, but you can use jmeter property file and in each environment override with different property file to launch jmeter

-G[prop_name]=[value]

defines a JMeter property to be sent to all remote servers.

-G[propertyfile]

defines a file containing JMeter properties to be sent to all remote servers.

Body:
I am trying to execute a pre-request script in Jmeter (similar to what you can do in postman) in order to set Header values at the beginning of every request.
How I can do it?

I am trying to set some Header values in my HTTP Header Manager when the request is made with the pre-request script script below. The values for these headers should be set by this script.

This is the script that I use in postman:

var client = "SHA256 Credential=" + environment["id"];
var timestamp = Math.floor(Date.now() / 1000);

postman.setEnvironmentVariable('client', client);
postman.setEnvironmentVariable('timestamp', timestamp);

(environment["id"] being a preset header).


问:
Fragment instantiation: Why isn't savedInstanceState bundle enough?
I've been using for a while the best practice recommended by Google of having a MyFragment.newInstance() static function. Though thinking about it, why can't we simplify it removing this static function, the call to onCreate to access the arguments, and only using one bundle to always save and retrieve the latest data when recreating the fragment ?

I made a simple test that seems to work just as fine as the slightly heavier current practice.

The state persisted after activity recreation, orientation change, and fragment re-creation in a FragmentStatePagerAdapter.

Am I missing anything?

```<code>public class TestFragment extends Fragment {

    private String fragmentText;

    public TestFragment() { } // Required empty public constructor

    @SuppressLint("ValidFragment")
    public TestFragment(String fragmentText) {
        // add here other init arguments
        // don't save them in any bundle yet
        this.fragmentText = fragmentText;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (savedInstanceState != null) {
            // retrieve all arguments here
            fragmentText = savedInstanceState.getString("fragmentText", fragmentText);
        }
        TextView textView = new TextView(getActivity());
        textView.setText(fragmentText);
        return textView;
    }

    @Override
    public void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        // save everything here once, only when needed
        outState.putString("fragmentText", fragmentText);
    }

    // Add your setters to interact with the fragment
    // those changes will persists after fragment re-creation
    public void setFragmentText(String fragmentText) {
        this.fragmentText = fragmentText;
    }
}
</code>```

答:
Why isn't savedInstanceState bundle enough?

It is enough. The arguments Bundle is added to the saved instance state Bundle automatically.

I made a simple test that seems to work just as fine as the slightly heavier current practice.

Your approach is roughly the same, in terms of lines of code, as is the factory-method approach.

Why do we need to add an additional bundle with setArguments?

You do not "need" it. It is merely an available and recommended pattern for providing input to the fragment. You are welcome to do something else if you wish. Just remember to have the public zero-argument constructor as well as your custom constructor, since the framework will use the public zero-argument constructor when recreating your fragments.

Body:
I've been using for a while the best practice recommended by Google of having a MyFragment.newInstance() static function. Though thinking about it, why can't we simplify it removing this static function, the call to onCreate to access the arguments, and only using one bundle to always save and retrieve the latest data when recreating the fragment ?

I made a simple test that seems to work just as fine as the slightly heavier current practice.

The state persisted after activity recreation, orientation change, and fragment re-creation in a FragmentStatePagerAdapter.

Am I missing anything?

public class TestFragment extends Fragment {

    private String fragmentText;

    public TestFragment() { } // Required empty public constructor

    @SuppressLint("ValidFragment")
    public TestFragment(String fragmentText) {
        // add here other init arguments
        // don't save them in any bundle yet
        this.fragmentText = fragmentText;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (savedInstanceState != null) {
            // retrieve all arguments here
            fragmentText = savedInstanceState.getString("fragmentText", fragmentText);
        }
        TextView textView = new TextView(getActivity());
        textView.setText(fragmentText);
        return textView;
    }

    @Override
    public void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        // save everything here once, only when needed
        outState.putString("fragmentText", fragmentText);
    }

    // Add your setters to interact with the fragment
    // those changes will persists after fragment re-creation
    public void setFragmentText(String fragmentText) {
        this.fragmentText = fragmentText;
    }
}


问:
Mongoengine, Flask and ReferenceField in WTForms
Hy everybody,
I'm realizing a Flask/MongoDB project and since I am new to this world, I've followed the tutorial at this page:
http://docs.mongodb.org/ecosystem/tutorial/write-a-tumblelog-application-with-flask-mongoengine/

After that, I've started to code my own application and this is part of the code:

MODELS:

```<code>class Generic(db.Document):
    descrizione = db.StringField(max_length=255, required=True)

    meta = {
        'allow_inheritance': True,
        'indexes': [
            {'fields': ['descrizione'], 'unique': True}
        ]
    }

class Category(Generic):
    def __call__(self, *args):
        pass

class User(db.Document):
    email = db.EmailField(max_length=255, required=True)
    nickname = db.StringField(max_length=255, required=True)
    password = db.StringField(max_length=16, required=True)
    categoria = db.ReferenceField('Category', required=True)

    meta = {
        'indexes': [
            {'fields': ['nickname', 'email'], 'unique': True}
        ]
    }
</code>```

As you can see above, I've a "Category" class which inherits the "Generic" class. The "User" class finally has a ReferenceField to the Category. This way when I create a user, the category field on mongo db is stored as an ObjectID, related to the "generic" collection which has all the categories I've created.

The next step is to create the form to insert new documents into the user collection.
In my Views python file I've this cose:

```<code>def iscrizione():

    form = model_form(User, only=['email', 'nickname', 'password', 'categoria'])(request.form)

    if request.method == 'GET':
        ctx = {
            'form': form
        }
        return render_template('users/iscrizione.html', **ctx)
</code>```

The template uses the Jinja macro reported in the tutorial page:

```<code>{% macro render(form) -%}
<fieldset>
{% for field in form %}
{% if field.type in ['CSRFTokenField', 'HiddenField'] %}
  {{ field() }}
{% else %}
  <div class="clearfix {% if field.errors %}error{% endif %}">
    {{ field.label }}
<div class="input">
  {% if field.name == "body" %}
    {{ field(rows=10, cols=40) }}
  {% else %}
    {{ field() }}
  {% endif %}
  {% if field.errors or field.help_text %}
    <span class="help-inline">
    {% if field.errors %}
      {{ field.errors|join(' ') }}
    {% else %}
      {{ field.help_text }}
    {% endif %}
    </span>
  {% endif %}
</div>
</div>
{% endif %}
{% endfor %}
</fieldset>
{% endmacro %}
</code>```

And finally, this is my problem
(If you have reached this text, you are my hero)

When I visit the webpage with the rendered form, the macro correctly show the text fields, and for the ReferenceField in my model it show a combo box.
The options values in the select combo are perfectly aligned with the object id of the category documents I've created. Choosing one of these and submitting the form, my application correctly creates the new user document.

Unfortunately, the select box labels doesn't show a human readable value, reporting "Category object".

```<code><select id="categoria" name="categoria">
  <option value="530536363c74031c24ee7ab6">Category object</option>
  <option value="5305362d3c74031c24ee7ab5">Category object</option>
  <option value="530535793c74031b73dd07b4">Category object</option>
</select>
</code>```

How can I manage to show a correct label for the select box?

答:
Maybe its will be useful to someone. You can use standard approach, like define

```<code>def __str__(self):
    return self.descrizione
</code>```

for your Category class

Body:
Hy everybody,
I'm realizing a Flask/MongoDB project and since I am new to this world, I've followed the tutorial at this page:
http://docs.mongodb.org/ecosystem/tutorial/write-a-tumblelog-application-with-flask-mongoengine/

After that, I've started to code my own application and this is part of the code:

MODELS:

class Generic(db.Document):
    descrizione = db.StringField(max_length=255, required=True)

    meta = {
        'allow_inheritance': True,
        'indexes': [
            {'fields': ['descrizione'], 'unique': True}
        ]
    }

class Category(Generic):
    def __call__(self, *args):
        pass

class User(db.Document):
    email = db.EmailField(max_length=255, required=True)
    nickname = db.StringField(max_length=255, required=True)
    password = db.StringField(max_length=16, required=True)
    categoria = db.ReferenceField('Category', required=True)

    meta = {
        'indexes': [
            {'fields': ['nickname', 'email'], 'unique': True}
        ]
    }

As you can see above, I've a "Category" class which inherits the "Generic" class. The "User" class finally has a ReferenceField to the Category. This way when I create a user, the category field on mongo db is stored as an ObjectID, related to the "generic" collection which has all the categories I've created.

The next step is to create the form to insert new documents into the user collection.
In my Views python file I've this cose:

def iscrizione():

    form = model_form(User, only=['email', 'nickname', 'password', 'categoria'])(request.form)

    if request.method == 'GET':
        ctx = {
            'form': form
        }
        return render_template('users/iscrizione.html', **ctx)

The template uses the Jinja macro reported in the tutorial page:

{% macro render(form) -%}
<fieldset>
{% for field in form %}
{% if field.type in ['CSRFTokenField', 'HiddenField'] %}
  {{ field() }}
{% else %}

    {{ field.label }}

  {% if field.name == "body" %}
    {{ field(rows=10, cols=40) }}
  {% else %}
    {{ field() }}
  {% endif %}
  {% if field.errors or field.help_text %}

    {% if field.errors %}
      {{ field.errors|join(' ') }}
    {% else %}
      {{ field.help_text }}
    {% endif %}

  {% endif %}

{% endif %}
{% endfor %}
</fieldset>
{% endmacro %}

And finally, this is my problem
(If you have reached this text, you are my hero)

When I visit the webpage with the rendered form, the macro correctly show the text fields, and for the ReferenceField in my model it show a combo box.
The options values in the select combo are perfectly aligned with the object id of the category documents I've created. Choosing one of these and submitting the form, my application correctly creates the new user document.

Unfortunately, the select box labels doesn't show a human readable value, reporting "Category object".

<select id="categoria" name="categoria">
  <option value="530536363c74031c24ee7ab6">Category object</option>
  <option value="5305362d3c74031c24ee7ab5">Category object</option>
  <option value="530535793c74031b73dd07b4">Category object</option>
</select>

How can I manage to show a correct label for the select box?

Body:
Maybe its will be useful to someone. You can use standard approach, like define

def __str__(self):
    return self.descrizione

for your Category class


问:
How do I make a single WordPress installation seem to power two sites?
I'd like to set up a single WordPress installation at siteA.com with 2 static pages and a blog. I have two domain names and I would like to set it up so that siteA.com shows page 1 as its home page, and siteB.com would show page 2 as the homepage. Both sites would share the blog contents.

Since the Wordpress installation resides at site A, how can I create a seamless experience for the user who visits site B?

Say they type in http://siteB.com/. What should I do to show page 1 at this address? PHP include? Redirect? Mess with .htaccess?

答:
Tricky, but probably doable, though I'm not sure why you'd want to do it this way, to be honest. You'll need to modify each WordPress install to use some different tables for different things, i.e. site info (base URL, etc.). Note that at runtime you can also use the HTTP_HOST header to determine which "site" you're displaying things for, but I suspect noodling with the tables will get you most of what you want.

See http://wordpress.org/support/topic/share-certain-parts-of-a-wp-database-over-2-domains for some more info.


问:
How do I tell an Observable that my array is complete
TLDR: How can I tell an Observed array to complete. See this jsBin for example.

I am new to Observables so I may be coming at this from the wrong angle. Given the code below, or this jsBin, what should I be doing differently to get the User's sites array to "complete".

let firstUser = {
  name: 'Susan',
  sites: [
    {company: 'ABC Co', role: 'admin'},
    {company: 'XYZ Co', role: 'reader'}
  ]
};

user = new Rx.BehaviorSubject(firstUser);

function authorized(authRoles) {
    // check if the current user has one of the authorizedRoles roles
    return this.user
      .do(user => console.log("Checking user: ",JSON.stringify(user)))
      .flatMap( user => user.sites )
      .do(res => console.log("Mapped user roles: ",res))
      .first( site => authRoles.indexOf(site.role) !== -1 ) // only return when a role matches
      .do( res => console.log('First: ',res))
      .map( res => true)
}

// This one finds a match and completes
authorized(['writer','admin','reader']).subscribe(res =>{
  console.log("1: isAuthorized?: ",res);
}, err => {
  console.log("1: ERROR: User is not authorized!");
}, () => {
  console.log("1: Authorized check completed!");
});

// This one never completes
authorized(['writer','foo']).subscribe(res =>{
  console.log("2: isAuthorized?: ",res);
}, err => {
  console.log("2: ERROR: User is not authorized!");
}, () => {
  console.log("2: Authorized check completed!");
});
```

<p>Note that (first)[http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html#instance-method-first] should throw an error if it doesn't find one, but only if the Observable completes.</p>

<p>The above will return properly and complete if a match is found, but it will never complete or error without a match because the array of user.sites never completes.</p>

<p>Is there a way to make the array complete? I can get it to work if I fetch/subscribe to the user first:</p>

<pre class="lang-js prettyprint-override"><code>//
// Pretend that fetchedUser is fetched in a safer/more sane way

// fetch the user and set it
let fetchedUser;
user.subscribe(user => fetchedUser = user);

function authorized2(authRoles) {
    // check if the current user has one of the authorizedRoles roles
    return Rx.Observable.of(this.fetchedUser.sites)
      .do(sites => console.log("auth2: Checking users sites: ",sites))
      .flatMap( sites => sites )
      .do(res => console.log("Mapped user roles: ",res))
      .first( site => authRoles.indexOf(site.role) !== -1 ) // only return when a role matches
      .do( res => console.log('First: ',res))
      .map( res => true)
}
</code>```

I feel like I am missing a crucial but yet simple step to get this to work using pure Observables. Thanks in advance for your help!

答:
Rx.Observable.of(this.fetchedUser.sites) converts its arguments to an observable sequence and then completes. This triggers the .first operator to throw an exception. You are never completing the this.user subject. You could change it to this.user.take(1) or even Rx.Observable.of(fetchedUser) and skip making it a behavior subject if you want it to complete. Or you could change your .first to a .map so that it returns false if the user is unauthorized. Here is an example of using the take operator.

const user = Rx.Observable.create((o) => {
  window.setTimeout(() => {
    o.next({
      name: 'Susan',
      sites: [
        {company: 'ABC Co', role: 'admin'},
        {company: 'XYZ Co', role: 'reader'}
      ]
    });
  }, 1000);
});

function authorized(authRoles) {
    return user
      .take(1)
      .flatMap( user => user.sites )
      .first( site => authRoles.indexOf(site.role) !== -1 )
      .map( res => true);
}

authorized(['writer','admin','reader']).subscribe(res =>{
  console.log("1: isAuthorized?: ",res);
}, err => {
  console.log("1: ERROR: User is not authorized!");
}, () => {
  console.log("1: Authorized check completed!");
});

authorized(['writer','foo']).subscribe(res =>{
  console.log("2: isAuthorized?: ",res);
}, err => {
  console.log("2: ERROR: User is not authorized!");
}, () => {
  console.log("2: Authorized check completed!");
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.5.2/Rx.min.js"></script></code>```

After looking at your example I am left wondering why you are trying to solve this problem with RxJs. RxJs is tailored for acting on streams of data but you are acting on a static value. Maybe your example is just simplifying what actually occurs in your app but you could just accomplish what you are going for without RxJs in a synchronous manner and it would be much simpler. Here is an example:

```<code>function authorized(authRoles) {
    return firstUser.sites.some(x => authRoles.includes(x));
}
</code>```

Body:
TLDR: How can I tell an Observed array to complete. See this jsBin for example.

I am new to Observables so I may be coming at this from the wrong angle. Given the code below, or this jsBin, what should I be doing differently to get the User's sites array to "complete".

let firstUser = {
  name: 'Susan',
  sites: [
    {company: 'ABC Co', role: 'admin'},
    {company: 'XYZ Co', role: 'reader'}
  ]
};

user = new Rx.BehaviorSubject(firstUser);

function authorized(authRoles) {
    // check if the current user has one of the authorizedRoles roles
    return this.user
      .do(user => console.log("Checking user: ",JSON.stringify(user)))
      .flatMap( user => user.sites )
      .do(res => console.log("Mapped user roles: ",res))
      .first( site => authRoles.indexOf(site.role) !== -1 ) // only return when a role matches
      .do( res => console.log('First: ',res))
      .map( res => true)
}

// This one finds a match and completes
authorized(['writer','admin','reader']).subscribe(res =>{
  console.log("1: isAuthorized?: ",res);
}, err => {
  console.log("1: ERROR: User is not authorized!");
}, () => {
  console.log("1: Authorized check completed!");
});

// This one never completes
authorized(['writer','foo']).subscribe(res =>{
  console.log("2: isAuthorized?: ",res);
}, err => {
  console.log("2: ERROR: User is not authorized!");
}, () => {
  console.log("2: Authorized check completed!");
});

Note that (first)[http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html#instance-method-first] should throw an error if it doesn't find one, but only if the Observable completes.

The above will return properly and complete if a match is found, but it will never complete or error without a match because the array of user.sites never completes.

Is there a way to make the array complete? I can get it to work if I fetch/subscribe to the user first:

//
// Pretend that fetchedUser is fetched in a safer/more sane way

// fetch the user and set it
let fetchedUser;
user.subscribe(user => fetchedUser = user);

function authorized2(authRoles) {
    // check if the current user has one of the authorizedRoles roles
    return Rx.Observable.of(this.fetchedUser.sites)
      .do(sites => console.log("auth2: Checking users sites: ",sites))
      .flatMap( sites => sites )
      .do(res => console.log("Mapped user roles: ",res))
      .first( site => authRoles.indexOf(site.role) !== -1 ) // only return when a role matches
      .do( res => console.log('First: ',res))
      .map( res => true)
}

I feel like I am missing a crucial but yet simple step to get this to work using pure Observables. Thanks in advance for your help!

Body:
Rx.Observable.of(this.fetchedUser.sites) converts its arguments to an observable sequence and then completes. This triggers the .first operator to throw an exception. You are never completing the this.user subject. You could change it to this.user.take(1) or even Rx.Observable.of(fetchedUser) and skip making it a behavior subject if you want it to complete. Or you could change your .first to a .map so that it returns false if the user is unauthorized. Here is an example of using the take operator.

const user = Rx.Observable.create((o) => {
  window.setTimeout(() => {
    o.next({
      name: 'Susan',
      sites: [
        {company: 'ABC Co', role: 'admin'},
        {company: 'XYZ Co', role: 'reader'}
      ]
    });
  }, 1000);
});

function authorized(authRoles) {
    return user
      .take(1)
      .flatMap( user => user.sites )
      .first( site => authRoles.indexOf(site.role) !== -1 )
      .map( res => true);
}

authorized(['writer','admin','reader']).subscribe(res =>{
  console.log("1: isAuthorized?: ",res);
}, err => {
  console.log("1: ERROR: User is not authorized!");
}, () => {
  console.log("1: Authorized check completed!");
});

authorized(['writer','foo']).subscribe(res =>{
  console.log("2: isAuthorized?: ",res);
}, err => {
  console.log("2: ERROR: User is not authorized!");
}, () => {
  console.log("2: Authorized check completed!");
});

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

After looking at your example I am left wondering why you are trying to solve this problem with RxJs. RxJs is tailored for acting on streams of data but you are acting on a static value. Maybe your example is just simplifying what actually occurs in your app but you could just accomplish what you are going for without RxJs in a synchronous manner and it would be much simpler. Here is an example:

function authorized(authRoles) {
    return firstUser.sites.some(x => authRoles.includes(x));
}


问:
React Native update placeholder of TextInput
I'm trying to change the placeholder of a TextInput with setState. But this does not seem to work.

```<code>render() {
   return (
      <TextInput
           placeholder={this.state.useThisPlaceholder}
      />
   );
}
</code>```

If i try the above code with value attribute instead of placeholder it works fine. Is this behaviour not allowed or am I missing something ?

Thank you.

Update

```<code> constructor() {

    super();

    this.formSections = {
        first:{
            fields:['username', 'password', 'confirm password'],
            buttonText:'Next',
            buttonAction:() => this._loadNext()
        },
        second:{
            fields:['first name', 'last name', 'email'],
            buttonText:'Register',
            buttonAction:() => alert('registering with the server')
        }
    }

    this.state = {
        currentFormSection:'first'
    }

}

_loadNext() {

    this.setState({
        currentFormSection:'second'
    });

}

render() {

    return (

        <View
            style={styles.container}
        >
            <TextInput
                placeholder={this.formSections[this.state.currentFormSection].fields[0]}
                style={styles.textInput}
                underlineColorAndroid="transparent"
                placeholderTextColor="rgba(255,255,255,1)"
            />
            <TextInput
                placeholder={this.formSections[this.state.currentFormSection].fields[1]}
                style={styles.textInput}
                underlineColorAndroid="transparent"
                placeholderTextColor="rgba(255,255,255,1)"
            />

            <TextInput
                placeholder={this.formSections[this.state.currentFormSection].fields[2]}
                style={styles.textInput}
                underlineColorAndroid="transparent"
                placeholderTextColor="rgba(255,255,255,1)"
            />

            <TouchableOpacity
                style={styles.formBtn}
                onPress={this.formSections[this.state.currentFormSection].buttonAction}
            >
                <Text style={styles.formBtnText}>
                    {this.formSections[this.state.currentFormSection].buttonText}
                </Text>
            </TouchableOpacity>

        </View>

    );
}
</code>```

What i'm trying to achieve here is using same text inputs for different form fields. Here the placeholder updates to blank. After setState the input field is blank with no value and no text. But if I type something to the input and erase it all, the updated placeholder appears.

答:
I have updated your code one more time. Just copy and paste this code. Firstly it shows username, password, confirm password and Next button. When you enter text in TextInputs and click on Next Button then It shows firstname, lastname, email and Register Button.

```<code>import React, { Component } from 'react';
import {
  Platform,
  StyleSheet,
  Text,
  TextInput,
  TouchableOpacity,
  View,
  Button
} from 'react-native';

const instructions = Platform.select({
  ios: 'Press Cmd+R to reload,\n' +
    'Cmd+D or shake for dev menu',
  android: 'Double tap R on your keyboard to reload,\n' +
    'Shake or press menu button for dev menu',
});

export default class App extends Component {
    constructor() {
            super();
            this.formSections = {
                first:{
                    fields:['username', 'password', 'confirm password'],
                    buttonText:'Next',
                    buttonAction:() => this._loadNext()
                },
                second:{
                    fields:['first name', 'last name', 'email'],
                    buttonText:'Register',
                    buttonAction:() => alert('registering with the server')
                }
            }
            this.state = {
                valueOfFirstInput:'',
                valueOfSecondInput:'',
                valueOfThirdInput:'',
                currentFormSection:'first'
            }
        }

        _loadNext() {

            this.setState({
                valueOfFirstInput:'',
                valueOfSecondInput:'',
                valueOfThirdInput:'',
                currentFormSection:'second'
            });
        }

        render() {

            return (

                <View style={styles.container}>
                    <TextInput style={{width:200}}
                        placeholder={this.formSections[this.state.currentFormSection].fields[0]}
                        value = {this.state.valueOfFirstInput}
                        onChangeText={value => this.setState({ valueOfFirstInput: value })}
                    />
                    <TextInput style={{width:200}}
                        placeholder={this.formSections[this.state.currentFormSection].fields[1]}
                        value = {this.state.valueOfSecondInput}
                        onChangeText={value => this.setState({ valueOfSecondInput: value })}
                    />

                    <TextInput style={{width:200}}
                        placeholder={this.formSections[this.state.currentFormSection].fields[2]}
                        value = {this.state.valueOfThirdInput}
                       onChangeText={value => this.setState({ valueOfThirdInput: value })}
                    />

                    <TouchableOpacity
                        style={styles.formBtn}
                        onPress={this.formSections[this.state.currentFormSection].buttonAction}
                    >
                        <Text style={styles.formBtnText}>
                            {this.formSections[this.state.currentFormSection].buttonText}
                        </Text>
                    </TouchableOpacity>

                </View>

            );
        }
 }

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#abcdef',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});
</code>```

Try one more time. May be it helps you.

Body:
I'm trying to change the placeholder of a TextInput with setState. But this does not seem to work.

render() {
   return (
      <TextInput
           placeholder={this.state.useThisPlaceholder}
      />
   );
}

If i try the above code with value attribute instead of placeholder it works fine. Is this behaviour not allowed or am I missing something ?

Thank you.

Update

 constructor() {

    super();

    this.formSections = {
        first:{
            fields:['username', 'password', 'confirm password'],
            buttonText:'Next',
            buttonAction:() => this._loadNext()
        },
        second:{
            fields:['first name', 'last name', 'email'],
            buttonText:'Register',
            buttonAction:() => alert('registering with the server')
        }
    }

    this.state = {
        currentFormSection:'first'
    }

}

_loadNext() {

    this.setState({
        currentFormSection:'second'
    });

}

render() {

    return (

        <View
            style={styles.container}
        >
            <TextInput
                placeholder={this.formSections[this.state.currentFormSection].fields[0]}
                style={styles.textInput}
                underlineColorAndroid="transparent"
                placeholderTextColor="rgba(255,255,255,1)"
            />
            <TextInput
                placeholder={this.formSections[this.state.currentFormSection].fields[1]}
                style={styles.textInput}
                underlineColorAndroid="transparent"
                placeholderTextColor="rgba(255,255,255,1)"
            />

            <TextInput
                placeholder={this.formSections[this.state.currentFormSection].fields[2]}
                style={styles.textInput}
                underlineColorAndroid="transparent"
                placeholderTextColor="rgba(255,255,255,1)"
            />

            <TouchableOpacity
                style={styles.formBtn}
                onPress={this.formSections[this.state.currentFormSection].buttonAction}
            >
                <Text style={styles.formBtnText}>
                    {this.formSections[this.state.currentFormSection].buttonText}
                </Text>
            </TouchableOpacity>

        </View>

    );
}

What i'm trying to achieve here is using same text inputs for different form fields. Here the placeholder updates to blank. After setState the input field is blank with no value and no text. But if I type something to the input and erase it all, the updated placeholder appears.

Body:
I have updated your code one more time. Just copy and paste this code. Firstly it shows username, password, confirm password and Next button. When you enter text in TextInputs and click on Next Button then It shows firstname, lastname, email and Register Button.

import React, { Component } from 'react';
import {
  Platform,
  StyleSheet,
  Text,
  TextInput,
  TouchableOpacity,
  View,
  Button
} from 'react-native';

const instructions = Platform.select({
  ios: 'Press Cmd+R to reload,\n' +
    'Cmd+D or shake for dev menu',
  android: 'Double tap R on your keyboard to reload,\n' +
    'Shake or press menu button for dev menu',
});

export default class App extends Component {
    constructor() {
            super();
            this.formSections = {
                first:{
                    fields:['username', 'password', 'confirm password'],
                    buttonText:'Next',
                    buttonAction:() => this._loadNext()
                },
                second:{
                    fields:['first name', 'last name', 'email'],
                    buttonText:'Register',
                    buttonAction:() => alert('registering with the server')
                }
            }
            this.state = {
                valueOfFirstInput:'',
                valueOfSecondInput:'',
                valueOfThirdInput:'',
                currentFormSection:'first'
            }
        }

        _loadNext() {

            this.setState({
                valueOfFirstInput:'',
                valueOfSecondInput:'',
                valueOfThirdInput:'',
                currentFormSection:'second'
            });
        }

        render() {

            return (

                <View style={styles.container}>
                    <TextInput style={{width:200}}
                        placeholder={this.formSections[this.state.currentFormSection].fields[0]}
                        value = {this.state.valueOfFirstInput}
                        onChangeText={value => this.setState({ valueOfFirstInput: value })}
                    />
                    <TextInput style={{width:200}}
                        placeholder={this.formSections[this.state.currentFormSection].fields[1]}
                        value = {this.state.valueOfSecondInput}
                        onChangeText={value => this.setState({ valueOfSecondInput: value })}
                    />

                    <TextInput style={{width:200}}
                        placeholder={this.formSections[this.state.currentFormSection].fields[2]}
                        value = {this.state.valueOfThirdInput}
                       onChangeText={value => this.setState({ valueOfThirdInput: value })}
                    />

                    <TouchableOpacity
                        style={styles.formBtn}
                        onPress={this.formSections[this.state.currentFormSection].buttonAction}
                    >
                        <Text style={styles.formBtnText}>
                            {this.formSections[this.state.currentFormSection].buttonText}
                        </Text>
                    </TouchableOpacity>

                </View>

            );
        }
 }

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#abcdef',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});

Try one more time. May be it helps you.


问:
Read file contents and create Map of filename and contents
I want to read files from given directory then read contents from file and create Map of filename as key and its contetns as value.

I did not got any success but I have tried like this,

```<code>   def getFileLists(): List[File] = {
      val directory = "./input"
    //  print(new File(directory).listFiles().toList)
      return new File(directory).listFiles().toList
    }

    val contents = getFileLists().map(file => Source.fromFile(file).getLines())
    print(contents)
</code>```

答:
You can try this:   </p>

```<code>getFileLists().map(file => (file.getName, Source.fromFile(file).getLines().toList)).toMap
</code>```

Body:
I want to read files from given directory then read contents from file and create Map of filename as key and its contetns as value.

I did not got any success but I have tried like this,

   def getFileLists(): List[File] = {
      val directory = "./input"
    //  print(new File(directory).listFiles().toList)
      return new File(directory).listFiles().toList
    }

    val contents = getFileLists().map(file => Source.fromFile(file).getLines())
    print(contents)

Body:
You can try this:

getFileLists().map(file => (file.getName, Source.fromFile(file).getLines().toList)).toMap


问:
how to set an onclick listener for an imagebutton in an alertdialog
I have a layout with an ImageButton that is inflated in an AlertDialog, where/how should I set an onClick listener?

Here's the code I tried using:

```<code>    ImageButton ib = (ImageButton) findViewById(R.id.searchbutton);
    ib.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(TravelBite.this, "test", Toast.LENGTH_SHORT).show();
        }
    });
</code>```

答:
The code above proved useful but I used "this" (not "ad") for the context:

```<code>    ImageButton ib = (ImageButton) this.findViewById(R.id.searchbutton);
    ib.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(TravelBite.this, "test", Toast.LENGTH_SHORT).show();
        }
</code>```

This is easier for copying and pasting ;-)

Thanks for the previous code I woulnd have found the solution above without it.

Body:
I have a layout with an ImageButton that is inflated in an AlertDialog, where/how should I set an onClick listener?

Here's the code I tried using:

    ImageButton ib = (ImageButton) findViewById(R.id.searchbutton);
    ib.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(TravelBite.this, "test", Toast.LENGTH_SHORT).show();
        }
    });

Body:
The code above proved useful but I used "this" (not "ad") for the context:

    ImageButton ib = (ImageButton) this.findViewById(R.id.searchbutton);
    ib.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(TravelBite.this, "test", Toast.LENGTH_SHORT).show();
        }

This is easier for copying and pasting ;-)

Thanks for the previous code I woulnd have found the solution above without it.


问:
Symfony 2.8 how to default select value in Dropdown using Propel
I have created one dropdown for employee Role. In edit mode how to select user selected role.

```<code>$builder->add('homePageId', \Propel\Bundle\PropelBundle\Form\Type\ModelType::class  , array(
            'class' => 'Admin\HomePageBundle\Model\HomePage',
            'required' => true,
            'multiple' => false,
            'expanded' => false,
            'query' => HomePageQuery::create()->orderByName(),
            'property' => 'name',
            'preferred_choices' => array('5')
       ));
</code>```

I have added "preferred_choices" for select "5" number role but not working.

Please help for fixed this issue.

答:
The selected value is the object value. I'll try to explain this way:</p>

```<code>$object = new Object();
$object->setHomePageId(5);

// kinda put the 5 as selected in your form, because your object contains 5 and the form is not binded yet.
$form = $this->createForm(ObjectType, $object);
$form->getData()->getHomePageId(); // will return 5

//kinda put the request parameter homepageId as selected in your form
$form->handleRequest($request);
$form->getData()->getHomePageId(); // will return the user selection
</code>```

Body:
I have created one dropdown for employee Role. In edit mode how to select user selected role.

$builder->add('homePageId', \Propel\Bundle\PropelBundle\Form\Type\ModelType::class  , array(
            'class' => 'Admin\HomePageBundle\Model\HomePage',
            'required' => true,
            'multiple' => false,
            'expanded' => false,
            'query' => HomePageQuery::create()->orderByName(),
            'property' => 'name',
            'preferred_choices' => array('5')
       ));

I have added "preferred_choices" for select "5" number role but not working.

Please help for fixed this issue.

Body:
The selected value is the object value. I'll try to explain this way:

$object = new Object();
$object->setHomePageId(5);

// kinda put the 5 as selected in your form, because your object contains 5 and the form is not binded yet.
$form = $this->createForm(ObjectType, $object);
$form->getData()->getHomePageId(); // will return 5

//kinda put the request parameter homepageId as selected in your form
$form->handleRequest($request);
$form->getData()->getHomePageId(); // will return the user selection


问:
Installing a custom project template with Visual Studio Installer project
I've created a custom project template, and now I need to deploy it together with my product (i.e., it should be installed by the same msi I use for the main installation). I'm using a Visual Studio Installer project. One option is to use a custom action and manually copy a template file included in the installation. Another is to create a vsi file and use a custom action to install it after the main installation (how do I have it installed silently?) . Which one is better?

Thanks a lot

ulu

答: You can get the complete example developing VSIX implemented here: Multi-Project Templates with Wizard: Visual Studio 2010 Sample</p>


问:
How to rename a nested file in visual studio extension
I have nested files like this

If i want to rename the file "Class1.v7_1_1.cs", I didn't get the rename option in visual studio. So either i need to manually edit the proj file or do a custom extension.

In case of custom extension how to give rename facility like this

and rename the file ?

I need to develop a custom extension which should do renaming as just like how Visual Studio renames the other non-nested files.

My Solution

My current solution is showing a window on right click of the selected file which needs to be renamed. In the window let the user enters the new file name and do the file renaming in the extension. But I don't know how to do the inline renaming as shown above.

Please help me this regard. Thanks in advance.

答:
Edit the project file directly.

Search for

```<code><Compile Include="Class1.v7_1_0.cs">
</code>```

and correct it to

```<code><Compile Include="Class1.v7_1_1.cs">
</code>```

Body:
Edit the project file directly.

Search for

<Compile Include="Class1.v7_1_0.cs">

and correct it to

<Compile Include="Class1.v7_1_1.cs">

ContentLicense: CC BY-SA 4.0


问:
FMX: Handle of controls
I'm working with DirectShow in firemonkey, and i have a problem with outputting Video.

```<code>iVideoWindow.Put_Owner(Panel1.Handle);
</code>```

I need handle of TPanel, to display video at it. But FMX controls have no handle. I know, that Firemonkey is not based on traditional windows and FMX do not provide this, but how to solve  this problem? I have no idea, please, help me.

答:
To get handle of a panel, try this : </p>

```<code>uses
  FMX.Platform.Win;

var
  Handle : HWND;

begin

  Handle := TWinWindowHandle (Panel1).Wnd;

end;
</code>```

Title: FMX: Handle of controls

Body:
I'm working with DirectShow in firemonkey, and i have a problem with outputting Video.

iVideoWindow.Put_Owner(Panel1.Handle);

I need handle of TPanel, to display video at it. But FMX controls have no handle. I know, that Firemonkey is not based on traditional windows and FMX do not provide this, but how to solve  this problem? I have no idea, please, help me.

Body:
To get handle of a panel, try this :

uses
  FMX.Platform.Win;

var
  Handle : HWND;

begin

  Handle := TWinWindowHandle (Panel1).Wnd;

end;


问:
Google Maps Distinguish between User Move and Animation
I'm working with Google Maps API V2, and I'm wondering if there is a way to distinguish between when the user interacts with the map to move or zoom the camera, and when the animateCamera method is called.

What I want to do is have the map center on the user following them until they zoom in or drag the map away, at which point I want to give the user full control.

My issue is that onCameraChange gets called both when the user moves the map, and when the map is animated. What can I do to solve this?

答:
There is a nice callback from GoogleMap.OnCameraMoveStartedListener described here

Point is:

```<code>@Override
public void onCameraMoveStarted(int reason) {

    if (reason == OnCameraMoveStartedListener.REASON_GESTURE) {
        Toast.makeText(this, "The user gestured on the map.",
                       Toast.LENGTH_SHORT).show();
    } else if (reason == OnCameraMoveStartedListener
                            .REASON_API_ANIMATION) {
        Toast.makeText(this, "The user tapped something on the map.",
                       Toast.LENGTH_SHORT).show();
    } else if (reason == OnCameraMoveStartedListener
                            .REASON_DEVELOPER_ANIMATION) {
        Toast.makeText(this, "The app moved the camera.",
                       Toast.LENGTH_SHORT).show();
    }
}
</code>```

Body:
There is a nice callback from GoogleMap.OnCameraMoveStartedListener described here

Point is:

@Override
public void onCameraMoveStarted(int reason) {

    if (reason == OnCameraMoveStartedListener.REASON_GESTURE) {
        Toast.makeText(this, "The user gestured on the map.",
                       Toast.LENGTH_SHORT).show();
    } else if (reason == OnCameraMoveStartedListener
                            .REASON_API_ANIMATION) {
        Toast.makeText(this, "The user tapped something on the map.",
                       Toast.LENGTH_SHORT).show();
    } else if (reason == OnCameraMoveStartedListener
                            .REASON_DEVELOPER_ANIMATION) {
        Toast.makeText(this, "The app moved the camera.",
                       Toast.LENGTH_SHORT).show();
    }
}


问:
Getting Error COMM PCT NOT VALID WITH PU* in sabre EnhancedAirBookRQ
i am getting this error  COMM PCT NOT VALID WITH PU* - USE COMM AMT-2029

when i call EnhancedairbookRQ of sabre

this is my response

```<code><EnhancedAirBookRS xmlns="http://webservices.sabre.com/sabreXML/2011/10" Version="2.3.0">
    <stl:ApplicationResults xmlns:stl="http://services.sabre.com/STL/v01" status="Incomplete">
        <stl:Success timeStamp="2017-09-30T00:24:43.017-05:00">
            <stl:SystemSpecificResults>
                <stl:Element>IgnoreBefore</stl:Element>
            </stl:SystemSpecificResults>
        </stl:Success>
        <stl:Success timeStamp="2017-09-
   30T00:24:43.077-05:00">
            <stl:SystemSpecificResults>
                <stl:Element>OTA_AirBookRQ</stl:Element>
            </stl:SystemSpecificResults>
        </stl:Success>
        <stl:Success timeStamp="2017-09-30T00:24:53.132-05:00">
            <stl:SystemSpecificResults>
                <stl:Element>HaltOnStatusRedisplayReservation[1]</stl:Element>
            </stl:SystemSpecificResults>
        </stl:Success>
        <stl:Error type="BusinessLogic" timeStamp="2017-09-30T00:24:53.436-05:00">
            <stl:SystemSpecificResults>
                <stl:Message code="0">COMM PCT NOT VALID WITH PU* - USE COMM AMT-2029
                </stl:Message>
                <stl:Message>ERR.SWS.HOST.ERROR_IN_RESPONSE</stl:Message>
                <stl:ShortText>ERR.SWS.ORCH.PROVIDER_ERROR</stl:ShortText>
                <stl:Element>OTA_AirPriceRQ</stl:Element>
            </stl:SystemSpecificResults>
        </stl:Error>
    </stl:ApplicationResults>
    .............
</EnhancedAirBookRS>
</code>```

what i do now?

答: You can't claim a percentage commission on a PU* fare. Must be set to a flat rate, generally the same as the PU* amount</p>

Body:
i am getting this error  COMM PCT NOT VALID WITH PU* - USE COMM AMT-2029

when i call EnhancedairbookRQ of sabre

this is my response

<EnhancedAirBookRS xmlns="http://webservices.sabre.com/sabreXML/2011/10" Version="2.3.0">
    <stl:ApplicationResults xmlns:stl="http://services.sabre.com/STL/v01" status="Incomplete">
        <stl:Success timeStamp="2017-09-30T00:24:43.017-05:00">
            <stl:SystemSpecificResults>
                <stl:Element>IgnoreBefore</stl:Element>
            </stl:SystemSpecificResults>
        </stl:Success>
        <stl:Success timeStamp="2017-09-
   30T00:24:43.077-05:00">
            <stl:SystemSpecificResults>
                <stl:Element>OTA_AirBookRQ</stl:Element>
            </stl:SystemSpecificResults>
        </stl:Success>
        <stl:Success timeStamp="2017-09-30T00:24:53.132-05:00">
            <stl:SystemSpecificResults>
                <stl:Element>HaltOnStatusRedisplayReservation[1]</stl:Element>
            </stl:SystemSpecificResults>
        </stl:Success>
        <stl:Error type="BusinessLogic" timeStamp="2017-09-30T00:24:53.436-05:00">
            <stl:SystemSpecificResults>
                <stl:Message code="0">COMM PCT NOT VALID WITH PU* - USE COMM AMT-2029
                </stl:Message>
                <stl:Message>ERR.SWS.HOST.ERROR_IN_RESPONSE</stl:Message>
                <stl:ShortText>ERR.SWS.ORCH.PROVIDER_ERROR</stl:ShortText>
                <stl:Element>OTA_AirPriceRQ</stl:Element>
            </stl:SystemSpecificResults>
        </stl:Error>
    </stl:ApplicationResults>
    .............
</EnhancedAirBookRS>

what i do now?


问:
PHP Call to a member function on a non-object
Okay, I have given up on figuring this out. I am creating a simple hook system, files are placed into a folder called hooks/.

Here is an example hook

```<code><?php
//Testhook
function exampleHook() {
    echo 'Example hook as been run';
}
//Register hook (start is the hook type (where to be called), exampleHook is the function //name and TRUE if it is enabled or not.

$hooks->RegisterHook('start','exampleHook','TRUE');
?>
</code>```

This system will load all the functions into the page, they wont be executed just yet though.

Now in the actual page heres what the code looks like:

```<code><?php
    include ("hooks.class.php");
    $hooks = new hooks('hooks/');
?>
<html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Hooks</title>
</head>

<body>
    <p>Start hooks should run below</p>
    <?php $hooks->callHooks('start'); ?>
    <p>Start hooks should now finish</p>
</body>
</html>
</code>```

The callHooks function will execute any functions with the type 'start' in it. My problem is that in the testHook.php it cannot find the class $hooks, I've put the exampleHook into the same page and registered the function and it works perfectly but for some reason it cannot find the class $hooks even though the page is included.

Here is the hooks class file:

```<code><?php

class hooks {

    //Variable Initialisation
    private $hookDir;
    private $allHooks;
    public $debug = FALSE;
    private $debugDetails = array();

    //Function runs when the class is called, sets the location and calls the function retrieveHooks() to include all the files
    function __construct($hookDir = "library/addHooks/hooks/") {
        $this->hookDir = $hookDir;
        $this->allHooks = array();
        $this->retrieveHooks();
    }

    public function retrieveHooks() {
        //Get all files located in hooks directory
        $hookFiles = scandir($this->hookDir);
        //Loop through the files and remove any that arnt a file
        foreach($hookFiles as $hookFile) {
            if (strlen($hookFile) > 2) {
                //Include the file into the page
                include_once($this->hookDir . $hookFile);
                // START DEBUG SECTION OF CODE //
                if ($this->debug == TRUE) { $this->debugDetails[] = $this->hookDir . $hookFile . '<br />'; }
                // END DEBUG SECTION OF CODE //
            }
        }

    }

    //Function is called by hook files to register themselves into the class file
    public function registerHook($hookType,$functionName,$hookEnabled = TRUE) {
        if ($hookEnabled == TRUE) {
            $singleHook = array('type' => $hookType, 'function' => $functionName);
            $this->allHooks[] = $singleHook;
            // START DEBUG SECTION OF CODE //
            if ($this->debug == TRUE) { $this->debugDetails[] = ($singleHook); }
            // END DEBUG SECTION OF CODE //
        }
    }

    //Execute the hooks based on the hook type, the programmer can add as many hooks as he wants
    public function callHooks($hookType) {
        //For each hook in the array
        foreach($this->allHooks as $singleHook) {
            //If hook is found for that type eg. start, end, middle
            if ($singleHook['type'] == $hookType) {
                //Call the function that is now included within the web page
                call_user_func($singleHook['function']);
                // START DEBUG SECTION OF CODE //
                if ($this->debug == TRUE) { $this->debugDetails[] = ($singleHook); }
                // END DEBUG SECTION OF CODE //
            }
        }
    }

    //Return the array of debug details
    public function fetchDebugDetails() {
        return $debugDetails;
    }

    //Test the class by outputting a simple message
    public function testClass() {
        $className = 'hooks';
        echo 'Class is working: ' . $className;
    }

}

?>
</code>```

Finally the error message:

```<code>Notice: Undefined variable: hooks in C:\wampserver64\www\Framework\library\addHooks\hooks\testHook.php on line 9

Fatal error: Call to a member function RegisterHook() on a non-object in C:\wampserver64\www\Framework\library\addHooks\hooks\testHook.php on line 9
</code>```

Thanks, for any clarification just ask :) This has been really bugging me.

答:
On the included file, instead of

```<code>$hooks->RegisterHook('start','exampleHook','TRUE');
</code>```

use

```<code>$this->RegisterHook('start','exampleHook','TRUE');
</code>```

This is because you include the file from the class

Body:
Okay, I have given up on figuring this out. I am creating a simple hook system, files are placed into a folder called hooks/.

Here is an example hook

<?php
//Testhook
function exampleHook() {
    echo 'Example hook as been run';
}
//Register hook (start is the hook type (where to be called), exampleHook is the function //name and TRUE if it is enabled or not.

$hooks->RegisterHook('start','exampleHook','TRUE');
?>

This system will load all the functions into the page, they wont be executed just yet though.

Now in the actual page heres what the code looks like:

<?php
    include ("hooks.class.php");
    $hooks = new hooks('hooks/');
?>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Hooks</title>

Start hooks should run below

    <?php $hooks->callHooks('start'); ?>

Start hooks should now finish

The callHooks function will execute any functions with the type 'start' in it. My problem is that in the testHook.php it cannot find the class $hooks, I've put the exampleHook into the same page and registered the function and it works perfectly but for some reason it cannot find the class $hooks even though the page is included.

Here is the hooks class file:

<?php

class hooks {

    //Variable Initialisation
    private $hookDir;
    private $allHooks;
    public $debug = FALSE;
    private $debugDetails = array();

    //Function runs when the class is called, sets the location and calls the function retrieveHooks() to include all the files
    function __construct($hookDir = "library/addHooks/hooks/") {
        $this->hookDir = $hookDir;
        $this->allHooks = array();
        $this->retrieveHooks();
    }

    public function retrieveHooks() {
        //Get all files located in hooks directory
        $hookFiles = scandir($this->hookDir);
        //Loop through the files and remove any that arnt a file
        foreach($hookFiles as $hookFile) {
            if (strlen($hookFile) > 2) {
                //Include the file into the page
                include_once($this->hookDir . $hookFile);
                // START DEBUG SECTION OF CODE //
                if ($this->debug == TRUE) { $this->debugDetails[] = $this->hookDir . $hookFile . '
'; }
                // END DEBUG SECTION OF CODE //
            }
        }

    }

    //Function is called by hook files to register themselves into the class file
    public function registerHook($hookType,$functionName,$hookEnabled = TRUE) {
        if ($hookEnabled == TRUE) {
            $singleHook = array('type' => $hookType, 'function' => $functionName);
            $this->allHooks[] = $singleHook;
            // START DEBUG SECTION OF CODE //
            if ($this->debug == TRUE) { $this->debugDetails[] = ($singleHook); }
            // END DEBUG SECTION OF CODE //
        }
    }

    //Execute the hooks based on the hook type, the programmer can add as many hooks as he wants
    public function callHooks($hookType) {
        //For each hook in the array
        foreach($this->allHooks as $singleHook) {
            //If hook is found for that type eg. start, end, middle
            if ($singleHook['type'] == $hookType) {
                //Call the function that is now included within the web page
                call_user_func($singleHook['function']);
                // START DEBUG SECTION OF CODE //
                if ($this->debug == TRUE) { $this->debugDetails[] = ($singleHook); }
                // END DEBUG SECTION OF CODE //
            }
        }
    }

    //Return the array of debug details
    public function fetchDebugDetails() {
        return $debugDetails;
    }

    //Test the class by outputting a simple message
    public function testClass() {
        $className = 'hooks';
        echo 'Class is working: ' . $className;
    }

}

?>

Finally the error message:

Notice: Undefined variable: hooks in C:\wampserver64\www\Framework\library\addHooks\hooks\testHook.php on line 9

Fatal error: Call to a member function RegisterHook() on a non-object in C:\wampserver64\www\Framework\library\addHooks\hooks\testHook.php on line 9

Thanks, for any clarification just ask :) This has been really bugging me.

Body:
On the included file, instead of

$hooks->RegisterHook('start','exampleHook','TRUE');

use

$this->RegisterHook('start','exampleHook','TRUE');

This is because you include the file from the class


问:
Tkinter image label not appearing
I have no idea why this doesn't work. I'm using python 3 on a mac. I have tried
label.image but it doesn't work. Here's my code:</p>

```<code>File=open("/Users/user/Desktop/Python/File.txt")
FileContents=File.readlines()
ThingAmount=Team[0]
ActiveThing=Team[1]
ActiveThingImage=PhotoImage("/Users/user/Desktop/Python/"+ActiveThing+"/"+ActiveThing+".gif")
EnemyThingImage=PhotoImage("/Users/user/Desktop/Python/Enemy/EnemyThing.gif")
ActiveThingLabel=Label(window,image=ActiveThingImage)
ActiveThingLabel.image=ActiveThingImage
ActiveThingLabel.place(x=0,y=0)
EnemyThingLabel=Label(window,image=EnemyThingImage)
EnemyThingLabel.place(x=100,y=100)
</code>```

答:
images can be slightly tricky - but I think I can help with 2 answers!

creates the image

how to load a bunch of images from a folder somewhere.

1:

getting the buttons to have an image can be kind of tricky (you kind of need a 2 layered approach), but changing the image is easy.

```<code>x_image = 'x.png'

o_image = 'o.png'
</code>```

then...

```<code>x_image_for_button = PhotoImage(file=x_image)
o_image_for_button = PhotoImage(file=o_image)
</code>```

then.....

```<code>button = tk.Button(self.controller, image=o_image_for_button, command=lambda: command_or_something)
button.config(width="40", height="40")
button.place(x=5, y=5)
</code>```

(add in self. or root. etc)

now all you do to change the image is:

```<code>button.set(image=o_image_for_button)
#on second thought... maybe use `button.config(image=o_image_for_button)` insted
</code>```

2:

```<code>image_folder = 'theme_icons'
if self.controller.background_theme == '1':
    image_pathway = 'classic'

elif self.controller.background_theme == '2':
    image_pathway = 'blue1'

elif self.controller.background_theme == '3':
    image_pathway = 'blue2'

elif self.controller.background_theme == '4':
    image_pathway = 'classic_blue'

self.house_image_d = os.path.join(image_folder, image_pathway, 'Image1.png')
self.line_d = os.path.join(image_folder, image_pathway, 'Image2.png')

self.house_image = tk.PhotoImage(file=self.house_image_d)
self.my_line = tk.PhotoImage(file=self.line_d)
</code>```

Title: Tkinter image label not appearing

Body:
I have no idea why this doesn't work. I'm using python 3 on a mac. I have tried
label.image but it doesn't work. Here's my code:

File=open("/Users/user/Desktop/Python/File.txt")
FileContents=File.readlines()
ThingAmount=Team[0]
ActiveThing=Team[1]
ActiveThingImage=PhotoImage("/Users/user/Desktop/Python/"+ActiveThing+"/"+ActiveThing+".gif")
EnemyThingImage=PhotoImage("/Users/user/Desktop/Python/Enemy/EnemyThing.gif")
ActiveThingLabel=Label(window,image=ActiveThingImage)
ActiveThingLabel.image=ActiveThingImage
ActiveThingLabel.place(x=0,y=0)
EnemyThingLabel=Label(window,image=EnemyThingImage)
EnemyThingLabel.place(x=100,y=100)

Body:
images can be slightly tricky - but I think I can help with 2 answers!

creates the image

how to load a bunch of images from a folder somewhere.

1:

getting the buttons to have an image can be kind of tricky (you kind of need a 2 layered approach), but changing the image is easy.

x_image = 'x.png'

o_image = 'o.png'

then...

x_image_for_button = PhotoImage(file=x_image)
o_image_for_button = PhotoImage(file=o_image)

then.....

button = tk.Button(self.controller, image=o_image_for_button, command=lambda: command_or_something)
button.config(width="40", height="40")
button.place(x=5, y=5)

(add in self. or root. etc)

now all you do to change the image is:

button.set(image=o_image_for_button)
#on second thought... maybe use `button.config(image=o_image_for_button)` insted

2:

image_folder = 'theme_icons'
if self.controller.background_theme == '1':
    image_pathway = 'classic'

elif self.controller.background_theme == '2':
    image_pathway = 'blue1'

elif self.controller.background_theme == '3':
    image_pathway = 'blue2'

elif self.controller.background_theme == '4':
    image_pathway = 'classic_blue'

self.house_image_d = os.path.join(image_folder, image_pathway, 'Image1.png')
self.line_d = os.path.join(image_folder, image_pathway, 'Image2.png')

self.house_image = tk.PhotoImage(file=self.house_image_d)
self.my_line = tk.PhotoImage(file=self.line_d)


问:
how to pass dynamic/optional filter in mongodb?
I want to select data from mongodb based on given filter. I am getting proper result if I pass static filter.

i.e.

```<code>var filter = {'categories ':'business'};
</code>```

If I put dynamic values it is not showing up. I am able to see variable type as object and value is also correct.

```<code>static async getArticle(req, res, next) {
   try {

      var filter = {};
   if(req.body.categories || req.body.categories != "") {
       filter.categories = req.body.categories;
   }
   console.log('val: '+JSON.stringify(filter));
   console.log('org val: '+filter);
   console.log('obj type: '+typeof(filter));
   let totalArticle = await Models.Article.find(filter).count().exec();

  res.send({
       success: true,
       totalArticle: totalArticle
   });
   } catch (error) {
       console.error(error);
       res.send({success: false, error});
   }
}
</code>```

Output in console is

```<code>val: {"categories":"business"}
org val: [object Object]
obj type: object
</code>```

If I pass static value as above I get following response.

```<code>{
    "success": true,
    "totalArticle": 2
}
</code>```

and in console it is also same:

```<code>val: {"categories":"business"}
org val: [object Object]
obj type: object
</code>```

Can someone please tell what I am doing wrong?

答:
i use $and in filter object. so, my query fire in database select * from collection_name where categorie like "%business"

```<code> var filter1 = {$and: []};
    if(req.body.categories) {
          var cat = new RegExp(req.body.categories);
          filter1.$and.push({categorie: cat});
    }
    let totalArticle = await Models.Article.find(filter1).count().exec();
    res.send({
          success: true,
          totalArticle: totalArticle
    });
</code>```

Body:
I want to select data from mongodb based on given filter. I am getting proper result if I pass static filter.

i.e.

var filter = {'categories ':'business'};

If I put dynamic values it is not showing up. I am able to see variable type as object and value is also correct.

static async getArticle(req, res, next) {
   try {

      var filter = {};
   if(req.body.categories || req.body.categories != "") {
       filter.categories = req.body.categories;
   }
   console.log('val: '+JSON.stringify(filter));
   console.log('org val: '+filter);
   console.log('obj type: '+typeof(filter));
   let totalArticle = await Models.Article.find(filter).count().exec();

  res.send({
       success: true,
       totalArticle: totalArticle
   });
   } catch (error) {
       console.error(error);
       res.send({success: false, error});
   }
}

Output in console is

val: {"categories":"business"}
org val: [object Object]
obj type: object

If I pass static value as above I get following response.

{
    "success": true,
    "totalArticle": 2
}

and in console it is also same:

val: {"categories":"business"}
org val: [object Object]
obj type: object

Can someone please tell what I am doing wrong?

Body:
i use $and in filter object. so, my query fire in database select * from collection_name where categorie like "%business"

 var filter1 = {$and: []};
    if(req.body.categories) {
          var cat = new RegExp(req.body.categories);
          filter1.$and.push({categorie: cat});
    }
    let totalArticle = await Models.Article.find(filter1).count().exec();
    res.send({
          success: true,
          totalArticle: totalArticle
    });


问:
JSX adding attribute with no value with conditional statement
So in JSX I know how I can use an conditional on class names etc or where the attribute has a value.

So if I'm doing class="something" or style="something" etc. The issue I'm having is i'm unsure how I'd do a conditional when adding the hidden attribute.

Example;

```<code>  className={classNames({
    'hidden': true,
    'visible': props.showAll,
  })}
</code>```

This will add a class depending on the value of showAll.

But the hidden attribute is literally just
this text is hidden
.

How would I go about adding a conditional into my JSX react component that renders an attribute but no value?

答:
If the data is present then show otherwise do not append the p tag on dom.So try this</p>

```<code>{this.props.showAll && <p>this.props.showAll</p>}
</code>```

Body:
So in JSX I know how I can use an conditional on class names etc or where the attribute has a value.

So if I'm doing class="something" or style="something" etc. The issue I'm having is i'm unsure how I'd do a conditional when adding the hidden attribute.

Example;

  className={classNames({
    'hidden': true,
    'visible': props.showAll,
  })}

This will add a class depending on the value of showAll.

But the hidden attribute is literally just
this text is hidden
.

How would I go about adding a conditional into my JSX react component that renders an attribute but no value?

Body:
If the data is present then show otherwise do not append the p tag on dom.So try this

{this.props.showAll && <p>this.props.showAll</p>}


问:
Ignoring rows within daterange
I have the following data:

```<code>CREATE TABLE SampleData
(
    orderid int,
    [name] nvarchar(1),
    [date] date
);
INSERT INTO SampleData
VALUES
(1, 'a', '2017-01-01'),
(2, 'a', '2017-01-05'),
(3, 'a', '2017-02-01'),
(4, 'a', '2017-04-01'),
(5, 'a', '2017-10-01'),
(6, 'b', '2017-04-01');
</code>```

I need to retrieve each new order according to the following rules:

The first date for a name is the 'current order' for that name

Orders with the same name, but less than 3 months difference with the 'current order' is considered the same order and needs to be ignored

3 months or more difference with the 'current' order is considered a new order and is now the 'current order' (in the SampleData orderid 1 and 4 need to be compared instead of 3 and 4, because 3 is not the current order)

If the name and date are the same, then the row with the lowest orderid is the superior order

So with the sample data I need the following result:

```<code>id name, date
1  a     2017-01-01
4  a     2017-04-01
5  a     2017-10-01
6  b     2017-04-01
</code>```

I tried several approaches, but without success. Any idea's on how I can achieve this?

答:
@SQLUser44, thanks for your input. Unfortunately your code is not working. The result for the table below should be orderid's 1,6,7,8 and 9. Yours results in 1,2,3,5,6,7,8 and 9.

```<code>INSERT INTO #tmp_SampleData
VALUES
(1,'a','2017-01-01'),
(2,'a','2017-01-08'),
(3,'a','2017-05-01'),
(4,'a','2017-01-05'),
(5,'a','2017-02-01'),
(6,'b','2017-01-01'),
(7,'b','2017-09-01'),
(8,'c','2017-10-01'),
(9,'a','2017-04-01');
</code>```

I came up with the following that works, but I think it will lack performance...

```<code>if object_id('tempdb..#tmp_SampleData','u') is not null
drop table #tmp_SampleData

CREATE TABLE #tmp_SampleData
(
    orderid int,
    [name] nvarchar(1),
    [date] date
);
INSERT INTO #tmp_SampleData
VALUES
(1,'a','2017-01-01'),
(2,'a','2017-01-08'),
(3,'a','2017-05-01'),
(4,'a','2017-01-05'),
(5,'a','2017-02-01'),
(6,'b','2017-01-01'),
(7,'b','2017-09-01'),
(8,'c','2017-10-01'),
(9,'a','2017-04-01');

DECLARE Test_Cursor CURSOR FOR
SELECT * FROM #tmp_SampleData ORDER BY [name], [date];
OPEN Test_Cursor;

DECLARE @orderid int;
DECLARE @name nvarchar(255);
DECLARE @date date;

FETCH NEXT FROM Test_Cursor INTO @orderid, @name, @date;

DECLARE @current_date date = @date;
DECLARE @current_name nvarchar(255) = @name;
DECLARE @listOfIDs TABLE (orderid int);
INSERT @listOfIDs values(@orderid);

WHILE @@FETCH_STATUS = 0
    BEGIN
       IF(@name = @current_name AND DATEDIFF(MONTH, @current_date, @date) >= 3)
          BEGIN
             SET @current_date = @date
             INSERT @listOfIDs values(@orderid)
          END
       IF(@name != @current_name)
          BEGIN
             SET @current_name = @name
             SET @current_date = @date
             INSERT @listOfIDs values(@orderid)
          END
    FETCH NEXT FROM Test_Cursor INTO @orderid, @name, @date;
    END;
CLOSE Test_Cursor;
DEALLOCATE Test_Cursor;
SELECT * FROM #tmp_SampleData WHERE orderid IN (SELECT orderid FROM @listOfIDs);
</code>```

Better performing alternatives are very welcome!

Title: Ignoring rows within daterange

Body:
I have the following data:

CREATE TABLE SampleData
(
    orderid int,
    [name] nvarchar(1),
    [date] date
);
INSERT INTO SampleData
VALUES
(1, 'a', '2017-01-01'),
(2, 'a', '2017-01-05'),
(3, 'a', '2017-02-01'),
(4, 'a', '2017-04-01'),
(5, 'a', '2017-10-01'),
(6, 'b', '2017-04-01');

I need to retrieve each new order according to the following rules:

The first date for a name is the 'current order' for that name

Orders with the same name, but less than 3 months difference with the 'current order' is considered the same order and needs to be ignored

3 months or more difference with the 'current' order is considered a new order and is now the 'current order' (in the SampleData orderid 1 and 4 need to be compared instead of 3 and 4, because 3 is not the current order)

If the name and date are the same, then the row with the lowest orderid is the superior order

So with the sample data I need the following result:

id name, date
1  a     2017-01-01
4  a     2017-04-01
5  a     2017-10-01
6  b     2017-04-01

I tried several approaches, but without success. Any idea's on how I can achieve this?

Body:
@SQLUser44, thanks for your input. Unfortunately your code is not working. The result for the table below should be orderid's 1,6,7,8 and 9. Yours results in 1,2,3,5,6,7,8 and 9.

INSERT INTO #tmp_SampleData
VALUES
(1,'a','2017-01-01'),
(2,'a','2017-01-08'),
(3,'a','2017-05-01'),
(4,'a','2017-01-05'),
(5,'a','2017-02-01'),
(6,'b','2017-01-01'),
(7,'b','2017-09-01'),
(8,'c','2017-10-01'),
(9,'a','2017-04-01');

I came up with the following that works, but I think it will lack performance...

if object_id('tempdb..#tmp_SampleData','u') is not null
drop table #tmp_SampleData

CREATE TABLE #tmp_SampleData
(
    orderid int,
    [name] nvarchar(1),
    [date] date
);
INSERT INTO #tmp_SampleData
VALUES
(1,'a','2017-01-01'),
(2,'a','2017-01-08'),
(3,'a','2017-05-01'),
(4,'a','2017-01-05'),
(5,'a','2017-02-01'),
(6,'b','2017-01-01'),
(7,'b','2017-09-01'),
(8,'c','2017-10-01'),
(9,'a','2017-04-01');

DECLARE Test_Cursor CURSOR FOR
SELECT * FROM #tmp_SampleData ORDER BY [name], [date];
OPEN Test_Cursor;

DECLARE @orderid int;
DECLARE @name nvarchar(255);
DECLARE @date date;

FETCH NEXT FROM Test_Cursor INTO @orderid, @name, @date;

DECLARE @current_date date = @date;
DECLARE @current_name nvarchar(255) = @name;
DECLARE @listOfIDs TABLE (orderid int);
INSERT @listOfIDs values(@orderid);

WHILE @@FETCH_STATUS = 0
    BEGIN
       IF(@name = @current_name AND DATEDIFF(MONTH, @current_date, @date) >= 3)
          BEGIN
             SET @current_date = @date
             INSERT @listOfIDs values(@orderid)
          END
       IF(@name != @current_name)
          BEGIN
             SET @current_name = @name
             SET @current_date = @date
             INSERT @listOfIDs values(@orderid)
          END
    FETCH NEXT FROM Test_Cursor INTO @orderid, @name, @date;
    END;
CLOSE Test_Cursor;
DEALLOCATE Test_Cursor;
SELECT * FROM #tmp_SampleData WHERE orderid IN (SELECT orderid FROM @listOfIDs);

Better performing alternatives are very welcome!


问:
Where is Windows CE Platform Builder 3.00?
I need to emulate a Windows CE executable on my Windows 7 64-bit machine. Back in the day, I used eMbedded Visual C++ 4.0's bundled device emulator, but nowadays the cool kids want me to use "Platform Builder" and ActiveSync. So I found a Windows CE Platform Builder 3.0 update here, but I can't find the original download, which it requires:

```<code>PB not installed: Please install Windows CE Platform Builder 3.00 before
installing this Update.
</code>```

My problem stems from having installed the Standard CE SDK (STANDARD_SDK.msi) and a Windows CE BSP, which shows up in Visual Studio 2008's "Device Emulator Manager", but I can't connect to or run them. The Pocket PC images work, though.

Where do I find Windows CE Platform Builder 3.00?

答:
Platform Builder 3.0 is really, really old and I doubt any distributors carry it any more.  When it was a shipping product, a distributor (Arrow, Avnet, etc) was the only place you could get it, so that's where I'd at least check on the long-shot chance.

That said, I'm not at all sure why you feel you need it.  Platform Builder is for generating an OS image.  PB is a difficult tool to get to know, and the 3.0 version was unwieldy at best.  It's also not going to run under 64-bit.  It also can't create an OS that runs on a 64-bit machine.  It also cannot create an SDK that will plug into any version of Studio (well it might work in VS 2003 - it's been a long time since I did that).

What it actually sounds like you're after is an emulator and image for that emulator for a basic CE 3.0 device.  Microsoft shipped the HPC Pro emulator, which was a 3.0-based device with the EVC tool set, though I've got no idea where you'd find it (short of digging out old MSDN disks).

For what it's worth, the PocketPC 2003 images are CE 3.0-based, so you do have a CE 3.0 emulator today - it's just not a more generic CE build.

Ideally I think you need to tell us exactly what you need.  An emulated version of what sort of CE 3.0 OS?  What components?  Targeting what OS (the old emulator would only do x86, so if you have some ARM or MIPS app, that was never emulated anyway).

Body:
I need to emulate a Windows CE executable on my Windows 7 64-bit machine. Back in the day, I used eMbedded Visual C++ 4.0's bundled device emulator, but nowadays the cool kids want me to use "Platform Builder" and ActiveSync. So I found a Windows CE Platform Builder 3.0 update here, but I can't find the original download, which it requires:

PB not installed: Please install Windows CE Platform Builder 3.00 before
installing this Update.

My problem stems from having installed the Standard CE SDK (STANDARD_SDK.msi) and a Windows CE BSP, which shows up in Visual Studio 2008's "Device Emulator Manager", but I can't connect to or run them. The Pocket PC images work, though.

Where do I find Windows CE Platform Builder 3.00?


问:
How to make a pseudo element same height and width in pure CSS?
The .speech height may vary therefore looking for solution to make .speech::after's width same as .speech's height.

ideal result

body {
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

.speech {
  width: 250px;
  padding: 1rem;
  background-color: tomato;
  color: white;
  border: 1px solid;
  position: relative;
}

.speech::after {
  content: '';
  position: absolute;
  top: 0;
  left: 100%;
  border: 3px solid deepskyblue;
  height: 100%;
  padding-left: 50%;
  background: linear-gradient(45deg, transparent 50%, green 0%);
  transform: translateX(-50%) rotate(45deg);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="speech">Lorem ipsum dolor sit amet consectetur adipisicing elit. Facilis minima possimus, maxime, fugit dolorum optio, tempora et doloribus doloremque ullam inventore repellendus veniam modi quasi iusto numquam amet eos! Exercitationem.</div></code>```

答:
Update your code like this</p>

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

<head>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=0, width=device-width;" />
    <meta name="format-detection" content="telephone=no">
    <meta name="description" content="">
    <link rel="shortcut icon" href="favicon.ico" />
    <meta name="author" content="">

    <style>

body {
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

.speech {
  width: 250px;
  padding: 0px;
  background-color: tomato;
  color: white;
  border: 1px solid;
  position: relative;
}

.speech::after {
  content: '';
  position: absolute;
  width: 0;
  height: 0;
  top:0px;
  left:100%;

}

</style>
</head>

<body>

<div class="speech">Lorem ipsum dolor sit amet consectetur adipisicing elit. Facilis minima possimus, maxime, fugit dolorum optio, tempora et doloribus doloremque ullam inventore repellendus veniam modi quasi iusto numquam amet eos! Exercitationem. Lorem ipsum dolor sit amet consectetur adipisicing elit. Facilis minima possimus, maxime, fugit dolorum optio, tempora et doloribus doloremque ullam inventore repellendus veniam modi quasi iusto numquam amet eos! Exercitationem.</div>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
$( document ).ready(function() {
    var ht = $(".speech").height();
    var ht1 = ht/2;
    $("head").append($('<style>.speech:after { border-top: '+ht1+'px solid transparent; border-bottom: '+ht1+'px solid transparent;  border-left: '+ht1+'px solid green;}</style>'));
});
</script>

</body>

</html>
</code>```

Body:
The .speech height may vary therefore looking for solution to make .speech::after's width same as .speech's height.

ideal result

body {
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

.speech {
  width: 250px;
  padding: 1rem;
  background-color: tomato;
  color: white;
  border: 1px solid;
  position: relative;
}

.speech::after {
  content: '';
  position: absolute;
  top: 0;
  left: 100%;
  border: 3px solid deepskyblue;
  height: 100%;
  padding-left: 50%;
  background: linear-gradient(45deg, transparent 50%, green 0%);
  transform: translateX(-50%) rotate(45deg);
}

Lorem ipsum dolor sit amet consectetur adipisicing elit. Facilis minima possimus, maxime, fugit dolorum optio, tempora et doloribus doloremque ullam inventore repellendus veniam modi quasi iusto numquam amet eos! Exercitationem.

Body:
Update your code like this

<!DOCTYPE html>
<html lang="en">

<head>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=0, width=device-width;" />
    <meta name="format-detection" content="telephone=no">
    <meta name="description" content="">
    <link rel="shortcut icon" href="favicon.ico" />
    <meta name="author" content="">

    <style>

body {
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

.speech {
  width: 250px;
  padding: 0px;
  background-color: tomato;
  color: white;
  border: 1px solid;
  position: relative;
}

.speech::after {
  content: '';
  position: absolute;
  width: 0;
  height: 0;
  top:0px;
  left:100%;

}

</style>
</head>

<body>

<div class="speech">Lorem ipsum dolor sit amet consectetur adipisicing elit. Facilis minima possimus, maxime, fugit dolorum optio, tempora et doloribus doloremque ullam inventore repellendus veniam modi quasi iusto numquam amet eos! Exercitationem. Lorem ipsum dolor sit amet consectetur adipisicing elit. Facilis minima possimus, maxime, fugit dolorum optio, tempora et doloribus doloremque ullam inventore repellendus veniam modi quasi iusto numquam amet eos! Exercitationem.</div>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
$( document ).ready(function() {
    var ht = $(".speech").height();
    var ht1 = ht/2;
    $("head").append($('<style>.speech:after { border-top: '+ht1+'px solid transparent; border-bottom: '+ht1+'px solid transparent;  border-left: '+ht1+'px solid green;}</style>'));
});
</script>

</body>

</html>


答:
What you are doing is transforming the list of file-names to a list of their contents. You want a Map[File, List[String]] instead. To do that the easiest ist to map to tuples of files and content, and then call toMap on the result:

```<code>getFileLists().map(file => file -> Source.fromFile(file).getLines().toList).toMap
</code>```

toMap works when the input sequence has Tuple2 as element type. file -> contents is such a tuple (File, List[String]).

Or in two steps:

```<code>val xs: Seq[(File, List[String])] = getFileLists().map(file =>
  file -> Source.fromFile(file).getLines().toList)
val m: Map[File, List[String]] = xs.toMap
</code>```

Title: Read file contents and create Map of filename and contents

Body:
I want to read files from given directory then read contents from file and create Map of filename as key and its contetns as value.

I did not got any success but I have tried like this,

   def getFileLists(): List[File] = {
      val directory = "./input"
    //  print(new File(directory).listFiles().toList)
      return new File(directory).listFiles().toList
    }

    val contents = getFileLists().map(file => Source.fromFile(file).getLines())
    print(contents)

Body:
What you are doing is transforming the list of file-names to a list of their contents. You want a Map[File, List[String]] instead. To do that the easiest ist to map to tuples of files and content, and then call toMap on the result:

getFileLists().map(file => file -> Source.fromFile(file).getLines().toList).toMap

toMap works when the input sequence has Tuple2 as element type. file -> contents is such a tuple (File, List[String]).

Or in two steps:

val xs: Seq[(File, List[String])] = getFileLists().map(file =>
  file -> Source.fromFile(file).getLines().toList)
val m: Map[File, List[String]] = xs.toMap


问:
Puppet Evaluation Error: Error while evaluating a Resource Statement, Could not find declared class
I'm trying to deploy an application called Bag-Of-Holding via Puppet using the instruction as posted on github - https://github.com/ribeiroit/boh-puppet

I run the command: sudo puppet apply /etc/puppet/manifests/site.pp
and I get the error below:

Error: Evaluation Error: Error while evaluating a Resource Statement, Could not find declared class boh at /etc/puppet/manifests/site.pp:2:2 on node lab1-hp-elitebook-8570p

It appears the puppet is having hard time finding the class boh which is already in the manifest folder

This is my directory tree:

```<code>/etc/puppet
├── code
├── manifests
└── modules
    └── boh-puppet
        ├── manifests
        └── templates
</code>```

my site.pp file is located in /etc/puppet/manifests
and it looks like this:

```<code>node 'lab1-hp-elitebook-8570p' {
  class { 'boh':
    python_version   => 3,
    environment      => 'dev',
    language         => 'en',
    debug            => 'True',
    create_superuser => 'true',
    pkg_checksum     => '86b0164f7fd6c5e4aa43c8f056f08cea'
  }
}
</code>```

And init.pp file has the class {boh } and that's located at:
/etc/puppet/modules/boh-puppet/manifests

Any ideas how to fix this?

答:
Puppet requires certain namespace restrictions and conventions with module directory structure and class names when autoloading. In this case, your problem can be solved most simply and cleanly to follow normal conventions by renaming your module directory of boh-puppet to simply boh. That will fix your issue.

Consult the documentation here for more information: https://puppet.com/docs/puppet/4.10/lang_namespaces.html

Since you are using puppet apply with absolute paths, you will also need to supply the path to your modules by modifying the command to: sudo puppet apply --modulepath=/etc/puppet/modules /etc/puppet/manifests/site.pp.

Body:
I'm trying to deploy an application called Bag-Of-Holding via Puppet using the instruction as posted on github - https://github.com/ribeiroit/boh-puppet

I run the command: sudo puppet apply /etc/puppet/manifests/site.pp
and I get the error below:

Error: Evaluation Error: Error while evaluating a Resource Statement, Could not find declared class boh at /etc/puppet/manifests/site.pp:2:2 on node lab1-hp-elitebook-8570p

It appears the puppet is having hard time finding the class boh which is already in the manifest folder

This is my directory tree:

/etc/puppet
├── code
├── manifests
└── modules
    └── boh-puppet
        ├── manifests
        └── templates

my site.pp file is located in /etc/puppet/manifests
and it looks like this:

node 'lab1-hp-elitebook-8570p' {
  class { 'boh':
    python_version   => 3,
    environment      => 'dev',
    language         => 'en',
    debug            => 'True',
    create_superuser => 'true',
    pkg_checksum     => '86b0164f7fd6c5e4aa43c8f056f08cea'
  }
}

And init.pp file has the class {boh } and that's located at:
/etc/puppet/modules/boh-puppet/manifests

Any ideas how to fix this?