问:
String index out of range exception where?
I'm trying to make a program for school which searches a text file for a string the user inputs. However I keep getting the error:

line 16, in <module>, while(test[i] != " ")
IndexError: string index out of range

This is my code:

```<code>import os
myList=[]
while True:
    ans = input("Please enter a filename or 'X' to exit")
        if(ans == "X"):
        exit()
    else:
        while True:
            if os.path.exists(ans):
                with open(ans,"r") as file:
                     test = file.read()
                     print(file)
                     i=0
                     while(i <= len(test)-1):
                        sol = ""
                        while(test[i] != " "):
                            sol = sol + test[i]
                            i += 1
                        myList.append(sol)
                        i += 1
                    ans2 = input("Please enter a word to search for or 'X' to exit")
                    if(ans2 == 'X'):
                        exit()
                    else:
                        if ans2 in myList:
                            print(ans2 + " is in " + ans)
                        else:
                            print(ans2 + " is NOT in " + ans)
            else:
                print("File does not exist. Try again.")
                break
</code>```

Basically it seems to me like the line while(i <= len(test)-1): should prevent the string from getting out of index so I cannot find out where I'm going out of index.

答: It seems you could greatly simplify this using for-loops. Or honestly, it looks like your nested while-loops are trying to split the string by " " character, but you could just use test.split(' ') which will return a list of strings, than you can check that list-of-strings directly

Body:
I'm trying to make a program for school which searches a text file for a string the user inputs. However I keep getting the error:

line 16, in <module>, while(test[i] != " ")
IndexError: string index out of range

This is my code:

import os
myList=[]
while True:
    ans = input("Please enter a filename or 'X' to exit")
        if(ans == "X"):
        exit()
    else:
        while True:
            if os.path.exists(ans):
                with open(ans,"r") as file:
                     test = file.read()
                     print(file)
                     i=0
                     while(i <= len(test)-1):
                        sol = ""
                        while(test[i] != " "):
                            sol = sol + test[i]
                            i += 1
                        myList.append(sol)
                        i += 1
                    ans2 = input("Please enter a word to search for or 'X' to exit")
                    if(ans2 == 'X'):
                        exit()
                    else:
                        if ans2 in myList:
                            print(ans2 + " is in " + ans)
                        else:
                            print(ans2 + " is NOT in " + ans)
            else:
                print("File does not exist. Try again.")
                break

Basically it seems to me like the line while(i <= len(test)-1): should prevent the string from getting out of index so I cannot find out where I'm going out of index.


来源: stackexchange

问:
How to perform query with cassandra's timestamp column as WHERE condition
I have the following Cassandra table

```<code>cqlsh:mydb> describe table events;

CREATE TABLE mydb.events (
    id uuid PRIMARY KEY,
    country text,
    insert_timestamp timestamp
) WITH bloom_filter_fp_chance = 0.01
    AND caching = '{"keys":"ALL", "rows_per_partition":"NONE"}'
    AND comment = ''
    AND compaction = {'class': 'org.apache.cassandra.db.compaction.SizeTieredCompactionStrategy'}
    AND compression = {'sstable_compression': 'org.apache.cassandra.io.compress.LZ4Compressor'}
    AND dclocal_read_repair_chance = 0.1
    AND default_time_to_live = 0
    AND gc_grace_seconds = 864000
    AND max_index_interval = 2048
    AND memtable_flush_period_in_ms = 0
    AND min_index_interval = 128
    AND read_repair_chance = 0.0
    AND speculative_retry = '99.0PERCENTILE';
CREATE INDEX country_index ON mydb.events (country);
CREATE INDEX insert_timestamp_index ON mydb.events (insert_timestamp);
</code>```

As you can see, index is already created on insert_timestamp column.

I had gone through https://stackoverflow.com/a/18698386/3238864

I though the following is the correct query

```<code>cqlsh:mydb> select * from events where insert_timestamp >= '2016-03-01 08:27:22+0000';
InvalidRequest: code=2200 [Invalid query] message="No secondary indexes on the restricted columns support the provided operators: 'insert_timestamp >= <value>'"

cqlsh:mydb> select * from events where insert_timestamp >= '2016-03-01 08:27:22+0000' ALLOW FILTERING;
InvalidRequest: code=2200 [Invalid query] message="No secondary indexes on the restricted columns support the provided operators: 'insert_timestamp >= <value>'"
</code>```

But, query with country column as WHERE condition does work.

```<code>cqlsh:mydb> select * from events where country = 'my';

id                                   | country | insert_timestamp
--------------------------------------+---------+--------------------------
53167d6a-e125-46ff-bacf-f5b267de0258 |      my | 2016-03-01 08:27:22+0000
</code>```

Any idea why query with timestamp as condition doesn't work? Is there anything wrong with my query syntax?

答:
Using cequel ORM

```<code>    now = DateTime.now
    today = DateTime.new(now.year, now.month, now.day, 0, 0, 0, now.zone)
    tommorrow = today + (60 * 60 * 24);
    MyObject.allow_filtering!.where("done_date" => today..tommorrow).select( "*" )
</code>```

Has worked for me.

ContentLicense: CC BY-SA 3.0

Body:
I have the following Cassandra table

cqlsh:mydb> describe table events;

CREATE TABLE mydb.events (
    id uuid PRIMARY KEY,
    country text,
    insert_timestamp timestamp
) WITH bloom_filter_fp_chance = 0.01
    AND caching = '{"keys":"ALL", "rows_per_partition":"NONE"}'
    AND comment = ''
    AND compaction = {'class': 'org.apache.cassandra.db.compaction.SizeTieredCompactionStrategy'}
    AND compression = {'sstable_compression': 'org.apache.cassandra.io.compress.LZ4Compressor'}
    AND dclocal_read_repair_chance = 0.1
    AND default_time_to_live = 0
    AND gc_grace_seconds = 864000
    AND max_index_interval = 2048
    AND memtable_flush_period_in_ms = 0
    AND min_index_interval = 128
    AND read_repair_chance = 0.0
    AND speculative_retry = '99.0PERCENTILE';
CREATE INDEX country_index ON mydb.events (country);
CREATE INDEX insert_timestamp_index ON mydb.events (insert_timestamp);

As you can see, index is already created on insert_timestamp column.

I had gone through https://stackoverflow.com/a/18698386/3238864

I though the following is the correct query

cqlsh:mydb> select * from events where insert_timestamp >= '2016-03-01 08:27:22+0000';
InvalidRequest: code=2200 [Invalid query] message="No secondary indexes on the restricted columns support the provided operators: 'insert_timestamp >= <value>'"

cqlsh:mydb> select * from events where insert_timestamp >= '2016-03-01 08:27:22+0000' ALLOW FILTERING;
InvalidRequest: code=2200 [Invalid query] message="No secondary indexes on the restricted columns support the provided operators: 'insert_timestamp >= <value>'"

But, query with country column as WHERE condition does work.

cqlsh:mydb> select * from events where country = 'my';

id                                   | country | insert_timestamp
--------------------------------------+---------+--------------------------
53167d6a-e125-46ff-bacf-f5b267de0258 |      my | 2016-03-01 08:27:22+0000

Any idea why query with timestamp as condition doesn't work? Is there anything wrong with my query syntax?

Body:
Using cequel ORM

    now = DateTime.now
    today = DateTime.new(now.year, now.month, now.day, 0, 0, 0, now.zone)
    tommorrow = today + (60 * 60 * 24);
    MyObject.allow_filtering!.where("done_date" => today..tommorrow).select( "*" )

Has worked for me.


问:
ZonedDateTime to UTC with offset applied?
I am using Java 8

This is what my ZonedDateTime looks like

```<code>2013-07-10T02:52:49+12:00
</code>```

I get this value as

```<code>z1.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME)
</code>```

where z1 is a ZonedDateTime.

I wanted to convert this value as 2013-07-10T14:52:49

How can I do that?

答:
@SimMac Thanks for the clarity. I also faced the same issue and able to find the answer based on his suggestion.

```<code>public static void main(String[] args) {
    try {
        String dateTime = "MM/dd/yyyy HH:mm:ss";
        String date = "09/17/2017 20:53:31";
        Integer gmtPSTOffset = -8;
        ZoneOffset offset = ZoneOffset.ofHours(gmtPSTOffset);

        // String to LocalDateTime
        LocalDateTime ldt = LocalDateTime.parse(date, DateTimeFormatter.ofPattern(dateTime));
        // Set the generated LocalDateTime's TimeZone. In this case I set it to UTC
        ZonedDateTime ldtUTC = ldt.atZone(ZoneOffset.UTC);
        System.out.println("UTC time with Timezone          : "+ldtUTC);

        // Convert above UTC to PST. You can pass ZoneOffset or Zone for 2nd parameter
        LocalDateTime ldtPST = LocalDateTime.ofInstant(ldtUTC.toInstant(), offset);
        System.out.println("PST time without offset         : "+ldtPST);

        // If you want UTC time with timezone
        ZoneId zoneId = ZoneId.of( "America/Los_Angeles" );
        ZonedDateTime zdtPST = ldtUTC.toLocalDateTime().atZone(zoneId);
        System.out.println("PST time with Offset and TimeZone   : "+zdtPST);

    } catch (Exception e) {
    }
}
</code>```

Output:

```<code>UTC time with Timezone          : 2017-09-17T20:53:31Z
PST time without offset         : 2017-09-17T12:53:31
PST time with Offset and TimeZone   : 2017-09-17T20:53:31-08:00[America/Los_Angeles]
</code>```

Body:
I am using Java 8

This is what my ZonedDateTime looks like

2013-07-10T02:52:49+12:00

I get this value as

z1.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME)

where z1 is a ZonedDateTime.

I wanted to convert this value as 2013-07-10T14:52:49

How can I do that?

Body:
@SimMac Thanks for the clarity. I also faced the same issue and able to find the answer based on his suggestion.

public static void main(String[] args) {
    try {
        String dateTime = "MM/dd/yyyy HH:mm:ss";
        String date = "09/17/2017 20:53:31";
        Integer gmtPSTOffset = -8;
        ZoneOffset offset = ZoneOffset.ofHours(gmtPSTOffset);

        // String to LocalDateTime
        LocalDateTime ldt = LocalDateTime.parse(date, DateTimeFormatter.ofPattern(dateTime));
        // Set the generated LocalDateTime's TimeZone. In this case I set it to UTC
        ZonedDateTime ldtUTC = ldt.atZone(ZoneOffset.UTC);
        System.out.println("UTC time with Timezone          : "+ldtUTC);

        // Convert above UTC to PST. You can pass ZoneOffset or Zone for 2nd parameter
        LocalDateTime ldtPST = LocalDateTime.ofInstant(ldtUTC.toInstant(), offset);
        System.out.println("PST time without offset         : "+ldtPST);

        // If you want UTC time with timezone
        ZoneId zoneId = ZoneId.of( "America/Los_Angeles" );
        ZonedDateTime zdtPST = ldtUTC.toLocalDateTime().atZone(zoneId);
        System.out.println("PST time with Offset and TimeZone   : "+zdtPST);

    } catch (Exception e) {
    }
}

Output:

UTC time with Timezone          : 2017-09-17T20:53:31Z
PST time without offset         : 2017-09-17T12:53:31
PST time with Offset and TimeZone   : 2017-09-17T20:53:31-08:00[America/Los_Angeles]


问:
Retrieve sessionStorage data on new page
js web storage newbie here.

I'm working on a billing page for a Wordpress site.

This page needs to show the items that a user has added to the cart on the previous (checkout page).

I have saved a new entry in the session storage database to show items in a user's cart like so :

```<code>setStorage_(data) {
  window.sessionStorage.setItem('tbhCart', JSON.stringify(data));
}
</code>```

How can I retrieve this data & display it on the next page (billing page)?

答:
simple answer would be </p>

```<code>sessionStorage.getItem('youritem');
</code>```

<p>Hope it helps. </p>

Body:
js web storage newbie here.

I'm working on a billing page for a Wordpress site.

This page needs to show the items that a user has added to the cart on the previous (checkout page).

I have saved a new entry in the session storage database to show items in a user's cart like so :

setStorage_(data) {
  window.sessionStorage.setItem('tbhCart', JSON.stringify(data));
}

How can I retrieve this data & display it on the next page (billing page)?

Body:
simple answer would be

sessionStorage.getItem('youritem');

Hope it helps.


问:
Return null if generic type is nullable
I am writing a function that checks if an output is DBNull and returns null if the generic type is nullable. If not it simply throws the error.

Update: added all recommendations

```<code>public T Get<T>(string key)
{
    int ordinal = reader.GetOrdinal(key);
    if (reader.IsDBNull(ordinal))
    {
        if (typeof(T).GetTypeInfo().IsValueType && Nullable.GetUnderlyingType(typeof(T)) == null) // isn't a nullable field
            throw new InvalidCastException();
        else return default(T);
    }
    return reader.GetFieldValue<T>(ordinal);
}
</code>```

However I am not sure if default(T) returns null for every nullable field. If now is there any other way to make it return null?

答:
In terms of computer resources, catching and handling an exception is an extremely expensive task. Your method is using the exception as part of its logic flow. This is an incorrect way of looking at the problem you are wanting to solve,.

In addition, you are catching specifically InvalidCastException exceptions. This exception can occur in other cases other than attempting to cast a null reference. You are hiding/misrepresenting a potentially valid error; something that can cost you many hours of frustrating, hair-pulling debugging.

The following should give you the same behavior as the original method, but without the overhead of unwinding the stack during the integrated error handling.

```<code>public T Get<T>(string key)
{
    if(reader.IsDbNull(reader.GetOrdinal(key)))
    {
       //IF YOU SPECIFICALLY WANT TO THROW AN ERROR IF A VALUE TYPE
       //if (typeof(T).IsValueType)
       //{ throw new InvalidCastException(); }
       return default(T);
    }

    return reader.GetFieldValue<T>(reader.GetOrdinal(key));
}
</code>```

Title: Return null if generic type is nullable

Body:
I am writing a function that checks if an output is DBNull and returns null if the generic type is nullable. If not it simply throws the error.

Update: added all recommendations

public T Get<T>(string key)
{
    int ordinal = reader.GetOrdinal(key);
    if (reader.IsDBNull(ordinal))
    {
        if (typeof(T).GetTypeInfo().IsValueType && Nullable.GetUnderlyingType(typeof(T)) == null) // isn't a nullable field
            throw new InvalidCastException();
        else return default(T);
    }
    return reader.GetFieldValue<T>(ordinal);
}

However I am not sure if default(T) returns null for every nullable field. If now is there any other way to make it return null?

Body:
In terms of computer resources, catching and handling an exception is an extremely expensive task. Your method is using the exception as part of its logic flow. This is an incorrect way of looking at the problem you are wanting to solve,.

In addition, you are catching specifically InvalidCastException exceptions. This exception can occur in other cases other than attempting to cast a null reference. You are hiding/misrepresenting a potentially valid error; something that can cost you many hours of frustrating, hair-pulling debugging.

The following should give you the same behavior as the original method, but without the overhead of unwinding the stack during the integrated error handling.

public T Get<T>(string key)
{
    if(reader.IsDbNull(reader.GetOrdinal(key)))
    {
       //IF YOU SPECIFICALLY WANT TO THROW AN ERROR IF A VALUE TYPE
       //if (typeof(T).IsValueType)
       //{ throw new InvalidCastException(); }
       return default(T);
    }

    return reader.GetFieldValue<T>(reader.GetOrdinal(key));
}


问:
node.js: is there no way to put HTML into i18n-node JSON translation files?
The question says it all.  If I put HTML directly into the (JSON-formatted) translation file, like this:

```<code>"test_html" : "click <a href='http://stackoverflow.com/'>here</a>",
</code>```

I get this in my HTML:

```<code>click <a href='http://stackoverflow.com/'>here</a>
</code>```

I also tried combining this in my translation file:

```<code>"test_html_placeholder" : "click %shere%s",
</code>```

With this in my HTML:

```<code><%= __('test_html_placeholder', '<a href="http://stackoverflow.com">', '</a>') %>
</code>```

But got similar results.

The only thing I can get to work is this clumsiness:

```<code>"test_html_pre" : "click ",
"test_html_link" : "here",
"test_html_post" : ".",
</code>```

with this:

```<code><%= __('test_html_pre') %><a href="http://stackoverflow.com"><%= __('test_html_link') %></a><%= __('test_html_post') %>
</code>```

But it's so cumbersome as to be almost not worth doing, and moreover the word order in some languages would force me to put some empty strings in my translation files, which i18n-node doesn't seem to like as it spits out the key (attribute) name when it
encounters an empty string.

I also tried using "\" as an escape character in front of the symbols, but I got an invalid JSON error when I lifted sails (restarted the server).

Any ideas, workarounds?  I'm using sails.js, it wasn't my decision but I'm stuck with it and it comes with i18n-node.  It's kind of late in the day on this project to consider using another library, but not completely out of the question.

答:
For those using pug/jade, you can use</p>

```<code>!{ __('key_for_your_text') }
</code>```

Body:
The question says it all.  If I put HTML directly into the (JSON-formatted) translation file, like this:

"test_html" : "click here",

I get this in my HTML:

click here

I also tried combining this in my translation file:

"test_html_placeholder" : "click %shere%s",

With this in my HTML:

<%= __('test_html_placeholder', '', '') %>

But got similar results.

The only thing I can get to work is this clumsiness:

"test_html_pre" : "click ",
"test_html_link" : "here",
"test_html_post" : ".",

with this:

<%= __('test_html_pre') %><%= __('test_html_link') %><%= __('test_html_post') %>

But it's so cumbersome as to be almost not worth doing, and moreover the word order in some languages would force me to put some empty strings in my translation files, which i18n-node doesn't seem to like as it spits out the key (attribute) name when it
encounters an empty string.

I also tried using "\" as an escape character in front of the symbols, but I got an invalid JSON error when I lifted sails (restarted the server).

Any ideas, workarounds?  I'm using sails.js, it wasn't my decision but I'm stuck with it and it comes with i18n-node.  It's kind of late in the day on this project to consider using another library, but not completely out of the question.

Body:
For those using pug/jade, you can use

!{ __('key_for_your_text') }


问:
How to get python to recognize "YYYY W##" as date time object and then fill add time objects less than a certain week
I have a dataframe consisting of columns Name (names), value (the week in 2016 that an event occurred), binary (an indication that the event occurred, "1"), for example:

```<code>df
    Name      value      binary
    apple     2016 W16   1
    orange    2016 W17   1
    melon     2016 W20   1
    berry     2016 W17   1
    lime      2016 W19   1
</code>```

I am interested in adding rows to this dataframe so that each Name (apple, orange, etc.) has an item in the value column for the weeks before an event occurred. Again, the week that the event occurred is stated as the value column in df. The time period of interest is the weeks between 2016 W16 and 2016 W19, e.g.:

```<code>start_end_weeks
     week
     2016 W16
     2016 W17
     2016 W18
     2016 W19
</code>```

My problem is that I need to in-fill the rows with weeks between 2016 W16 and 2016 W19 that are not represented in df. Here's what I mean:

```<code>df_result
    Name      value      binary
    apple     2016 W16   1
    orange    2016 W16   0
    orange    2016 W17   1
    melon     2016 W16   0
    melon     2016 W17   0
    melon     2016 W18   0
    melon     2016 W19   0
    melon     2016 W20   1
    berry     2016 W17   1
    lime      2016 W19   1
    ...
</code>```

But since value isn't a traditional date time object, I'm not sure how to get python to recognize that 2016 W16 occurs before 2016 W17, and then to only in-fill the values before the week stated in value in df.

I am having trouble with where to start, so if someone could help me convert value to a date time object that would be great, and I can go from there. Any other insight appreciated.

I found this stack overflow question which is all I have so far: Match rows in one Pandas dataframe to another based on three columns.

答:
You can get a valid datetime date as follows:

```<code>from datetime import datetime

df['year'] = df.value.str.split(' W').str[0]
df['week'] = df.value.str.split(' W').str[1]
df['date'] = df.apply(lambda x: datetime.strptime(
    x.year + '-' + x.week + '-0', '%Y-%W-%w'), axis=1)
</code>```

And the result will be:

```<code>    Name    value  binary   year    week    date
0   apple   2016 W16    1   2016    16      2016-04-24
1   orange  2016 W17    1   2016    17      2016-05-01
2   melon   2016 W20    1   2016    20      2016-05-22
3   berry   2016 W17    1   2016    17      2016-05-01
4   lime    2016 W19    1   2016    19      2016-05-15
</code>```

Body:
I have a dataframe consisting of columns Name (names), value (the week in 2016 that an event occurred), binary (an indication that the event occurred, "1"), for example:

df
    Name      value      binary
    apple     2016 W16   1
    orange    2016 W17   1
    melon     2016 W20   1
    berry     2016 W17   1
    lime      2016 W19   1

I am interested in adding rows to this dataframe so that each Name (apple, orange, etc.) has an item in the value column for the weeks before an event occurred. Again, the week that the event occurred is stated as the value column in df. The time period of interest is the weeks between 2016 W16 and 2016 W19, e.g.:

start_end_weeks
     week
     2016 W16
     2016 W17
     2016 W18
     2016 W19

My problem is that I need to in-fill the rows with weeks between 2016 W16 and 2016 W19 that are not represented in df. Here's what I mean:

df_result
    Name      value      binary
    apple     2016 W16   1
    orange    2016 W16   0
    orange    2016 W17   1
    melon     2016 W16   0
    melon     2016 W17   0
    melon     2016 W18   0
    melon     2016 W19   0
    melon     2016 W20   1
    berry     2016 W17   1
    lime      2016 W19   1
    ...

But since value isn't a traditional date time object, I'm not sure how to get python to recognize that 2016 W16 occurs before 2016 W17, and then to only in-fill the values before the week stated in value in df.

I am having trouble with where to start, so if someone could help me convert value to a date time object that would be great, and I can go from there. Any other insight appreciated.

I found this stack overflow question which is all I have so far: Match rows in one Pandas dataframe to another based on three columns.

Body:
You can get a valid datetime date as follows:

from datetime import datetime

df['year'] = df.value.str.split(' W').str[0]
df['week'] = df.value.str.split(' W').str[1]
df['date'] = df.apply(lambda x: datetime.strptime(
    x.year + '-' + x.week + '-0', '%Y-%W-%w'), axis=1)

And the result will be:

    Name    value  binary   year    week    date
0   apple   2016 W16    1   2016    16      2016-04-24
1   orange  2016 W17    1   2016    17      2016-05-01
2   melon   2016 W20    1   2016    20      2016-05-22
3   berry   2016 W17    1   2016    17      2016-05-01
4   lime    2016 W19    1   2016    19      2016-05-15


问:
multioutput regression by xgboost
Is it possible to train a model by xgboost that has multiple continuous outputs (multi-regression)?
What would be the objective of training such a model?

Thanks in advance for any suggestions

答:
My suggestion is to use sklearn.multioutput.MultiOutputRegressor as a wrapper of xgb.XGBRegressor. MultiOutputRegressor trains one regressor per target and only requires that the regressor implements fit and predict, which xgboost happens to support.

# get some noised linear data
X = np.random.random((1000, 10))
a = np.random.random((10, 3))
y = np.dot(X, a) + np.random.normal(0, 1e-3, (1000, 3))

# fitting
multioutputregressor = MultiOutputRegressor(xgb.XGBRegressor(objective='reg:linear')).fit(X, y)

# predicting
print(np.mean((multioutputregressor.predict(X) - y)**2, axis=0))  # 0.004, 0.003, 0.005
```

This is probably the easiest way to regress multi-dimension targets using xgboost as you would not need to change any other part of your code (if you were using the sklearn API originally).

However, this method does not leverage any possible relation between targets. But you can try to design a customized objective function to achieve that.

ContentLicense: CC BY-SA 4.0

Title: multioutput regression by xgboost

Body:
My suggestion is to use sklearn.multioutput.MultiOutputRegressor as a wrapper of xgb.XGBRegressor. MultiOutputRegressor trains one regressor per target and only requires that the regressor implements fit and predict, which xgboost happens to support.

# get some noised linear data
X = np.random.random((1000, 10))
a = np.random.random((10, 3))
y = np.dot(X, a) + np.random.normal(0, 1e-3, (1000, 3))

# fitting
multioutputregressor = MultiOutputRegressor(xgb.XGBRegressor(objective='reg:linear')).fit(X, y)

# predicting
print(np.mean((multioutputregressor.predict(X) - y)**2, axis=0))  # 0.004, 0.003, 0.005

This is probably the easiest way to regress multi-dimension targets using xgboost as you would not need to change any other part of your code (if you were using the sklearn API originally).

However, this method does not leverage any possible relation between targets. But you can try to design a customized objective function to achieve that.


问:
Bash Shell Scripting: How to Sum the Values in a File With the Use of For Loop and bc Command
I'm currently trying to write a function in my bash script that does the following: Take in a file as an argument and calculate the sum of the numbers within that file. I must make use of a for loop and the bc command.

Example of values in the file (each value on their own line):

```<code>12
4
53
19
6
</code>```

So here's what I have so far:

```<code>function sum_values() {
  for line in $1; do
  #not sure how to sum the values using bc
  done
}
</code>```

Am I on the right track? I'm not sure how to implement the bc command  in this situation.

答:
To do math in bash we surround an operation in $(( ... ))

Here are some examples:

```<code>$(( 5 + 5 )) # 10

my_var = $((5 + 5)) # my_var is now 10

my_var = $(($my_var + 5)) # my_var is now 10
</code>```

Solution to your problem:

```<code>function sum_values() {
    sum=0
    for i in $(<$1); do
        sum=$(($sum + $i))
    done
    echo $sum
}
</code>```

Note that you could have also done $(cat $1) instead of $(<$1) in the solution above.

Edit: Replaced return $sum with echo $sum

Body:
I'm currently trying to write a function in my bash script that does the following: Take in a file as an argument and calculate the sum of the numbers within that file. I must make use of a for loop and the bc command.

Example of values in the file (each value on their own line):

12
4
53
19
6

So here's what I have so far:

function sum_values() {
  for line in $1; do
  #not sure how to sum the values using bc
  done
}

Am I on the right track? I'm not sure how to implement the bc command  in this situation.

Body:
To do math in bash we surround an operation in $(( ... ))

Here are some examples:

$(( 5 + 5 )) # 10

my_var = $((5 + 5)) # my_var is now 10

my_var = $(($my_var + 5)) # my_var is now 10

Solution to your problem:

function sum_values() {
    sum=0
    for i in $(<$1); do
        sum=$(($sum + $i))
    done
    echo $sum
}

Note that you could have also done $(cat $1) instead of $(<$1) in the solution above.

Edit: Replaced return $sum with echo $sum


问:
Configuration options for SI 5.0.0, XML or DSL?
Am using SI 5.0.0 and a newbie.

WRT to SI 5.0.0 and Java8, what is the configuration option supported as default and moving forward ?

XML

DSL

Am a bit confused on this new release 5.0.0, as I just started SI from this version. Am not sure, what was the configuration option used in prev releases (< 5.0.0)and what is adopted as new configuration option in 5.0.0?

Thanks

答:
It's up to user preference; there are no plans to deprecate or remove the XML configuration.

Before 5.0, the DSL was also available, but it was in it's own jar with its own version.


问:
kubectl update service with new label and service names
Is it possible to update an external loadbalancer service in kubernetes with a new spec from an yaml file.

I can do rolling updates of the deployments but how can I update services, primarily not changing the external IP address.

Thanks, Rajesh

答:
If you do not want to edit on the living or already deployed  manifest file. you can edit the service manifest file on your computer and use apply action instead of create.
For instance,

```<code>kubectl apply -f service-manifest.yaml
</code>```

It will work without changing already existing external IPs

Body:
If you do not want to edit on the living or already deployed  manifest file. you can edit the service manifest file on your computer and use apply action instead of create.
For instance,

kubectl apply -f service-manifest.yaml

It will work without changing already existing external IPs


问:
Android Google Places autocomplete api bounds not working
I want to be able to autocomplete some places by using the google places api. I only want to include certain places from a certain area. Googles API docs describe this feature by using the function setBoundsBias, but I can't seem to get it working properly as it still returns results from outside the specified area.

```<code>try {
            Intent intent = new PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_OVERLAY)
                    .setBoundsBias(new LatLngBounds(
                            new LatLng(16.371163, 21.051073),
                            new LatLng(16.725743, 21.424006)))
                    .build(getActivity());

            startActivityForResult(intent, requestCode);
        } catch (GooglePlayServicesRepairableException | GooglePlayServicesNotAvailableException e) {
            e.printStackTrace();
        }
</code>```

答:
The setBoundsBias is supposed to return results from outside the area.
It is only a bias.
If you want to exclusively return results from within the bounds, you must use the AutocompleteFilter.
Unfortunately currently the only level of filtering by region is by country.

Body:
I want to be able to autocomplete some places by using the google places api. I only want to include certain places from a certain area. Googles API docs describe this feature by using the function setBoundsBias, but I can't seem to get it working properly as it still returns results from outside the specified area.

try {
            Intent intent = new PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_OVERLAY)
                    .setBoundsBias(new LatLngBounds(
                            new LatLng(16.371163, 21.051073),
                            new LatLng(16.725743, 21.424006)))
                    .build(getActivity());

            startActivityForResult(intent, requestCode);
        } catch (GooglePlayServicesRepairableException | GooglePlayServicesNotAvailableException e) {
            e.printStackTrace();
        }


问:
Using Switch-blocks to Parse input for a Text Adventure?
Okay, I have a goal right now to make a basic text adventure. To do this, however, I would need/want to have a switch statement that can do the following:

Check to see if a string has a word SOMEWHERE inside.

Check to see if a string has two words in any combination somewhere inside.

How would I accomplish this? Could you show me coding for this specific example:

A user is prompted for data. A switch statement checks for "look box" as one case, and "sleep" as another. The program doesn't care what order any words are in, but does care about the order of the letters.

Please explain everything in detail. I just started coding.

EDIT: Thank you for all the answers. I understand there are better, more complicated, and more useful ways of handling this, but it just isn't at my level yet.

答:
People sometimes ask me why I don't built a boat. I'm pretty handy, I like building things, and I sail. I always tell them that people who like to sail shouldn't build boats, because you end up spending three years in your garage building a boat before you can go sailing. If your goal is to sail, buy a boat. If your goal is to build a boat, build a boat.

If your goal is to learn C# by writing a text adventure, great, you'll learn a lot. If your goal is to write a text adventure, then don't use C#, use Inform7. It is easy to learn, specifically designed to write text adventures, and is probably the most high level language in the world. It is an amazing programming language and I highly recommend it.

To answer your specific question: that is not a good way to go about it. The way text adventure processors actually work is first you write a program that breaks the sentence typed by the user up into tokens. You have to search through the string character by character looking for boundaries between words, like spaces, commas, periods, and so on.  Once you find the boundaries then you extract the substrings between the boundaries and try to recognize every word by comparing it to words in a dictionary.

Once you have a sequence of tokens you then try to match the sequence against a grammar. That is, you see if the sequence of tokens can be classified as a one-word command like {"look"} or a verb-noun phrase like {"look", "at", "the", "red", "button"}. You want to break that down - "look" is the verb, "at" is the preposition, "the red button" is the object of the verb, "the" is the article, "red" is the adjective and "button" is the noun.

It sounds like you're a beginner, so concentrate first on the lexical analysis; walking through the string one character at a time, identifying word boundaries, and building up a List<string> of tokens. Techniques for grammatical analysis can be quite complicated; get the simple stuff done and solid first.

ContentLicense: CC BY-SA 2.5


问:
How to get effectors working on my character unity 2d
I'm trying to use a buoyancy effector in my platformer however for some reason due to my controller script that's attached to my player makes the effector does not work. Below is my controller script.

controller.cs

```<code>using UnityEngine;
using System.Collections;

public class controller : MonoBehaviour
{

    public float topSpeed = 15f;
    bool facingRight = true;

    bool grounded = false;

    public Transform groundCheck;

    float groundRadius = 0.2f;

    GameObject Player, Player2;
    int characterselect;

    public float jumpForce = 700f;

    public LayerMask whatIsGround;

    void Start()
    {
        characterselect = 1;
        Player = GameObject.Find("Player");
        Player2 = GameObject.Find("Player2");

    }

    void FixedUpdate()
    {

        grounded = Physics2D.OverlapCircle(groundCheck.position, groundRadius, whatIsGround);

        float move = Input.GetAxis("Horizontal");

        GetComponent<Rigidbody2D>().velocity = new Vector2(move * topSpeed, GetComponent<Rigidbody2D>().velocity.y);
        if (move > 0 && !facingRight) //if facing not right then use the flip function
            flip();
        else if (move < 0 && facingRight)
            flip();

    }

    void Update()
    {

        if(grounded&& Input.GetKeyDown(KeyCode.Space))
        {

            GetComponent<Rigidbody2D>().AddForce(new Vector2(0, jumpForce));
        }
        {

        }
        if (Input.GetKeyDown(KeyCode.LeftShift))
        {
            topSpeed = topSpeed * 2;
        }
        else if (Input.GetKeyUp(KeyCode.LeftShift))
        {
            topSpeed = 15;
        }

    }

    void flip()
    {

        facingRight = ! facingRight;

        Vector3 theScale = transform.localScale;

        theScale.x *= -1;

        transform.localScale = theScale;

    }

}
</code>```

When I disable this script it works fine. Just wondering how I can make the effector work with my current controller script.

答:
It's this line:

```<code>GetComponent<Rigidbody2D>().velocity = new Vector2(
    move * topSpeed,
    GetComponent<Rigidbody2D>().velocity.y);
</code>```

By setting the velocity, you are overriding whatever velocity is added by the physics engine—including from buoyancy effectors. If you want to keep the physics from the buoyancy effector, do some kind of sum instead. There are plenty of ways to implement this, depending on exactly what behavior you want.

I would also recommend that you store the Rigidbody2D as a variable to save time for both you and the computer:

```<code>using UnityEngine;
using System.Collections;

public class Controller : MonoBehaviour
{
    // ...
    Rigidbody2D rbody2D;

    void Start() {
        // ...
        rbody2D = GetComponent<Rigidbody2D>();
    }

    void FixedUpdate() {
        // One simple example of adding to the velocity.
        // Adds velocity in the x-axis such that the new x velocity
        //   is about equal to topSpeed in the direction we are trying to move.
        // Note that "Vector2.right * deltaVelX" = "new Vector2(deltaVelX, 0)".
        float move = Input.GetAxis("Horizontal");
        float deltaVelX = (move * topSpeed) - rbody2D.velocity.x;
        rbody2D.velocity += Vector2.right * deltaVelX;
    }
}
</code>```

Body:
I'm trying to use a buoyancy effector in my platformer however for some reason due to my controller script that's attached to my player makes the effector does not work. Below is my controller script.

controller.cs

using UnityEngine;
using System.Collections;

public class controller : MonoBehaviour
{

    public float topSpeed = 15f;
    bool facingRight = true;

    bool grounded = false;

    public Transform groundCheck;

    float groundRadius = 0.2f;

    GameObject Player, Player2;
    int characterselect;

    public float jumpForce = 700f;

    public LayerMask whatIsGround;

    void Start()
    {
        characterselect = 1;
        Player = GameObject.Find("Player");
        Player2 = GameObject.Find("Player2");

    }

    void FixedUpdate()
    {

        grounded = Physics2D.OverlapCircle(groundCheck.position, groundRadius, whatIsGround);

        float move = Input.GetAxis("Horizontal");

        GetComponent<Rigidbody2D>().velocity = new Vector2(move * topSpeed, GetComponent<Rigidbody2D>().velocity.y);
        if (move > 0 && !facingRight) //if facing not right then use the flip function
            flip();
        else if (move < 0 && facingRight)
            flip();

    }

    void Update()
    {

        if(grounded&& Input.GetKeyDown(KeyCode.Space))
        {

            GetComponent<Rigidbody2D>().AddForce(new Vector2(0, jumpForce));
        }
        {

        }
        if (Input.GetKeyDown(KeyCode.LeftShift))
        {
            topSpeed = topSpeed * 2;
        }
        else if (Input.GetKeyUp(KeyCode.LeftShift))
        {
            topSpeed = 15;
        }

    }

    void flip()
    {

        facingRight = ! facingRight;

        Vector3 theScale = transform.localScale;

        theScale.x *= -1;

        transform.localScale = theScale;

    }

}

When I disable this script it works fine. Just wondering how I can make the effector work with my current controller script.

Body:
It's this line:

GetComponent<Rigidbody2D>().velocity = new Vector2(
    move * topSpeed,
    GetComponent<Rigidbody2D>().velocity.y);

By setting the velocity, you are overriding whatever velocity is added by the physics engine—including from buoyancy effectors. If you want to keep the physics from the buoyancy effector, do some kind of sum instead. There are plenty of ways to implement this, depending on exactly what behavior you want.

I would also recommend that you store the Rigidbody2D as a variable to save time for both you and the computer:

using UnityEngine;
using System.Collections;

public class Controller : MonoBehaviour
{
    // ...
    Rigidbody2D rbody2D;

    void Start() {
        // ...
        rbody2D = GetComponent<Rigidbody2D>();
    }

    void FixedUpdate() {
        // One simple example of adding to the velocity.
        // Adds velocity in the x-axis such that the new x velocity
        //   is about equal to topSpeed in the direction we are trying to move.
        // Note that "Vector2.right * deltaVelX" = "new Vector2(deltaVelX, 0)".
        float move = Input.GetAxis("Horizontal");
        float deltaVelX = (move * topSpeed) - rbody2D.velocity.x;
        rbody2D.velocity += Vector2.right * deltaVelX;
    }
}


答:
Use getItem() on sessionStorage.

```<code>var tbhCart = sessionStorage.getItem("tbhCart");
</code>```

Title: Retrieve sessionStorage data on new page

Body:
Use getItem() on sessionStorage.

var tbhCart = sessionStorage.getItem("tbhCart");


问:
HTML/CSS/Javascript: Open/Close Menu when Clicking Button
I've got a hamburger icon for my page that should open/close a dropdown menu when clicked on. I pulled the code for the hamburger icon from Jonathan Suh's github page and am trying to implement a open/close dropdown menu with it (here's the page for your reference https://github.com/jonsuh/hamburgers).

The problem is that when I click on it, the dropdown menu will appear, but when I click on it again it won't disappear. I've tried a few things, such as setting a boolean variable to false and making it true when clicked on, but the code doesn't execute the way I imagine it would. Here's the Code:

//declarations
var hamburger = document.querySelector(".hamburger");

function dropDown() {
  document.querySelector(".dropdown-content").style.display = "block";

}

hamburger.addEventListener("click", function() {
  hamburger.classList.toggle("is-active");
  dropDown();
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.dropdown {
  position: relative;
  display: inline-block;
}

.dropdown-content {
  display: none;
  position: absolute;
  z-index: 1;
}

.dropdown-content a {
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
}

.show {
  display: block;
}

/*!
 * Hamburgers
 * @description Tasty CSS-animated hamburgers
 * @author Jonathan Suh @jonsuh
 * @site https://jonsuh.com/hamburgers
 * @link https://github.com/jonsuh/hamburgers
 */

.hamburger {
  padding: 15px 15px;
  display: inline-block;
  cursor: pointer;
  transition-property: opacity, filter;
  transition-duration: 0.15s;
  transition-timing-function: linear;
  font: inherit;
  color: inherit;
  text-transform: none;
  background-color: transparent;
  border: 0;
  margin: 0;
  overflow: visible;
}

.hamburger:hover {
  opacity: 0.7;
}

.hamburger-box {
  width: 40px;
  height: 24px;
  display: inline-block;
  position: relative;
}

.hamburger-inner {
  display: block;
  top: 50%;
  margin-top: -2px;
}

.hamburger-inner,
.hamburger-inner::before,
.hamburger-inner::after {
  width: 40px;
  height: 4px;
  background-color: #000;
  border-radius: 4px;
  position: absolute;
  transition-property: transform;
  transition-duration: 0.15s;
  transition-timing-function: ease;
}

.hamburger-inner::before,
.hamburger-inner::after {
  content: "";
  display: block;
}

.hamburger-inner::before {
  top: -10px;
}

.hamburger-inner::after {
  bottom: -10px;
}

/*
   * Spring
   */

.hamburger--spring .hamburger-inner {
  top: 2px;
  transition: background-color 0s 0.13s linear;
}

.hamburger--spring .hamburger-inner::before {
  top: 10px;
  transition: top 0.1s 0.2s cubic-bezier(0.33333, 0.66667, 0.66667, 1), transform 0.13s cubic-bezier(0.55, 0.055, 0.675, 0.19);
}

.hamburger--spring .hamburger-inner::after {
  top: 20px;
  transition: top 0.2s 0.2s cubic-bezier(0.33333, 0.66667, 0.66667, 1), transform 0.13s cubic-bezier(0.55, 0.055, 0.675, 0.19);
}

.hamburger--spring.is-active .hamburger-inner {
  transition-delay: 0.22s;
  background-color: transparent;
}

.hamburger--spring.is-active .hamburger-inner::before {
  top: 0;
  transition: top 0.1s 0.15s cubic-bezier(0.33333, 0, 0.66667, 0.33333), transform 0.13s 0.22s cubic-bezier(0.215, 0.61, 0.355, 1);
  transform: translate3d(0, 10px, 0) rotate(45deg);
}

.hamburger--spring.is-active .hamburger-inner::after {
  top: 0;
  transition: top 0.2s cubic-bezier(0.33333, 0, 0.66667, 0.33333), transform 0.13s 0.22s cubic-bezier(0.215, 0.61, 0.355, 1);
  transform: translate3d(0, 10px, 0) rotate(-45deg);
}</code>```

    <button onclick="dropDown()" class="hamburger hamburger--spring" type="button">

            Home
            Work
            Resume
            Life

    </button>

```

While I know there is probably a solution you can use in jQuery, I have no experience with that. So please, keep it in JavaScript. I am completely new to it, but have a basic understanding of how it works.

答:
No need for dropDown() or any additional JS for that matter. Your current click event handler will do just fine. Just add a descendant selector in your CSS that targets dropdown-content when .hamburger also has the class of .is-active (which is already being handled through your class toggle):

```<code>.hamburger.is-active .dropdown-content {
  display: block;
}
</code>```

Body:
I've got a hamburger icon for my page that should open/close a dropdown menu when clicked on. I pulled the code for the hamburger icon from Jonathan Suh's github page and am trying to implement a open/close dropdown menu with it (here's the page for your reference https://github.com/jonsuh/hamburgers).

The problem is that when I click on it, the dropdown menu will appear, but when I click on it again it won't disappear. I've tried a few things, such as setting a boolean variable to false and making it true when clicked on, but the code doesn't execute the way I imagine it would. Here's the Code:

//declarations
var hamburger = document.querySelector(".hamburger");

function dropDown() {
  document.querySelector(".dropdown-content").style.display = "block";

}

hamburger.addEventListener("click", function() {
  hamburger.classList.toggle("is-active");
  dropDown();
});

.dropdown {
  position: relative;
  display: inline-block;
}

.dropdown-content {
  display: none;
  position: absolute;
  z-index: 1;
}

.dropdown-content a {
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
}

.show {
  display: block;
}

/*!
 * Hamburgers
 * @description Tasty CSS-animated hamburgers
 * @author Jonathan Suh @jonsuh
 * @site https://jonsuh.com/hamburgers
 * @link https://github.com/jonsuh/hamburgers
 */

.hamburger {
  padding: 15px 15px;
  display: inline-block;
  cursor: pointer;
  transition-property: opacity, filter;
  transition-duration: 0.15s;
  transition-timing-function: linear;
  font: inherit;
  color: inherit;
  text-transform: none;
  background-color: transparent;
  border: 0;
  margin: 0;
  overflow: visible;
}

.hamburger:hover {
  opacity: 0.7;
}

.hamburger-box {
  width: 40px;
  height: 24px;
  display: inline-block;
  position: relative;
}

.hamburger-inner {
  display: block;
  top: 50%;
  margin-top: -2px;
}

.hamburger-inner,
.hamburger-inner::before,
.hamburger-inner::after {
  width: 40px;
  height: 4px;
  background-color: #000;
  border-radius: 4px;
  position: absolute;
  transition-property: transform;
  transition-duration: 0.15s;
  transition-timing-function: ease;
}

.hamburger-inner::before,
.hamburger-inner::after {
  content: "";
  display: block;
}

.hamburger-inner::before {
  top: -10px;
}

.hamburger-inner::after {
  bottom: -10px;
}

/*
   * Spring
   */

.hamburger--spring .hamburger-inner {
  top: 2px;
  transition: background-color 0s 0.13s linear;
}

.hamburger--spring .hamburger-inner::before {
  top: 10px;
  transition: top 0.1s 0.2s cubic-bezier(0.33333, 0.66667, 0.66667, 1), transform 0.13s cubic-bezier(0.55, 0.055, 0.675, 0.19);
}

.hamburger--spring .hamburger-inner::after {
  top: 20px;
  transition: top 0.2s 0.2s cubic-bezier(0.33333, 0.66667, 0.66667, 1), transform 0.13s cubic-bezier(0.55, 0.055, 0.675, 0.19);
}

.hamburger--spring.is-active .hamburger-inner {
  transition-delay: 0.22s;
  background-color: transparent;
}

.hamburger--spring.is-active .hamburger-inner::before {
  top: 0;
  transition: top 0.1s 0.15s cubic-bezier(0.33333, 0, 0.66667, 0.33333), transform 0.13s 0.22s cubic-bezier(0.215, 0.61, 0.355, 1);
  transform: translate3d(0, 10px, 0) rotate(45deg);
}

.hamburger--spring.is-active .hamburger-inner::after {
  top: 0;
  transition: top 0.2s cubic-bezier(0.33333, 0, 0.66667, 0.33333), transform 0.13s 0.22s cubic-bezier(0.215, 0.61, 0.355, 1);
  transform: translate3d(0, 10px, 0) rotate(-45deg);
}

    <button onclick="dropDown()" class="hamburger hamburger--spring" type="button">

            Home
            Work
            Resume
            Life

    </button>

While I know there is probably a solution you can use in jQuery, I have no experience with that. So please, keep it in JavaScript. I am completely new to it, but have a basic understanding of how it works.

Body:
No need for dropDown() or any additional JS for that matter. Your current click event handler will do just fine. Just add a descendant selector in your CSS that targets dropdown-content when .hamburger also has the class of .is-active (which is already being handled through your class toggle):

.hamburger.is-active .dropdown-content {
  display: block;
}


问:
How to add a user-defined typecast for a variable in c++?
I have a class with functions that take vector<double> as input and also return vector<double>.

I want to overload this function to take Eigen::vectorXd as input and output. I have many functions that need to be overloaded. Is there a way to create a typecast which would typecast Eigen::vecrtorXd to vector<double> for all these functions?

答:
Depending on what you're looking for, you might be able to achieve this with a basic templated function, i.e.

```<code>template <typename vec_t>
vec_t do_something(const vec_t& input)
{
  // Do things
}
</code>```

This works fine if you want to do something generic like calculate a norm where the dimension of the vector doesn't matter.

Body:
Depending on what you're looking for, you might be able to achieve this with a basic templated function, i.e.

template <typename vec_t>
vec_t do_something(const vec_t& input)
{
  // Do things
}

This works fine if you want to do something generic like calculate a norm where the dimension of the vector doesn't matter.


问:
Bootstrap 4 - Image overflows from column when the window is resized
Bootstrap newbie here.

I'm trying to bootstrapify an old page but I can't seem to figure out how to stop my image from overflowing to the next column. I have a row with two columns- with the left side containing a picture. As soon as I reduce the window width, my image will start overflowing to the right column and will eventually collapse on top of the right column. I would like for the left column width to remain static or collapse to the top of the right column until the image can no longer fit in the left column.

I've tried adding the image-responsive class to the image but that will only change my image dimensions and I would prefer the image to keep its dimensions. Any help would be greatly appreciated!

Here is my code: https://www.codeply.com/go/fb14u8fsSc

答:
Is it something like the one below you are looking for?

A couple of notes though:

It might be because of your simplified codeply example, but you use

…X…

, which is the equivalent of …X…. That simplifies things.

We are talking about Bootstrap 4 here (you also use that in your codeply), but the .img-responsive class is from Bootstrap 3. That class is called .img-fluid in Bootstrap 4.

Regarding inline-style margins, I would suggest to use the spacing utility classes instead.

                    Insert name here

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" rel="stylesheet"/>```

Body:
Is it something like the one below you are looking for?

A couple of notes though:

It might be because of your simplified codeply example, but you use <div class="row"><div class="col-md-12">…X…</div></div>, which is the equivalent of …X…. That simplifies things.

We are talking about Bootstrap 4 here (you also use that in your codeply), but the .img-responsive class is from Bootstrap 3. That class is called .img-fluid in Bootstrap 4.

Regarding inline-style margins, I would suggest to use the spacing utility classes instead.

<div class="container-fluid" style="position: fixed">
    <div class="row">
        <div class="col">
            <div class="card my-3">
                <div class="card-header"></div>

                <div class="card-body">
                    Insert name here<br/>
                    <img src="https://dummyimage.com/188x225/000/fff" class="XXXimg-fluid" alt=""/>
                </div>

                <div class="card-footer"></div>
            </div>
        </div>

        <div class="col-md-9">
            <div class="card text-xs-center mt-3">
                <div class="card-header"></div>
                <div class="card-body"></div>
            </div>
        </div>
    </div>
</div>

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" rel="stylesheet"/>


问:
iOS SceneKit to UIView projection issue
I have a SCNView with SCNNode of SCNPlane geometry in front of my camera root node.

Over SCNView, in UIView, I am adding UIImages (Markers) - orange circles.

In Motion listener I am trying to position the Markers in a way so they will stick to the center of each edge of the Plane.

A proper Markers alignment - while device is in straight position:

I'm doing this using projection from SceneKit objects to UIView:

```<code>//world coordinates
let v1w =  sm.node.convertPosition(sm.node.boundingBox.min,
    to: self.sceneView.scene?.rootNode)
let v2w =  sm.node.convertPosition(sm.node.boundingBox.max,
    to: self.sceneView.scene?.rootNode)

//projected coordinates
let v1p = self.sceneView.projectPoint(v1w)
let v2p = self.sceneView.projectPoint(v2w)

//frame rectangle
let rect = CGRect.init(x: CGFloat(v1p.x), y: CGFloat(v2p.y),
    width: CGFloat(v2p.x - v1p.x), height: CGFloat(v1p.y - v2p.y))

var frameOld = sm.marker.frame

switch sm.position
{
case .Top:
    frameOld.origin.y = rect.minY - frameOld.size.height/2
    frameOld.origin.x = rect.midX - frameOld.size.width/2
case .Bottom:
    frameOld.origin.y = rect.maxY - frameOld.size.height/2
    frameOld.origin.x = rect.midX - frameOld.size.width/2
case .Left:
    frameOld.origin.y = rect.midY - frameOld.size.height/2
    frameOld.origin.x = rect.minX - frameOld.size.width/2
case .Right:
    frameOld.origin.y = rect.midY - frameOld.size.height/2
    frameOld.origin.x = rect.maxX - frameOld.size.width/2
}

sm.marker.frame = frameOld
self.view.layoutSubviews()
</code>```

Similar approach you can find here: Scene Kit: projectPoint calculated is displaced

So I would like those Markers to stick to the edges of the Plane during device motion. But there is the issue: when rotating device - Markers are drifting from the Plane edges

See video of an issue: https://youtu.be/XBgNDDX5ZI8

I have created a basic project on github to reproduce an issue: https://github.com/mgontar/SceneKitProjectionIssue

答:
The problem here is that CGRect you use to calculate the mid points is based on the projected coordinates of the bounding box. The two corner points of the bounding box are transformed using the model view projection matrix, to get the correct view space coordinates for the mid points you need to perform the same transformation.

Hopefully the code is a bit clearer.

```<code>//world coordinates
let v1w =  sm.node.convertPosition(sm.node.boundingBox.min, to: self.sceneView.scene?.rootNode)
let v2w =  sm.node.convertPosition(sm.node.boundingBox.max, to: self.sceneView.scene?.rootNode)

//calc center of BB in world coordinates
let center = SCNVector3Make(
    (v1w.x + v2w.x)/2,
    (v1w.y + v2w.y)/2,
    (v1w.z + v2w.z)/2)

//calc each mid point
let mp1w = SCNVector3Make(v1w.x, center.y, center.z)
let mp2w = SCNVector3Make(center.x, v2w.y, center.z)
let mp3w = SCNVector3Make(v2w.x, center.y, center.z)
let mp4w = SCNVector3Make(center.x, v1w.y, center.z)

//projected coordinates
let mp1p = self.sceneView.projectPoint(mp1w)
let mp2p = self.sceneView.projectPoint(mp2w)
let mp3p = self.sceneView.projectPoint(mp3w)
let mp4p = self.sceneView.projectPoint(mp4w)

var frameOld = sm.marker.frame

switch sm.position
{
case .Top:
    frameOld.origin.y = CGFloat(mp1p.y) - frameOld.size.height/2
    frameOld.origin.x = CGFloat(mp1p.x) - frameOld.size.width/2
    sm.marker.isHidden = (mp1p.z < 0 || mp1p.z > 1)
case .Bottom:
    frameOld.origin.y = CGFloat(mp2p.y) - frameOld.size.height/2
    frameOld.origin.x = CGFloat(mp2p.x) - frameOld.size.width/2
    sm.marker.isHidden = (mp2p.z < 0 || mp2p.z > 1)
case .Left:
    frameOld.origin.y = CGFloat(mp3p.y) - frameOld.size.height/2
    frameOld.origin.x = CGFloat(mp3p.x) - frameOld.size.width/2
    sm.marker.isHidden = (mp3p.z < 0 || mp3p.z > 1)
case .Right:
    frameOld.origin.y = CGFloat(mp4p.y) - frameOld.size.height/2
    frameOld.origin.x = CGFloat(mp4p.x) - frameOld.size.width/2
    sm.marker.isHidden = (mp4p.z < 0 || mp4p.z > 1)
}
</code>```

It's a cool little sample project!

Update on z-clipping issue

The projectPoint method returns a 3D SCNVector, the x any y coords as we know are the screen coordinates. The z coordinate tells us the location of the point relative to the far and near clipping planes (z = 0 near clipping plane, z = 1 far clipping plane). If you set a negative value for your near clipping plane, objects behind the camera would be rendered. We don't have a negative near clipping plane, but we also don't have any logic to say what happens if those projected point locations fall outside the z far and z near range.

I've updated the code above to include this zNear and zFar check and toggle the UIView visibility accordingly.

tl;dr

The markers visible when the camera was rotated 180deg are behind the camera, but they were still projected onto the view plane. And as we weren't checking if they we behind the camera, they were still displayed.

Title: iOS SceneKit to UIView projection issue

Body:
I have a SCNView with SCNNode of SCNPlane geometry in front of my camera root node.

Over SCNView, in UIView, I am adding UIImages (Markers) - orange circles.

In Motion listener I am trying to position the Markers in a way so they will stick to the center of each edge of the Plane.

A proper Markers alignment - while device is in straight position:

I'm doing this using projection from SceneKit objects to UIView:

//world coordinates
let v1w =  sm.node.convertPosition(sm.node.boundingBox.min,
    to: self.sceneView.scene?.rootNode)
let v2w =  sm.node.convertPosition(sm.node.boundingBox.max,
    to: self.sceneView.scene?.rootNode)

//projected coordinates
let v1p = self.sceneView.projectPoint(v1w)
let v2p = self.sceneView.projectPoint(v2w)

//frame rectangle
let rect = CGRect.init(x: CGFloat(v1p.x), y: CGFloat(v2p.y),
    width: CGFloat(v2p.x - v1p.x), height: CGFloat(v1p.y - v2p.y))

var frameOld = sm.marker.frame

switch sm.position
{
case .Top:
    frameOld.origin.y = rect.minY - frameOld.size.height/2
    frameOld.origin.x = rect.midX - frameOld.size.width/2
case .Bottom:
    frameOld.origin.y = rect.maxY - frameOld.size.height/2
    frameOld.origin.x = rect.midX - frameOld.size.width/2
case .Left:
    frameOld.origin.y = rect.midY - frameOld.size.height/2
    frameOld.origin.x = rect.minX - frameOld.size.width/2
case .Right:
    frameOld.origin.y = rect.midY - frameOld.size.height/2
    frameOld.origin.x = rect.maxX - frameOld.size.width/2
}

sm.marker.frame = frameOld
self.view.layoutSubviews()

Similar approach you can find here: Scene Kit: projectPoint calculated is displaced

So I would like those Markers to stick to the edges of the Plane during device motion. But there is the issue: when rotating device - Markers are drifting from the Plane edges

See video of an issue: https://youtu.be/XBgNDDX5ZI8

I have created a basic project on github to reproduce an issue: https://github.com/mgontar/SceneKitProjectionIssue

Body:
The problem here is that CGRect you use to calculate the mid points is based on the projected coordinates of the bounding box. The two corner points of the bounding box are transformed using the model view projection matrix, to get the correct view space coordinates for the mid points you need to perform the same transformation.

Hopefully the code is a bit clearer.

//world coordinates
let v1w =  sm.node.convertPosition(sm.node.boundingBox.min, to: self.sceneView.scene?.rootNode)
let v2w =  sm.node.convertPosition(sm.node.boundingBox.max, to: self.sceneView.scene?.rootNode)

//calc center of BB in world coordinates
let center = SCNVector3Make(
    (v1w.x + v2w.x)/2,
    (v1w.y + v2w.y)/2,
    (v1w.z + v2w.z)/2)

//calc each mid point
let mp1w = SCNVector3Make(v1w.x, center.y, center.z)
let mp2w = SCNVector3Make(center.x, v2w.y, center.z)
let mp3w = SCNVector3Make(v2w.x, center.y, center.z)
let mp4w = SCNVector3Make(center.x, v1w.y, center.z)

//projected coordinates
let mp1p = self.sceneView.projectPoint(mp1w)
let mp2p = self.sceneView.projectPoint(mp2w)
let mp3p = self.sceneView.projectPoint(mp3w)
let mp4p = self.sceneView.projectPoint(mp4w)

var frameOld = sm.marker.frame

switch sm.position
{
case .Top:
    frameOld.origin.y = CGFloat(mp1p.y) - frameOld.size.height/2
    frameOld.origin.x = CGFloat(mp1p.x) - frameOld.size.width/2
    sm.marker.isHidden = (mp1p.z < 0 || mp1p.z > 1)
case .Bottom:
    frameOld.origin.y = CGFloat(mp2p.y) - frameOld.size.height/2
    frameOld.origin.x = CGFloat(mp2p.x) - frameOld.size.width/2
    sm.marker.isHidden = (mp2p.z < 0 || mp2p.z > 1)
case .Left:
    frameOld.origin.y = CGFloat(mp3p.y) - frameOld.size.height/2
    frameOld.origin.x = CGFloat(mp3p.x) - frameOld.size.width/2
    sm.marker.isHidden = (mp3p.z < 0 || mp3p.z > 1)
case .Right:
    frameOld.origin.y = CGFloat(mp4p.y) - frameOld.size.height/2
    frameOld.origin.x = CGFloat(mp4p.x) - frameOld.size.width/2
    sm.marker.isHidden = (mp4p.z < 0 || mp4p.z > 1)
}

It's a cool little sample project!

Update on z-clipping issue

The projectPoint method returns a 3D SCNVector, the x any y coords as we know are the screen coordinates. The z coordinate tells us the location of the point relative to the far and near clipping planes (z = 0 near clipping plane, z = 1 far clipping plane). If you set a negative value for your near clipping plane, objects behind the camera would be rendered. We don't have a negative near clipping plane, but we also don't have any logic to say what happens if those projected point locations fall outside the z far and z near range.

I've updated the code above to include this zNear and zFar check and toggle the UIView visibility accordingly.

tl;dr

The markers visible when the camera was rotated 180deg are behind the camera, but they were still projected onto the view plane. And as we weren't checking if they we behind the camera, they were still displayed.


问:
Algorithm for optimal "intersection" of two results?
I have two results and like to get the best "order" of both these.
Example:

We have a race with 5 people in one race, and 7 in another. The outcome is:
Race 1.

```<code>1. Karl
2. Fred
3. John
4. Peter
5. Sid
</code>```

Race 2.

```<code>1. Steven
2. John
3. Karl
4. Peter
5. Aron
6. Fred
7. Kevin
</code>```

The questin is: whats the top 7 of both these races?

Its quite obvious that that nr 1 is Karl in this case, since he hold one 1st place and one 3rd, which is better than Johns second and third place. However, Steven could be equally good but he did only participate in one race and should suffer some kind of penalty for that.

What are the known algorithms for this problem? Are there any trivial solutions? I just can't figure it out

答:
A naive solution would be to have some kind of ID for all the players. Go through both lists and add any new IDs you come across to a separate list, called Positions for example. Set all values for these IDs to some large number that can not be a race position, call it BIG_VAL (eg. 100). Go through the first list and mark all the positions as the new values in the Positions list. This was just the first race, so there is nothing special here. Then go through the second list and add the second position results for those IDs into the Positions list. For the IDs that don't occur, add another BIG_VAL to their result. The list will now have the race positions in order, all that remains is to sort them. Karl will be 4, John will be 5, Fred will be 8, and so on in this list:

http://bit.ly/fvYtal

Body:
I have two results and like to get the best "order" of both these.
Example:

We have a race with 5 people in one race, and 7 in another. The outcome is:
Race 1.

1. Karl
2. Fred
3. John
4. Peter
5. Sid

Race 2.

1. Steven
2. John
3. Karl
4. Peter
5. Aron
6. Fred
7. Kevin

The questin is: whats the top 7 of both these races?

Its quite obvious that that nr 1 is Karl in this case, since he hold one 1st place and one 3rd, which is better than Johns second and third place. However, Steven could be equally good but he did only participate in one race and should suffer some kind of penalty for that.

What are the known algorithms for this problem? Are there any trivial solutions? I just can't figure it out


问:
proper installation sequence of Aptana, node.js, ruby, SASS
My wife of 13 years, Dreamweaver, was killed by the Windows 10 Fall upgrade.
In recovery, I'm hooking up with Aptana.

So, I must uninstall and re-install WampStack,
download Aptana,
JDK,
Node.js,
Ruby,
and Git.

In your experience, is there a proper sequence by which I should download and install these components?

TIA

答:
Ok, here is the document I overlooked.
https://github.com/aptana/studio3/wiki/Getting-Started</p>


问:
Javafx 2 : How do I delete a row or column in Gridpane
If I want to add a row of text fields programatically in JavaFx, i can simply use the gridpane add method

This adds a set of text fields to row 1.

```<code>for (int i = 0; i < Fields.size(); i++) {
   gridpane.add(new TextField(), i, 1);
}
</code>```

Similarly, How do I delete a row?. I dont find a suitable method to delete a row/column conveeniently in JavaFX.

答:
In Java 8+, you can use removeIf:

```<code>gridPane.getChildren().removeIf(node -> GridPane.getRowIndex(node) == rowNumber);
</code>```

Caveat

If removing items from the 0th row, also check GridPane.getRowIndex(node) == null, i.e.,

```<code>node -> GridPane.getRowIndex(node) == null || GridPane.getRowIndex(node) == 0
</code>```

(I think this is JavaFX leaving the row number as null when no row number is given in the corresponding element in FXML, even though giving no row number in FXML means the element is in the 0th row, since the default row is the 0th row.)

Body:
If I want to add a row of text fields programatically in JavaFx, i can simply use the gridpane add method

This adds a set of text fields to row 1.

for (int i = 0; i < Fields.size(); i++) {
   gridpane.add(new TextField(), i, 1);
}

Similarly, How do I delete a row?. I dont find a suitable method to delete a row/column conveeniently in JavaFX.

Body:
In Java 8+, you can use removeIf:

gridPane.getChildren().removeIf(node -> GridPane.getRowIndex(node) == rowNumber);

Caveat

If removing items from the 0th row, also check GridPane.getRowIndex(node) == null, i.e.,

node -> GridPane.getRowIndex(node) == null || GridPane.getRowIndex(node) == 0

(I think this is JavaFX leaving the row number as null when no row number is given in the corresponding element in FXML, even though giving no row number in FXML means the element is in the 0th row, since the default row is the 0th row.)


问:
How to filter objects full of arrays based on the value of its property
I am trying to get a value from an array of objects based on the value of another property.

Sample array of objects:

```<code>objArray = [ { foo: 1, bar: 2}, { foo: 3, bar: 4}, { foo: 5, bar: 6} ];
</code>```

I am trying to get "1" based on filtering "2". I do not know the position of "bar: 2" and as the data is changing every day, the objArray may look like this next day:

```<code>objArray = [ { foo: 3, bar: 4}, { foo: 1, bar: 2}, { foo: 5, bar: 6} ];
</code>```

I thought about filtering:

but I am getting nowhere...

答:
Might be a bit easier to get the value(s) with JSON.parse :

j = '[ { "foo": 1, "bar": 2 }, { "foo": 3, "bar": 4 }, { "foo": 5, "bar": 6 } ]'

a = [], b = JSON.parse(j, function(key, v) { if (v.bar === 2) a.push(v.foo); return v; })

console.log( a ); console.log( b )```

Body:
I am trying to get a value from an array of objects based on the value of another property.

Sample array of objects:

objArray = [ { foo: 1, bar: 2}, { foo: 3, bar: 4}, { foo: 5, bar: 6} ];

I am trying to get "1" based on filtering "2". I do not know the position of "bar: 2" and as the data is changing every day, the objArray may look like this next day:

objArray = [ { foo: 3, bar: 4}, { foo: 1, bar: 2}, { foo: 5, bar: 6} ];

I thought about filtering:

but I am getting nowhere...


问:
Getting Process List on Oracle Solaris 11
i used to get a list of processs under linux by enumerating the /proc file system, since it had plain-text files that i can read data from (stat, status, exe link....) but thats not the case on solaris, i tried porting my tools to Oracle Solaris 11 (my first solaris) but it wont work, i tried accessing the /proc folder manually, but couldn't find anything readable, but ps -fu user works !

is it possible that someone can point me on how to get a list of processes uneder solaris?
im coding in gcc btw.

thanks.

答:
Unlike Linux, Solaris /proc is providing binary data, not text one.

Solaris has an extensive and detailed manual page proc(4) describing what the different files under a process number hierarchy contain, how to access them and what structures to use in order to get their content.

This manual page is of course also accessible locally with man -s 4 proc


问:
How to hide app name from title bar in Android?
My app is showing name and icon. I want to hide name.

How i can do that?

答:
You can use getSupportActionBar.
if you want to hide just your app name use this code in Activity of that page :

```<code>getSupportActionBar().setDisplayShowHomeEnabled(false);

</code>```

And if you want to hide ActionBar use this

```<code>getSupportActionBar().hide();
</code>```

And you can ReName your app with :

```<code>getSupportActionBar().setTitle("that name you want");
</code>```

Totaly you can use:

```<code>getSupportActionBar().
</code>```

and others code ...

Body:
You can use getSupportActionBar.
if you want to hide just your app name use this code in Activity of that page :

getSupportActionBar().setDisplayShowHomeEnabled(false);

And if you want to hide ActionBar use this

getSupportActionBar().hide();

And you can ReName your app with :

getSupportActionBar().setTitle("that name you want");

Totaly you can use:

getSupportActionBar().

and others code ...


问:
Using Firebase and Angular, how can I retrieve a key generated from another page?
I am creating a grocery list app that stores food ids inside a user's list. The name of this list is generated with a .push method that is fired once, when the user registers, and will always remain the same. I need to retrieve this value on other pages that edit the food attributes.

Here is my database structure:

```<code>"userlist" : {
  {
    "-L-i60DHuiX6jba6TZLt" : {
      "list" : {
        "-L-4FJ9EaFjtDT_7XO6c" : {
          "category" : "Beverages",
          "foodname" : "7Up",
          "state" : "on"
        },
        "-L-i4dIBkloIxZPtY3Ge" : {
          "category" : "bread",
          "foodname" : "toast",
          "state" : "on"
        }
      }
    }
  }
}
</code>```

How can I retrieve the value of the first value shown, "-L-i60DHuiX6jba6TZLt"?

答:
The push() method doesn't return the generated key, even though it's generated locally.

So in this scenario you should generate your own key which you can persist in your app, instead of using push().

```<code>// Generate new key (client side)
let newKey = ref.push().key();
</code>```

Then instead of pushing to a list, you can just call set() or update() on a specific object ref (that doesn't exist yet).

```<code>ref(`/userlist/${newKey}`).set({ category: 'bread' });
</code>```

Body:
I am creating a grocery list app that stores food ids inside a user's list. The name of this list is generated with a .push method that is fired once, when the user registers, and will always remain the same. I need to retrieve this value on other pages that edit the food attributes.

Here is my database structure:

"userlist" : {
  {
    "-L-i60DHuiX6jba6TZLt" : {
      "list" : {
        "-L-4FJ9EaFjtDT_7XO6c" : {
          "category" : "Beverages",
          "foodname" : "7Up",
          "state" : "on"
        },
        "-L-i4dIBkloIxZPtY3Ge" : {
          "category" : "bread",
          "foodname" : "toast",
          "state" : "on"
        }
      }
    }
  }
}

How can I retrieve the value of the first value shown, "-L-i60DHuiX6jba6TZLt"?

Body:
The push() method doesn't return the generated key, even though it's generated locally.

So in this scenario you should generate your own key which you can persist in your app, instead of using push().

// Generate new key (client side)
let newKey = ref.push().key();

Then instead of pushing to a list, you can just call set() or update() on a specific object ref (that doesn't exist yet).

ref(`/userlist/${newKey}`).set({ category: 'bread' });


问:
Merge two columns in Select into one column based on a condition
I have a SELECT with two columns I'd like to merge based on the condition that if the left one is null it should choose the right column but when the left column is not null it should always choose the left.

scenario

What I have on the left is what I currently Have and I'd like to get the table on the right

AlphabetTable

```<code>+-------+------+    +---------+
| A     | B    |    | Desired |
+-------+------+    |---------+
| null  | 1    |    | 1       |
| null  | 1    |    | 1       |
|  2    | null |    | 2       |
|  2    | 3    |    | 2       |
|  2    | 5    |    |  2      |
|  null | null |    | null    |
+-------+------+    +---------+
</code>```

SQL for left table above

```<code>SELECT
    CAST((select sum(Total) from LettersTable LT
                                WHERE LT.ID = ID
                                AND LT.Count > 5)
                                AS INT) as A
    CAST((select sum(Total) from LettersTable LT
                                WHERE LT.ID = ID
                                AND LT.Count > 5)
                                AS INT) as B
From IDTable
</code>```

Heres what I have so far

```<code>SELECT
        CASE WHEN
            CAST((select sum(Total) from LettersTable LT
                        WHERE LT.ID = AT.ID
                        AND LT.Count > 5)
                        AS INT) IS NULL
            THEN
                (select sum(Total) from LettersTable LT
                        WHERE LT.ID = AT.ID
                        AND LT.Count > 5)
                        AS INT)
            ELSE
                (select sum(Total) from LettersTable LT
                        WHERE LT.ID = AT.ID
                        AND LT.Count > 5)
                        AS INT)
 FROM AlphabetTable AT
</code>```

答:
try this </p>

```<code>;with mycte as (
select null as a, 1 as b
union all
select null as a, 1 as b
union all
select 2 as a, null as b
union all
select 2 as a, 3 as b
union all
select 2 as a, 5 as b
union all
select null as a, null as b

)
SELECT ISNULL(a,b) FROM mycte
</code>```

Body:
I have a SELECT with two columns I'd like to merge based on the condition that if the left one is null it should choose the right column but when the left column is not null it should always choose the left.

scenario

What I have on the left is what I currently Have and I'd like to get the table on the right

AlphabetTable

+-------+------+    +---------+
| A     | B    |    | Desired |
+-------+------+    |---------+
| null  | 1    |    | 1       |
| null  | 1    |    | 1       |
|  2    | null |    | 2       |
|  2    | 3    |    | 2       |
|  2    | 5    |    |  2      |
|  null | null |    | null    |
+-------+------+    +---------+

SQL for left table above

SELECT
    CAST((select sum(Total) from LettersTable LT
                                WHERE LT.ID = ID
                                AND LT.Count > 5)
                                AS INT) as A
    CAST((select sum(Total) from LettersTable LT
                                WHERE LT.ID = ID
                                AND LT.Count > 5)
                                AS INT) as B
From IDTable

Heres what I have so far

SELECT
        CASE WHEN
            CAST((select sum(Total) from LettersTable LT
                        WHERE LT.ID = AT.ID
                        AND LT.Count > 5)
                        AS INT) IS NULL
            THEN
                (select sum(Total) from LettersTable LT
                        WHERE LT.ID = AT.ID
                        AND LT.Count > 5)
                        AS INT)
            ELSE
                (select sum(Total) from LettersTable LT
                        WHERE LT.ID = AT.ID
                        AND LT.Count > 5)
                        AS INT)
 FROM AlphabetTable AT

Body:
try this

;with mycte as (
select null as a, 1 as b
union all
select null as a, 1 as b
union all
select 2 as a, null as b
union all
select 2 as a, 3 as b
union all
select 2 as a, 5 as b
union all
select null as a, null as b

)
SELECT ISNULL(a,b) FROM mycte


问:
Spring cloud stream MessageChannel send() always return true
I'm using Spring cloud stream and I'd like to save messages and retry to publish them on the topic when the Kafka server is gone but MessageChannel send() method always return true even if the Kafka/Zookeeper server is stopped.

Can somebody help ?

UPDATE with application.yml content :

```<code>spring:
    cloud:
        stream:
            kafka:
                binder:
                    brokers: localhost
                    zk-nodes: localhost
                    mode: raw
                bindings:
                    output:
                        producer:
                            sync: true
            bindings:
                output:
                    destination: topic-notification
                    content-type: application/json
</code>```

CODE :

```<code>@Service
public class SendToKafka {
    private Logger log = LoggerFactory.getLogger(SendToKafka.class);

    @Autowired
    Source source;

    @Autowired
    NotificationFileService notificationFileService;

    public void send(NotificationToResendDTO notification){
        try {
            CompletableFuture.supplyAsync(() -> notification)
                .thenAcceptAsync(notif -> {
                    boolean resp = source.output().send(MessageBuilder.withPayload(notif).build());
                    log.info(" ======== kafka server response === " + resp);

                    if (!resp){
                        log.info(" ======== failed to send the notification" + notification);
                        // save failed notification
                        notificationFileService.writeTofile(notification);
                    }
                }).get();
        } catch (InterruptedException | ExecutionException e) {
            log.info(" ======== failed to send the notification with exception" + notification);
            // save failed notification
            notificationFileService.writeTofile(notification);
            e.printStackTrace();
        }
    }
}
</code>```

答:
Kafka is async by default; you need to set sync to true; see the binder producer properties.

sync

Whether the producer is synchronous.

Default: false.

Body:
I'm using Spring cloud stream and I'd like to save messages and retry to publish them on the topic when the Kafka server is gone but MessageChannel send() method always return true even if the Kafka/Zookeeper server is stopped.

Can somebody help ?

UPDATE with application.yml content :

spring:
    cloud:
        stream:
            kafka:
                binder:
                    brokers: localhost
                    zk-nodes: localhost
                    mode: raw
                bindings:
                    output:
                        producer:
                            sync: true
            bindings:
                output:
                    destination: topic-notification
                    content-type: application/json

CODE :

@Service
public class SendToKafka {
    private Logger log = LoggerFactory.getLogger(SendToKafka.class);

    @Autowired
    Source source;

    @Autowired
    NotificationFileService notificationFileService;

    public void send(NotificationToResendDTO notification){
        try {
            CompletableFuture.supplyAsync(() -> notification)
                .thenAcceptAsync(notif -> {
                    boolean resp = source.output().send(MessageBuilder.withPayload(notif).build());
                    log.info(" ======== kafka server response === " + resp);

                    if (!resp){
                        log.info(" ======== failed to send the notification" + notification);
                        // save failed notification
                        notificationFileService.writeTofile(notification);
                    }
                }).get();
        } catch (InterruptedException | ExecutionException e) {
            log.info(" ======== failed to send the notification with exception" + notification);
            // save failed notification
            notificationFileService.writeTofile(notification);
            e.printStackTrace();
        }
    }
}


问:
Protect Direct Line Secret in Botframework for Web Client
I have my bot ready and working with Direct Line Secret in WebChat (by passing &s=SECRET in URL) and on other channels.

I am interested in the integration of front-end Custom Chat Application using Direct Line ClientJS (link at bottom).

After going through the documentation on Bot Framework I came to know that it can be done in 2 ways:

Pass Direct Line secret from front-end Chat Application in ClientJS

Passing Token from front-end Chat Application (But, this requires Direct Line Secret to be passed to generate token first time)

As I develop bots for my clients with their respective use-cases which
need to be kept private with client servers.

So, anybody having Direct Line Secret can easily obtain Bots Logic (i.e Not actual code, but what answer bot replies to particular question) by just passing that Direct Line secret in Microsoft Bot Framework provided WebChat client (by passing s=SECRET in URL)

So, basically, how do I hide the secret from others?

Direct Line Client : https://github.com/Microsoft/BotBuilder-Samples/tree/master/Node/core-DirectLine

Authentication Mechanism : https://learn.microsoft.com/en-us/bot-framework/rest-api/bot-framework-rest-direct-line-3-0-authentication

Programming Languages:

FrontEnd - Angular.js with Typescript

Backend - Node.js on Heroku

答:
You need to follow method #2 as described in the section Generate a Direct Line Token. Then you won't have to use the secret in your WebChat page at all.

A Direct Line token is a key that can be used to access a single conversation. A token expires but can be refreshed.

This way your client will use the generated token on a per-conversation basis, and there's no need to embed the secret in the WebChat page. Also when you are using the token it will expire, so you have additional security there as well.


问:
Yellowbrick: Increasing font size on Yellowbrick generated charts
Is there a way to increase the font size on Yellowbrick generated charts? I find it difficult to read the text. I wasn't able to find anything on it in the documentation.

I'm using Python 3.6, Yellowbrick 0.5 in a Jupyter Notebook.

答:
Update: The yellowbrick API now uses viz.show instead of viz.poof.

Yellowbrick wraps matplotlib in order to produce visualizations, so you can influence all the visual settings for the figure by making calls directly to matplotlib. I find that the easiest way to do that is by getting access to the Visualizer.ax property and setting things directly there, though of course, you can use plt directly to manage the global figure.

Here's some code that produces an example similar to yours:

```<code>import pandas as pd

from yellowbrick.classifier import ConfusionMatrix
from sklearn.ensemble import AdaBoostClassifier
from sklearn.model_selection import train_test_split as tts

data = pd.read_csv('examples/data/occupancy/occupancy.csv')

features = ["temperature", "relative humidity", "light", "C02", "humidity"]

# Extract the numpy arrays from the data frame
X = data[features].as_matrix()
y = data.occupancy.as_matrix()

X_train, X_test, y_train, y_test = tts(X, y, test_size=0.2)

clf = AdaBoostClassifier()
viz = ConfusionMatrix(clf)

viz.fit(X_train, y_train)
viz.score(X_test, y_test)
viz.show()
</code>```

This results in the following image being generated:

You can start to manage the figure right after score and before show as follows:

```<code>viz.fit(X_train, y_train)
viz.score(X_test, y_test)

for label in viz.ax.texts:
    label.set_size(12)

viz.show()
</code>```

This produces the following image, with slightly larger fonts on the inside:

What's happening here is that I'm directly accessing the matplotlib Axes object on the visualizer that contains all the elements of the drawing. The labels in the middle of the grid are Text objects, so I loop through all the text objects setting their size to 12pt. This technique can be used to modify any visual element before display if required (typically I use it to put annotations on the visualization).

Note, however, that show calls a finalize function, so some things like the title, axis labels, etc. should be modified after calling show, or by short-circuiting show by calling finalize then plt.show().

This particular code only works with the ConfusionMatrix, but I've added an issue in the Yellowbrick library to hopefully make this easier or at least more readable in the future.

Body:
Update: The yellowbrick API now uses viz.show instead of viz.poof.

Yellowbrick wraps matplotlib in order to produce visualizations, so you can influence all the visual settings for the figure by making calls directly to matplotlib. I find that the easiest way to do that is by getting access to the Visualizer.ax property and setting things directly there, though of course, you can use plt directly to manage the global figure.

Here's some code that produces an example similar to yours:

import pandas as pd

from yellowbrick.classifier import ConfusionMatrix
from sklearn.ensemble import AdaBoostClassifier
from sklearn.model_selection import train_test_split as tts

data = pd.read_csv('examples/data/occupancy/occupancy.csv')

features = ["temperature", "relative humidity", "light", "C02", "humidity"]

# Extract the numpy arrays from the data frame
X = data[features].as_matrix()
y = data.occupancy.as_matrix()

X_train, X_test, y_train, y_test = tts(X, y, test_size=0.2)

clf = AdaBoostClassifier()
viz = ConfusionMatrix(clf)

viz.fit(X_train, y_train)
viz.score(X_test, y_test)
viz.show()

This results in the following image being generated:

You can start to manage the figure right after score and before show as follows:

viz.fit(X_train, y_train)
viz.score(X_test, y_test)

for label in viz.ax.texts:
    label.set_size(12)

viz.show()

This produces the following image, with slightly larger fonts on the inside:

What's happening here is that I'm directly accessing the matplotlib Axes object on the visualizer that contains all the elements of the drawing. The labels in the middle of the grid are Text objects, so I loop through all the text objects setting their size to 12pt. This technique can be used to modify any visual element before display if required (typically I use it to put annotations on the visualization).

Note, however, that show calls a finalize function, so some things like the title, axis labels, etc. should be modified after calling show, or by short-circuiting show by calling finalize then plt.show().

This particular code only works with the ConfusionMatrix, but I've added an issue in the Yellowbrick library to hopefully make this easier or at least more readable in the future.


问:
How to develop compiler without compiler writing tools
My teacher gave this question ( how to develop compilers without compiler writing tools ). I searched for it but I did not find anything. So, If anyone have any idea about this please help me. I found so many information about developing compiler with writing tools but I found nothing when I searched for without compiler writing tools.

Thank you in advance.

答:
With:

Hand-written scanner (large switch statement), and

Recursive descent parser.


问:
Overflow-x value ignored in mobile safari
We set the overflow-x values to hidden on both the body and scrollable elements, but mobile Safari ignores these values. On the desktop, the overflow values work fine.

Relevant code:

```<code>body { overflow-x:hidden; width:320px; height:100%; min-height:100%; margin:0; background:-webkit-linear-gradient(top,#e8e4dc,#f2f0eb); }

.page_list, .content { max-height:370px; box-sizing:border-box; padding:0; overflow-x:hidden; overflow-y:auto; -webkit-overflow-scrolling:touch }

#catalog_page { border-left:1px solid #CCC; z-index:28; position:absolute; top:0; width:200px; height:460px; background:white; -webkit-transition:-webkit-transform 0.1s ease-in;; -webkit-transform:translate3d(0,0,0); display:none; }
</code>```

catalog_page is what sits outside the viewport, sliding into view only after someone does a gesture.

To reproduce:

1) Visit www.tekiki.com on your iPhone (not iPad). Scroll to the right, and you'll see how catalog_page extends the site's width, even though we fixed the body width.

答: If html, body overflow-x: hidden; is not working for you try looking for text-indent. The default settings of flexslider for example have some elements set to text-indent -9999px. I found this was overriding html overflow rules.

Body:
We set the overflow-x values to hidden on both the body and scrollable elements, but mobile Safari ignores these values. On the desktop, the overflow values work fine.

Relevant code:

body { overflow-x:hidden; width:320px; height:100%; min-height:100%; margin:0; background:-webkit-linear-gradient(top,#e8e4dc,#f2f0eb); }

.page_list, .content { max-height:370px; box-sizing:border-box; padding:0; overflow-x:hidden; overflow-y:auto; -webkit-overflow-scrolling:touch }

#catalog_page { border-left:1px solid #CCC; z-index:28; position:absolute; top:0; width:200px; height:460px; background:white; -webkit-transition:-webkit-transform 0.1s ease-in;; -webkit-transform:translate3d(0,0,0); display:none; }

catalog_page is what sits outside the viewport, sliding into view only after someone does a gesture.

To reproduce:

1) Visit www.tekiki.com on your iPhone (not iPad). Scroll to the right, and you'll see how catalog_page extends the site's width, even though we fixed the body width.


问:
Show alternate for ad blockers
I was recently testing the Amazon MP3 Widget on my site.  It was not appearing and I realized it was being blocked by my ad blocker plug-in that prevents cross site flash objects.  I want to know if there is a way to tell people that they are missing this content.  It seems like the ad blocker simply removes any embed code.  What can I do to tell people they might be missing something they actually want to see.  I'm hoping there's something similar to the no script tag, but I'm assuming its more than that.   </p>

答:
Proxy the iframe source URL through your server with a redirect.

Edit: You can use alternative content (check out this article) to provide either:

a link which issues an ajax request to get the embed/object code; this might bypass the blocker since it the page was already open;

a piece of text or an image alerting the user to turn off the ad blocker, since he's missing content.

Title: Show alternate for ad blockers


问:
Calculate value using proportion
I'm designing a machine that requires an automated ignition system. This project uses a motor control script that I wrote for Arduino.

I need to calculate the delay between ignition based on the percentage motor load.

These are the variables currently used

```<code>//Variables
int potentiometerIn; //RAW Potentiometer data variable
int potentiometerIn2; //Used in percent calculation, Will be == to potentiometerIn, just a different operation order
int potentiometerDivper; //Variable to hold percentage calculation (first step)
int potentiometerPer; // Holds the integer percent for motor speed IE: motor at 83% speed would have this value at 83
int potentiometerDiv;
int motorPin = (); //REPLACE () with PIN NUM
int motorRly = (); //Motor Positive pin () = pin num + Motor Pin
int motorNeg = (); //Motor Negative Pin () = pin num (Likely Not Needed)
int igniteRly = (); //Ignition Control Positive Pin
int igniteNeg = (); //Ignition Control Negative Pin (Likely Not Needed)
int ignitionTime = 0; // This will be used to set the time for an electric ignition.
int ignitionCalc = (); //This should be the time in seconds, that it takes for the machine to complete a full cycle with the motor set to 50%

// This enables/disables the ignition portion

int ignitionEnabled = true; // Default = True

 if (ignitionEnabled == true)
  {
    ignitionCalc * 1000; //Converts the seconds to a format accepted by delay
    50 / ignitionCalc = potentiometerPer / ignitionTime;
  }
</code>```

A quick summary for those who don't want to read all of my comments (I'm writing this code before the motor arrives so the values are all unset)

potentiometerPer > This is the percentage of power being supplied to the motor.

ignitionTime > This value will be used to set the delay between ignition firing

ignitionCalc > The amount of time in seconds for 1 cycle at 50% power.

I'm trying to figure out a way to calculate the delay for ignition with regards to what percentage the motor is currently set to. For example:

If motor percentage is 80 and the time per cycle is 5, then at 100% power the time per cycle is X (in this case 6.25)

I can't seem to figure out how to do proportions in C++, I'm rather new to the language and only started to learn it for this project.

答:
Well since when the motor power is at 80%, the time per cycle you get is 5. So ignore the percentage, lets just say that when power level is 80, you get time per cycle as 5. Ratios in simpler words are just divisions. When 80 is divided by 16, you get 5. So what we know is the value 16 is going to remain constant. Similarly if you take any value of motor power, and divide by 16, you are going to get what you want. If this ratio is going to remain constant then it will be for all cases no matter what the motor power is.  Im assuming that the ratio is going to remain constant.

So what you can do is -

```<code>float timePerCycle = potentiometerPer/16;
</code>```

Title: Calculate value using proportion

Body:
I'm designing a machine that requires an automated ignition system. This project uses a motor control script that I wrote for Arduino.

I need to calculate the delay between ignition based on the percentage motor load.

These are the variables currently used

//Variables
int potentiometerIn; //RAW Potentiometer data variable
int potentiometerIn2; //Used in percent calculation, Will be == to potentiometerIn, just a different operation order
int potentiometerDivper; //Variable to hold percentage calculation (first step)
int potentiometerPer; // Holds the integer percent for motor speed IE: motor at 83% speed would have this value at 83
int potentiometerDiv;
int motorPin = (); //REPLACE () with PIN NUM
int motorRly = (); //Motor Positive pin () = pin num + Motor Pin
int motorNeg = (); //Motor Negative Pin () = pin num (Likely Not Needed)
int igniteRly = (); //Ignition Control Positive Pin
int igniteNeg = (); //Ignition Control Negative Pin (Likely Not Needed)
int ignitionTime = 0; // This will be used to set the time for an electric ignition.
int ignitionCalc = (); //This should be the time in seconds, that it takes for the machine to complete a full cycle with the motor set to 50%

// This enables/disables the ignition portion

int ignitionEnabled = true; // Default = True

 if (ignitionEnabled == true)
  {
    ignitionCalc * 1000; //Converts the seconds to a format accepted by delay
    50 / ignitionCalc = potentiometerPer / ignitionTime;
  }

A quick summary for those who don't want to read all of my comments (I'm writing this code before the motor arrives so the values are all unset)

potentiometerPer > This is the percentage of power being supplied to the motor.

ignitionTime > This value will be used to set the delay between ignition firing

ignitionCalc > The amount of time in seconds for 1 cycle at 50% power.

I'm trying to figure out a way to calculate the delay for ignition with regards to what percentage the motor is currently set to. For example:

If motor percentage is 80 and the time per cycle is 5, then at 100% power the time per cycle is X (in this case 6.25)

I can't seem to figure out how to do proportions in C++, I'm rather new to the language and only started to learn it for this project.

Body:
Well since when the motor power is at 80%, the time per cycle you get is 5. So ignore the percentage, lets just say that when power level is 80, you get time per cycle as 5. Ratios in simpler words are just divisions. When 80 is divided by 16, you get 5. So what we know is the value 16 is going to remain constant. Similarly if you take any value of motor power, and divide by 16, you are going to get what you want. If this ratio is going to remain constant then it will be for all cases no matter what the motor power is.  Im assuming that the ratio is going to remain constant.

So what you can do is -

float timePerCycle = potentiometerPer/16;