问:
How to select specific observations from columns based on partial string match of column names
My dataset a large number of columns starting with "dis....".

The values in the columns are either 0 (without disease) or 1 (with disease). I would like create a dataframe of observations with 1 for a specific disease and 0 for everything else.

I have tried the following:

```<code>istroke <- filter(onlyCRP, dis_ep0009 == 1 & grep("dis_" == 0))
</code>```

and in combination with select:

```<code>istroke1 <- filter(onlyCRP, dis_ep0009 == 1 & select(contains("dis_") == 0))
</code>```

As you'd guess, neither of them work.

I have looked at these posts:

filtering columns by regex in dataframe

Subset data based on partial match of column names

But they don't answer my question.

Please let me know if you require further clarifications.

Edit
I realized I needed to clarify further what I wanted. Consider this table:

```<code>dis_ep0009  dis_epxxx   dis_epxxx
 0            0             0
 0            1             0
 0            0             1
 1            0             1
 0            0             0
 0            0             0
 1            1             1
</code>```

I need another column, e.g - IS according to some conditions of these 3 columns (I actually have 29 of these "dis_" columns):

If dis_ep0009 == 1, then IS == 1 (regardless of 0 or 1 on any other "dis.." columns).

if dis_ep0009 == 0 and dis_epxxx == 1, I want to drop these observations

if dis_ep0009 == 0 and dis_epxxx == 0, I want to code IS == 0.

So the resulting table should look like this:

```<code>dis_ep0009  dis_epxxx   dis_epxxx    IS
 0            0             0        0
 0            1             0        drop
 0            0             1        drop
 1            0             1        1
 0            0             0        0
 0            0             0        0
 1            1             1        1
</code>```

I have tried pairing filter (dplyr) with grep and ifelse statements but can't make head or tails of it. In essence, it should be something simple like this (not meant to work):

```<code>istroke <- filter(df, ifelse(dis_ep0009 == 1, 1, ifelse(dis_ep0009 == 0 & grep("dis_", names(df)) == 0, 0, ifelse(dis_ep0009 == 0 & grep("dis_", names(df)) == 1, drop())))
</code>```

Thanks in advance!

答:
See comments in code, and tell me if that's what you want</p>

```<code>specific_disease <- "dis_ep0009"
disease_cols <- grep("dis",names(onlyCRP),value=TRUE) # all columns containing "dis"
disease_cols <- setdiff(disease_cols,specific_disease) # all these columns except your specific disease
onlyCRP$any_other_disease <- apply(onlyCRP[,disease_cols]==1,1,any) # a Boolean column saying if there is another disease besides the possible specific one
onlyCRP[onlyCRP$specific_disease == 1 & !onlyCRP$any_other_disease,] # the subset where you'll have only your specific disease and no other
</code>```

Body:
My dataset a large number of columns starting with "dis....".

The values in the columns are either 0 (without disease) or 1 (with disease). I would like create a dataframe of observations with 1 for a specific disease and 0 for everything else.

I have tried the following:

istroke <- filter(onlyCRP, dis_ep0009 == 1 & grep("dis_" == 0))

and in combination with select:

istroke1 <- filter(onlyCRP, dis_ep0009 == 1 & select(contains("dis_") == 0))

As you'd guess, neither of them work.

I have looked at these posts:

filtering columns by regex in dataframe

Subset data based on partial match of column names

But they don't answer my question.

Please let me know if you require further clarifications.

Edit
I realized I needed to clarify further what I wanted. Consider this table:

dis_ep0009  dis_epxxx   dis_epxxx
 0            0             0
 0            1             0
 0            0             1
 1            0             1
 0            0             0
 0            0             0
 1            1             1

I need another column, e.g - IS according to some conditions of these 3 columns (I actually have 29 of these "dis_" columns):

If dis_ep0009 == 1, then IS == 1 (regardless of 0 or 1 on any other "dis.." columns).

if dis_ep0009 == 0 and dis_epxxx == 1, I want to drop these observations

if dis_ep0009 == 0 and dis_epxxx == 0, I want to code IS == 0.

So the resulting table should look like this:

dis_ep0009  dis_epxxx   dis_epxxx    IS
 0            0             0        0
 0            1             0        drop
 0            0             1        drop
 1            0             1        1
 0            0             0        0
 0            0             0        0
 1            1             1        1

I have tried pairing filter (dplyr) with grep and ifelse statements but can't make head or tails of it. In essence, it should be something simple like this (not meant to work):

istroke <- filter(df, ifelse(dis_ep0009 == 1, 1, ifelse(dis_ep0009 == 0 & grep("dis_", names(df)) == 0, 0, ifelse(dis_ep0009 == 0 & grep("dis_", names(df)) == 1, drop())))

Thanks in advance!

Body:
See comments in code, and tell me if that's what you want

specific_disease <- "dis_ep0009"
disease_cols <- grep("dis",names(onlyCRP),value=TRUE) # all columns containing "dis"
disease_cols <- setdiff(disease_cols,specific_disease) # all these columns except your specific disease
onlyCRP$any_other_disease <- apply(onlyCRP[,disease_cols]==1,1,any) # a Boolean column saying if there is another disease besides the possible specific one
onlyCRP[onlyCRP$specific_disease == 1 & !onlyCRP$any_other_disease,] # the subset where you'll have only your specific disease and no other


来源: stackexchange

问:
Querying an SQL file into CSV
I have a SQL file with the following info:

```<code>CREATE TABLE 'people' (
'id' int(11) UNSIGNED NOT NULL,
'email' varchar(255) DEFAULT NULL,
'name' varchar(255) DEFAULT
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO 'people' ('id', 'email', 'name') VALUES
(1, 'a@gmail.com', 'john doe'),
(2, 'b@gmail.com', 'jane doe'),
...
(1000, 'x@gmail.com', 'big cat');
</code>```

How can I query this people.sql file with a list of emails (one per line) in a text file and write the email and name pairings to a new csv?

答:
Assume that you have execute file above and put data into mySQL DB.

You can use the select command to write to csv file.

```<code>SELECT email, name FROM people INTO OUTFILE 'yourfile.csv' FIELDS
TERMINATED BY ','
</code>```

In you updated comment, you simply want to do mapping from people name from text file to SQL command to perform query. If you break down the question, it will become two tasks. First is to select name from the given list, which can be done by:

```<code>SELECT email, name FROM people WHERE name IN ('john', 'alice', 'bob') INTO
OUTFILE 'yourfile.csv' FIELDS TERMINATED BY ','
</code>```

Above will produce a mapping according to the given list. But your second need is to get that list from text file. One way to do so is to transform a "one-name-per-line" to a "list-of-name-with-comma" using sed and tr utilities.

```<code>cat your-name-list.txt | sed -e "s/\([a-zA-Z0-9\=\.\-]*\)/'\1'/g" | tr "\n" ","
</code>```

I don't know what is your environment. but basically, you want to use the result from this as a query condition in SQL above. Hope this give you enough idea.

ContentLicense: CC BY-SA 3.0

Title: Querying an SQL file into CSV

Body:
I have a SQL file with the following info:

CREATE TABLE 'people' (
'id' int(11) UNSIGNED NOT NULL,
'email' varchar(255) DEFAULT NULL,
'name' varchar(255) DEFAULT
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO 'people' ('id', 'email', 'name') VALUES
(1, 'a@gmail.com', 'john doe'),
(2, 'b@gmail.com', 'jane doe'),
...
(1000, 'x@gmail.com', 'big cat');

How can I query this people.sql file with a list of emails (one per line) in a text file and write the email and name pairings to a new csv?

Body:
Assume that you have execute file above and put data into mySQL DB.

You can use the select command to write to csv file.

SELECT email, name FROM people INTO OUTFILE 'yourfile.csv' FIELDS
TERMINATED BY ','

In you updated comment, you simply want to do mapping from people name from text file to SQL command to perform query. If you break down the question, it will become two tasks. First is to select name from the given list, which can be done by:

SELECT email, name FROM people WHERE name IN ('john', 'alice', 'bob') INTO
OUTFILE 'yourfile.csv' FIELDS TERMINATED BY ','

Above will produce a mapping according to the given list. But your second need is to get that list from text file. One way to do so is to transform a "one-name-per-line" to a "list-of-name-with-comma" using sed and tr utilities.

cat your-name-list.txt | sed -e "s/\([a-zA-Z0-9\=\.\-]*\)/'\1'/g" | tr "\n" ","

I don't know what is your environment. but basically, you want to use the result from this as a query condition in SQL above. Hope this give you enough idea.


问:
Strange padding on the bottom after hide and show the fragment using the transparent status bar in DrawerLayout
I used the way https://stackoverflow.com/a/27051852/3875363 to achieve the drawer behind the status bar, it seems fine before only stay for one view.

But I faced a strange case after I hide and show this fragment, a white padding appears on the bottom of the drawerlayout, it likes below.

I comment most codes to show a simple example.

The layout of activity:

```<code><?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/content_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

</FrameLayout>
</code>```

The layout of fragment with drawer

```<code><android.support.v4.widget.DrawerLayout android:id="@+id/drawer_layout"
                                        xmlns:android="http://schemas.android.com/apk/res/android"
                                        xmlns:tools="http://schemas.android.com/tools"
                                        android:layout_width="match_parent"
                                        android:layout_height="match_parent"
                                        android:fitsSystemWindows="true"
                                        tools:context=".MainActivity">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <include
            android:id="@+id/action_bar_in_list"
            layout = "@layout/toolbar"/>

    </RelativeLayout>

    <com.ghostflying.portalwaitinglist.ScrimInsetsFrameLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/debug_content"
        android:background="@color/setting_item_group_title_text"
        app:insetForeground="#4000"
        android:fitsSystemWindows="true"
        android:layout_gravity="start"
        android:layout_height="match_parent"
        android:layout_width="@dimen/navigation_drawer_width">

    </com.ghostflying.portalwaitinglist.ScrimInsetsFrameLayout>
</android.support.v4.widget.DrawerLayout>
</code>```

The layout of the second fragment:

```<code><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
             xmlns:tools="http://schemas.android.com/tools"
             android:layout_width="match_parent"
             android:layout_height="match_parent">

    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="@string/hello_blank_fragment"/>

</FrameLayout>
</code>```

Once I hide the drawer fragment, show the second fragment, then I popup the back stack to return. The drawer fragment will seem like the image, a padding with the height of status bar always appear. So strange.

答:
Try to remove the android attribute:

```<code>fitsSystemWindows = "true"
</code>```

This worked for me.

According to the official documentation it's a

Boolean internal attribute to adjust view layout based on system
  windows such as the status bar. If true, adjusts the padding of this
  view to leave space for the system windows.

Body:
I used the way https://stackoverflow.com/a/27051852/3875363 to achieve the drawer behind the status bar, it seems fine before only stay for one view.

But I faced a strange case after I hide and show this fragment, a white padding appears on the bottom of the drawerlayout, it likes below.

I comment most codes to show a simple example.

The layout of activity:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/content_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

</FrameLayout>

The layout of fragment with drawer

<android.support.v4.widget.DrawerLayout android:id="@+id/drawer_layout"
                                        xmlns:android="http://schemas.android.com/apk/res/android"
                                        xmlns:tools="http://schemas.android.com/tools"
                                        android:layout_width="match_parent"
                                        android:layout_height="match_parent"
                                        android:fitsSystemWindows="true"
                                        tools:context=".MainActivity">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <include
            android:id="@+id/action_bar_in_list"
            layout = "@layout/toolbar"/>

    </RelativeLayout>

    <com.ghostflying.portalwaitinglist.ScrimInsetsFrameLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/debug_content"
        android:background="@color/setting_item_group_title_text"
        app:insetForeground="#4000"
        android:fitsSystemWindows="true"
        android:layout_gravity="start"
        android:layout_height="match_parent"
        android:layout_width="@dimen/navigation_drawer_width">

    </com.ghostflying.portalwaitinglist.ScrimInsetsFrameLayout>
</android.support.v4.widget.DrawerLayout>

The layout of the second fragment:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
             xmlns:tools="http://schemas.android.com/tools"
             android:layout_width="match_parent"
             android:layout_height="match_parent">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="@string/hello_blank_fragment"/>

</FrameLayout>

Once I hide the drawer fragment, show the second fragment, then I popup the back stack to return. The drawer fragment will seem like the image, a padding with the height of status bar always appear. So strange.

Body:
Try to remove the android attribute:

fitsSystemWindows = "true"

This worked for me.

According to the official documentation it's a

Boolean internal attribute to adjust view layout based on system
  windows such as the status bar. If true, adjusts the padding of this
  view to leave space for the system windows.


问:
How to filter reserved words in parser combinators?
I am using Scala's Parser Combinator framework, extending the RegexParsers class. I have an identifier token which starts with a letter and can contain alphabet characters, dashes, underscores and digits, as long as it is not one of the reserved words. I tried to use the parser's not() to function to stop reserved words from being used, however it is also matching identifiers which are prefixed with a reserved word.

```<code>def reserved = "and" | "or"

def identifier: Parser[String] = not(reserved) ~> """[a-zA-Z][\.a-zA-Z0-9_-]*""".r
</code>```

However, when I tried to parse an identifier like and-today I get an error saying Expected Failure.

How do I only filter reserved words if they are a full match of the token and not just a prefix?

Also is there a way to improve the error reporting in this case when using not()? In other cases I get the regular expression that the parser is expecting, but in this case it just says Failure without any details.

答:
You can use filterWithError both to filter out the reserved words and to customize the error message like this:

```<code>    val reservedWords = HashSet("and", "or")

    val idRegex= """[a-zA-Z][\.a-zA-Z0-9_-]*""".r

    val identifier = Parser(input =>
      idRegex(input).filterWithError(
        !reservedWords.contains(_),
        reservedWord => s"YOUR ERROR MESSAGE FOR $reservedWord",
        input
      )
    )
</code>```

Body:
I am using Scala's Parser Combinator framework, extending the RegexParsers class. I have an identifier token which starts with a letter and can contain alphabet characters, dashes, underscores and digits, as long as it is not one of the reserved words. I tried to use the parser's not() to function to stop reserved words from being used, however it is also matching identifiers which are prefixed with a reserved word.

def reserved = "and" | "or"

def identifier: Parser[String] = not(reserved) ~> """[a-zA-Z][\.a-zA-Z0-9_-]*""".r

However, when I tried to parse an identifier like and-today I get an error saying Expected Failure.

How do I only filter reserved words if they are a full match of the token and not just a prefix?

Also is there a way to improve the error reporting in this case when using not()? In other cases I get the regular expression that the parser is expecting, but in this case it just says Failure without any details.

Body:
You can use filterWithError both to filter out the reserved words and to customize the error message like this:

    val reservedWords = HashSet("and", "or")

    val idRegex= """[a-zA-Z][\.a-zA-Z0-9_-]*""".r

    val identifier = Parser(input =>
      idRegex(input).filterWithError(
        !reservedWords.contains(_),
        reservedWord => s"YOUR ERROR MESSAGE FOR $reservedWord",
        input
      )
    )


问:
Java util logger: custom formatter only works for some levels
I have made a custom formatter for the java.util logger, implemented as below

```<code>logger = Logger.getAnonymousLogger();
logger.setUseParentHandlers(false);
sb = new StringBuffer();
try {
  Handler handler = new FileHandler("xx.log");
  handler.setFormatter(new CustomFormatter());
  logger.addHandler(handler);
} catch (IOException e) {
  e.printStackTrace();
}

 private class CustomFormatter extends Formatter {
    @Override
    public String format(LogRecord record) {
      String msg = record.getMessage();
      sb.append(msg);
      System.out.print(sb.toString());
      return sb.toString();
    }
  }
</code>```

Running the following code:

```<code>logger.finest(msg);
logger.finer(msg);
logger.fine(msg);
logger.config(msg);
logger.info(msg);
logger.warning(msg);
logger.severe(msg);
logger.log(new LogRecord(Level.FINE, msg));
</code>```

Only info, warning, and severe work. the other methods run but return nothing to console, and write nothing to the log file. I need to implement at least 4 logging levels, but only the 3 work.

What is happening to log,config,fine,finer, finest? How do I get them to use my formatter? Or how do I pass the level to the formatter?

答:
You may set the Level of logging with setlevel(Level)

Set the log level specifying which message levels will be logged by
  this logger. Message levels lower than this value will be discarded.

In your case as you are interested in all levels, it would be :

```<code>logger.setLevel(Level.ALL);
</code>```

Body:
I have made a custom formatter for the java.util logger, implemented as below

logger = Logger.getAnonymousLogger();
logger.setUseParentHandlers(false);
sb = new StringBuffer();
try {
  Handler handler = new FileHandler("xx.log");
  handler.setFormatter(new CustomFormatter());
  logger.addHandler(handler);
} catch (IOException e) {
  e.printStackTrace();
}

 private class CustomFormatter extends Formatter {
    @Override
    public String format(LogRecord record) {
      String msg = record.getMessage();
      sb.append(msg);
      System.out.print(sb.toString());
      return sb.toString();
    }
  }

Running the following code:

logger.finest(msg);
logger.finer(msg);
logger.fine(msg);
logger.config(msg);
logger.info(msg);
logger.warning(msg);
logger.severe(msg);
logger.log(new LogRecord(Level.FINE, msg));

Only info, warning, and severe work. the other methods run but return nothing to console, and write nothing to the log file. I need to implement at least 4 logging levels, but only the 3 work.

What is happening to log,config,fine,finer, finest? How do I get them to use my formatter? Or how do I pass the level to the formatter?

Body:
You may set the Level of logging with setlevel(Level)

Set the log level specifying which message levels will be logged by
  this logger. Message levels lower than this value will be discarded.

In your case as you are interested in all levels, it would be :

logger.setLevel(Level.ALL);


问:
Laravel 5.4 null csrf_token() when posting to route
I'm sending an ajax post request, and with Laravel it seems that is done by creating a post route for it. I've set it up so a csrf token is put in the header automaticaly for every ajax request using ajaxSetup. I'm attempting to then catch that header on the backend and verify the tokens match.

In my web routes (which automatically use the web middleware), this returns as expected:

```<code>Route::get('/test', function() {
    return csrf_token();
});
</code>```

However, when I post to a route via AJAX, like either of the below ways:

Attempt 1:

```<code>Route::post('/test', 'AjaxController@test');
</code>```

In the AjaxController construct, followed by an alert in the view:

```<code>var_dump(csrf_token().',hi'); die;
</code>```

Response: ',hi' (csrf_token was null).

Attempt 2:

```<code>Route::post('/test', ['test' => csrf_token().',hi', 'uses' => 'AjaxController@test']);

$test = $request->route()->getAction()['test'];
var_dump($test); die;
</code>```

Response: ',hi' (csrf_token was null).

What I seem to be running into is, with get requests csrf_token() is populated, on my post request, it is not.

Any ideas?

答:
If you run this command php artisan make:auth documented here https://laravel.com/docs/5.4/authentication#authentication-quickstart when going to resources/views/layouts/app.blade.php you'll see this:

```<code><meta name="csrf-token" content="{{ csrf_token() }}">
</code>```

And in app.js

```<code>$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN':$('meta[name="csrf-token"]').attr('content')
    }
});
</code>```

In 5.3 there was this cool feature which looks as though it has since been removed in 5.4.

```<code><script>
    window.Laravel = <?php echo json_encode([
        'csrfToken' => csrf_token(),
    ]); ?>
</script>
</code>```

So what you need to do is add the csrf field to every request. Do the first 2 code snippets and you'll be fine. The 3rd I believe is probably for Vue.

Answer to your question: no, no, no and no. CSRF tokens I wouldn't believe are generated in POST requests, it's a Cross site Reference token, not an authentication token. If you're looking for something like authentication token refreshing then checkout JWT although the packages for JWT for laravel are a bit unfinished at the moment; with a little work you can get them working.

https://github.com/tymondesigns/jwt-auth 1.0.*@dev is pretty good. You can then use their refresh middleware to generate new tokens on request but this is quite advanced and unless it's for authentication then I wouldn't bother really.

I believe Dingo (another work in progress I believe) https://github.com/dingo/api uses the above package

Anything else let me know!

Body:
I'm sending an ajax post request, and with Laravel it seems that is done by creating a post route for it. I've set it up so a csrf token is put in the header automaticaly for every ajax request using ajaxSetup. I'm attempting to then catch that header on the backend and verify the tokens match.

In my web routes (which automatically use the web middleware), this returns as expected:

Route::get('/test', function() {
    return csrf_token();
});

However, when I post to a route via AJAX, like either of the below ways:

Attempt 1:

Route::post('/test', 'AjaxController@test');

In the AjaxController construct, followed by an alert in the view:

var_dump(csrf_token().',hi'); die;

Response: ',hi' (csrf_token was null).

Attempt 2:

Route::post('/test', ['test' => csrf_token().',hi', 'uses' => 'AjaxController@test']);

$test = $request->route()->getAction()['test'];
var_dump($test); die;

Response: ',hi' (csrf_token was null).

What I seem to be running into is, with get requests csrf_token() is populated, on my post request, it is not.

Any ideas?

Body:
If you run this command php artisan make:auth documented here https://laravel.com/docs/5.4/authentication#authentication-quickstart when going to resources/views/layouts/app.blade.php you'll see this:

<meta name="csrf-token" content="{{ csrf_token() }}">

And in app.js

$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN':$('meta[name="csrf-token"]').attr('content')
    }
});

In 5.3 there was this cool feature which looks as though it has since been removed in 5.4.

<script>
    window.Laravel = <?php echo json_encode([
        'csrfToken' => csrf_token(),
    ]); ?>
</script>

So what you need to do is add the csrf field to every request. Do the first 2 code snippets and you'll be fine. The 3rd I believe is probably for Vue.

Answer to your question: no, no, no and no. CSRF tokens I wouldn't believe are generated in POST requests, it's a Cross site Reference token, not an authentication token. If you're looking for something like authentication token refreshing then checkout JWT although the packages for JWT for laravel are a bit unfinished at the moment; with a little work you can get them working.

https://github.com/tymondesigns/jwt-auth 1.0.*@dev is pretty good. You can then use their refresh middleware to generate new tokens on request but this is quite advanced and unless it's for authentication then I wouldn't bother really.

I believe Dingo (another work in progress I believe) https://github.com/dingo/api uses the above package

Anything else let me know!


问:
Concat multiple C++ strings at once?
I'm new to C++ strings. Is there a way to concatenate more than two strings at once? Or I have to concat two strings at the time? My concern is that it probably needs to allocate memory on each operation, instead of only once for the final result.

Remember something like that in java, wonder if there is a method for that somewhere in std. Actually, std::stringstream might be it, but I don't know how exactly it works.

答:
You are correct that each concatenation could require an allocation.  Consider an expression like this, where each variable is a string:

```<code>a = b + c + d + e;
</code>```

This requires three concatenation operations and three temporaries, each of which requires a new allocation.

A simple solution is to use std::ostringstream, which should not require as many reallocations:

```<code>std::ostringstream ss;
ss << b << c << d << e;
a = ss.str();
</code>```

However, if we are concatenating only strings, we can do one better, and allocate exactly the right size of string (C++11-compatible implementation):

```<code>std::size_t total_string_size()
{
    return 1;
}

template <typename... T>
std::size_t total_string_size(std::string const &s, T const & ...tail)
{
    return s.size() + total_string_size(tail...);
}

void concat_strings_impl(std::string &) { }

template <typename... T>
void concat_strings_impl(std::string &out, std::string const &s, T const & ...tail)
{
    out += s;
    concat_strings_impl(out, tail...);
}

template <typename... T>
void concat_strings(std::string &out, T const & ...strings)
{
    out.clear();
    out.reserve(total_string_size(strings...));
    concat_strings_impl(out, strings...);
}
</code>```

Now we can call concat_strings(a, b, c, d, e) to perform the equivalent of a = b + c + d + e; in a single reallocation. (Demo)

Title: Concat multiple C++ strings at once?

Body:
You are correct that each concatenation could require an allocation.  Consider an expression like this, where each variable is a string:

a = b + c + d + e;

This requires three concatenation operations and three temporaries, each of which requires a new allocation.

A simple solution is to use std::ostringstream, which should not require as many reallocations:

std::ostringstream ss;
ss << b << c << d << e;
a = ss.str();

However, if we are concatenating only strings, we can do one better, and allocate exactly the right size of string (C++11-compatible implementation):

std::size_t total_string_size()
{
    return 1;
}

template <typename... T>
std::size_t total_string_size(std::string const &s, T const & ...tail)
{
    return s.size() + total_string_size(tail...);
}

void concat_strings_impl(std::string &) { }

template <typename... T>
void concat_strings_impl(std::string &out, std::string const &s, T const & ...tail)
{
    out += s;
    concat_strings_impl(out, tail...);
}

template <typename... T>
void concat_strings(std::string &out, T const & ...strings)
{
    out.clear();
    out.reserve(total_string_size(strings...));
    concat_strings_impl(out, strings...);
}

Now we can call concat_strings(a, b, c, d, e) to perform the equivalent of a = b + c + d + e; in a single reallocation. (Demo)


问:
What does Java do with my "equals" implementations here?
Today, I've stumbled over the following:

Consider two classes NewClass and NewClass1, which have the following "equals"-methods:

NewClass:

```<code>@Override
public boolean equals(Object obj) {
    return false;
}

public boolean equals(NewClass obj) {
    return value == obj.getValue();
}
</code>```

NewClass1:

```<code>@Override
public boolean equals(Object obj) {
    if(!(obj instanceof NewClass1)) {
        return false;
    }
    return equals((NewClass1) obj);
}

public boolean equals(NewClass1 obj) {
    return value == obj.getValue();
}
</code>```

What I find weird is that the equals in NewClass1 seems to be exponentially slower than the one in NewClass (for 10.000.000 calls 14ms against 3000ms). At first, I thought this was related to the "instanceof" check, but if I replace "return equals((NewClass1) obj);" with "return false;" in NewClass1, suddenly it runs more or less equally fast. I don't really understand what is happening here, because in my opinion, the return statement in equals(Object) should never actually be called. What am I getting wrong here?

The following is my "benchmarking code", in case I made some mistake there:

```<code>public static void main(String[] args) {
    // TODO code application logic here

    NewClass i1 = new NewClass(1);
    NewClass i2 = new NewClass(1);
    NewClass i3 = new NewClass(5);

    NewClass1 j1 = new NewClass1(1);
    NewClass1 j2 = new NewClass1(1);
    NewClass1 j3 = new NewClass1(5);

    Object o1 = new Object();
    Object o2 = new Object();

    assert(i1.equals(i1));
    assert(i1.equals(i2));
    assert(i1.equals(i3) == false);
    assert(i1.equals(o1) == false);

    assert(j1.equals(j1));
    assert(j1.equals(j2));
    assert(j1.equals(j3) == false);
    assert(j1.equals(o1) == false);

    long start = System.currentTimeMillis();

    for(int i=0; i<1000000000; i++) {
        i1.equals(i1);
        i1.equals(i2);
        i1.equals(o1);
        i1.equals(o2);
    }

    long end = System.currentTimeMillis();

    System.out.println("Execution time was "+(end-start)+" ms.");

    start = System.currentTimeMillis();

    for(int i=0; i<1000000000; i++) {
        j1.equals(j1);
        j1.equals(j2);
        j1.equals(o1);
        j1.equals(o2);
    }

    end = System.currentTimeMillis();

    System.out.println("Execution time was "+(end-start)+" ms.");
}
</code>```

答:
In the first example equals(NewClass) would ordinarily never be called. equals(Object) can be inlined by HotSpot (or similar), and the body of your test can be reduced to effectively nothing.

Back of enveloper calculations can be informative. "10.000.000 calls 8ms" is 1,250,000,000 iterations a second. Assuming a 4 GHz processor, that's about three cycles per iteration. A bit fast to be doing anything worthwhile. In fact the code says 1,000,000,000 not 10,000,000.

In fact in the actual code all the loop body could be eliminated. So, it doesn't really matter what you are measuring - it wont be reliable indication of anything useful. There are many other problems with doing microbenchmarks, which you can read in many other places.

ContentLicense: CC BY-SA 2.5

Body:
Today, I've stumbled over the following:

Consider two classes NewClass and NewClass1, which have the following "equals"-methods:

NewClass:

@Override
public boolean equals(Object obj) {
    return false;
}

public boolean equals(NewClass obj) {
    return value == obj.getValue();
}

NewClass1:

@Override
public boolean equals(Object obj) {
    if(!(obj instanceof NewClass1)) {
        return false;
    }
    return equals((NewClass1) obj);
}

public boolean equals(NewClass1 obj) {
    return value == obj.getValue();
}

What I find weird is that the equals in NewClass1 seems to be exponentially slower than the one in NewClass (for 10.000.000 calls 14ms against 3000ms). At first, I thought this was related to the "instanceof" check, but if I replace "return equals((NewClass1) obj);" with "return false;" in NewClass1, suddenly it runs more or less equally fast. I don't really understand what is happening here, because in my opinion, the return statement in equals(Object) should never actually be called. What am I getting wrong here?

The following is my "benchmarking code", in case I made some mistake there:

public static void main(String[] args) {
    // TODO code application logic here

    NewClass i1 = new NewClass(1);
    NewClass i2 = new NewClass(1);
    NewClass i3 = new NewClass(5);

    NewClass1 j1 = new NewClass1(1);
    NewClass1 j2 = new NewClass1(1);
    NewClass1 j3 = new NewClass1(5);

    Object o1 = new Object();
    Object o2 = new Object();

    assert(i1.equals(i1));
    assert(i1.equals(i2));
    assert(i1.equals(i3) == false);
    assert(i1.equals(o1) == false);

    assert(j1.equals(j1));
    assert(j1.equals(j2));
    assert(j1.equals(j3) == false);
    assert(j1.equals(o1) == false);

    long start = System.currentTimeMillis();

    for(int i=0; i<1000000000; i++) {
        i1.equals(i1);
        i1.equals(i2);
        i1.equals(o1);
        i1.equals(o2);
    }

    long end = System.currentTimeMillis();

    System.out.println("Execution time was "+(end-start)+" ms.");

    start = System.currentTimeMillis();

    for(int i=0; i<1000000000; i++) {
        j1.equals(j1);
        j1.equals(j2);
        j1.equals(o1);
        j1.equals(o2);
    }

    end = System.currentTimeMillis();

    System.out.println("Execution time was "+(end-start)+" ms.");
}


问:
Img won't centre align - email
Having an issue getting an image at the top of an email to center align. I believe it is to do with a piece of code that makes the image vanish when the browser is greater than 520px. Though I need this code for the rest of email. How can I create an exception so this particular image remains central?

```<code>.mobile {
    display: none !important;
    font-size 0 !important;
    max-height: 0 !important;
    line-height: 0 !important;
    margin: 0 !important;
    mso-hide: all !important;
    overflow: hidden !important;
}
.mobile img {
    max-height: 0 !important;
    width: 0 !important;
}

@media only screen and (max-width: 520px) {
    *[class=hide] {
        display: none !important;
    }
    [class=mobile] {
        display: block !important;
        max-height: none !important;
        margin: 0px !important;
        overflow: visible !important;
    }
    *[class=mobile] img {
        display: block !important;
        width: 100% !important;
        height: auto !important;
        max-height: none !important;
        max-width: 100% !important;
    }
}
</code>```

.

```<code><td class="mobile" style="font-size: 0; mso-hide: all; width:120px; height:24px;"><div align="center"><a href="~PROBE(201)~"><img border="0" height="24" width="120" src="images/MH-logo.png" /></a></div></td>
</code>```

答:
Give certain width and add this css

```<code>margin-left : auto;
margin-right : auto;
</code>```

Should solve your issue.

Title: Img won't centre align - email

Body:
Having an issue getting an image at the top of an email to center align. I believe it is to do with a piece of code that makes the image vanish when the browser is greater than 520px. Though I need this code for the rest of email. How can I create an exception so this particular image remains central?

.mobile {
    display: none !important;
    font-size 0 !important;
    max-height: 0 !important;
    line-height: 0 !important;
    margin: 0 !important;
    mso-hide: all !important;
    overflow: hidden !important;
}
.mobile img {
    max-height: 0 !important;
    width: 0 !important;
}

@media only screen and (max-width: 520px) {
    *[class=hide] {
        display: none !important;
    }
    [class=mobile] {
        display: block !important;
        max-height: none !important;
        margin: 0px !important;
        overflow: visible !important;
    }
    *[class=mobile] img {
        display: block !important;
        width: 100% !important;
        height: auto !important;
        max-height: none !important;
        max-width: 100% !important;
    }
}

.

Body:
Give certain width and add this css

margin-left : auto;
margin-right : auto;

Should solve your issue.


问:
Custom aggregation functions in angular ui-grid header get non-numeric value
It's easy to do count, min, max for the aggregate functions, but I would like to get string concat value in the grouped row.

What kind of custom function/aggregator I can write to aggregate string values?

```<code>$scope.gridOptions = {
    enableFiltering: true,
    treeRowHeaderAlwaysVisible: false,
    columnDefs: [
      { name: 'name', width: '30%' },
      { name: 'gender', sort: { priority: 1, direction: 'asc' }, width: '20%', cellFilter: 'mapGender' },
      { name: 'age', treeAggregationType: uiGridGroupingConstants.aggregation.MAX, width: '20%' },
      { name: 'company', width: '25%' },
      { name: 'registered', width: '40%', cellFilter: 'date', type: 'date' },
      { name: 'state', grouping: { groupPriority: 0 }, sort: { priority: 0, direction: 'desc' }, width: '35%', cellTemplate: '<div><div ng-if="!col.grouping || col.grouping.groupPriority === undefined || col.grouping.groupPriority === null || ( row.groupHeader && col.grouping.groupPriority === row.treeLevel )" class="ui-grid-cell-contents" title="TOOLTIP">{{COL_FIELD CUSTOM_FILTERS}}</div></div>' },
      { name: 'balance', width: '25%', cellFilter: 'currency', treeAggregationType: uiGridGroupingConstants.aggregation.AVG, customTreeAggregationFinalizerFn: function( aggregation ) {
        aggregation.rendered = aggregation.value;
      } }
    ],
    onRegisterApi: function( gridApi ) {
      $scope.gridApi = gridApi;
    }
</code>```

Here is plunkr - http://plnkr.co/edit/KVq7vC9cFb7uNc9edLYj?p=preview

Currently, it's grouped on State and gives aggregated value max and sum for two columns Age and Balance respectively. I want to display grouped Gender row value as "Male, Female". How can I do that?

答:
I was able to resolve it on my own, here is the custom function to add concat or conditional string value return -

```<code>     { name: 'company', width: '25%',
        customTreeAggregationFn : function( aggregation, fieldValue, numValue, row ) {
          if(!aggregation.value){
           aggregation.value = row.entity.company;
          }
        },
        customTreeAggregationFinalizerFn: function( aggregation ) {
         aggregation.rendered = aggregation.value;
        }
      }
</code>```

Plunkr link to the solution - http://plnkr.co/edit/KVq7vC9cFb7uNc9edLYj?p=preview

Body:
It's easy to do count, min, max for the aggregate functions, but I would like to get string concat value in the grouped row.

What kind of custom function/aggregator I can write to aggregate string values?

$scope.gridOptions = {
    enableFiltering: true,
    treeRowHeaderAlwaysVisible: false,
    columnDefs: [
      { name: 'name', width: '30%' },
      { name: 'gender', sort: { priority: 1, direction: 'asc' }, width: '20%', cellFilter: 'mapGender' },
      { name: 'age', treeAggregationType: uiGridGroupingConstants.aggregation.MAX, width: '20%' },
      { name: 'company', width: '25%' },
      { name: 'registered', width: '40%', cellFilter: 'date', type: 'date' },
      { name: 'state', grouping: { groupPriority: 0 }, sort: { priority: 0, direction: 'desc' }, width: '35%', cellTemplate: '

{{COL_FIELD CUSTOM_FILTERS}}

' },
      { name: 'balance', width: '25%', cellFilter: 'currency', treeAggregationType: uiGridGroupingConstants.aggregation.AVG, customTreeAggregationFinalizerFn: function( aggregation ) {
        aggregation.rendered = aggregation.value;
      } }
    ],
    onRegisterApi: function( gridApi ) {
      $scope.gridApi = gridApi;
    }

Here is plunkr - http://plnkr.co/edit/KVq7vC9cFb7uNc9edLYj?p=preview

Currently, it's grouped on State and gives aggregated value max and sum for two columns Age and Balance respectively. I want to display grouped Gender row value as "Male, Female". How can I do that?

Body:
I was able to resolve it on my own, here is the custom function to add concat or conditional string value return -

     { name: 'company', width: '25%',
        customTreeAggregationFn : function( aggregation, fieldValue, numValue, row ) {
          if(!aggregation.value){
           aggregation.value = row.entity.company;
          }
        },
        customTreeAggregationFinalizerFn: function( aggregation ) {
         aggregation.rendered = aggregation.value;
        }
      }

Plunkr link to the solution - http://plnkr.co/edit/KVq7vC9cFb7uNc9edLYj?p=preview


问:
How do I desing my application on Java(eclipse)
I'm new with learning Java. I was learning C# and C# has own designer inside it. Like " Add: Button, Label, Timer, TextBox" But in Eclipse there is no such a thing. Should I use and external program for design or I'm blind and can't see it?

答:
Take a look at the Eclipse RCP, that is a good documented environment to create graphical GUI's
https://wiki.eclipse.org/Rich_Client_Platform/FAQ</p>


问:
Hbase remotely connecting to standalone instance
I have been trying to setup HBase for the first time. I am able to successfully run the native Hbase shell on the server. But I am not able to connect remotely via a client.

I start Hbase using the following command on host:
/home/kirill/hbase/hbase-1.2.5/bin/start-hbase.sh

To connect from a client, I run the following in Python (Anaconda):

```<code>>>> import happybase
>>> co = happybase.Connection('192.168.0.18',2181)
>>> co.tables()
</code>```

I get the following error after trying to list tables with co.tables():

```<code>Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\soft\miniconda2\lib\site-packages\happybase\connection.py", line 242, in tables
    names = self.client.getTableNames()
  File "C:\soft\miniconda2\lib\site-packages\thriftpy\thrift.py", line 198, in _req
    return self._recv(_api)
  File "C:\soft\miniconda2\lib\site-packages\thriftpy\thrift.py", line 210, in _recv
    fname, mtype, rseqid = self._iprot.read_message_begin()
  File "C:\soft\miniconda2\lib\site-packages\thriftpy\protocol\binary.py", line 372, in read_message_begin
    self.trans, strict=self.strict_read)
  File "C:\soft\miniconda2\lib\site-packages\thriftpy\protocol\binary.py", line 164, in read_message_begin
    sz = unpack_i32(inbuf.read(4))
  File "C:\soft\miniconda2\lib\site-packages\thriftpy\transport\__init__.py", line 32, in read
    return readall(self._read, sz)
  File "C:\soft\miniconda2\lib\site-packages\thriftpy\transport\__init__.py", line 14, in readall
    chunk = read_fn(sz - have)
  File "C:\soft\miniconda2\lib\site-packages\thriftpy\transport\buffered\__init__.py", line 39, in _read
    self._rbuf = BytesIO(self._trans.read(max(sz, self._buf_size)))
  File "C:\soft\miniconda2\lib\site-packages\thriftpy\transport\socket.py", line 125, in read
    message='TSocket read 0 bytes')
thriftpy.transport.TTransportException: TTransportException(message='TSocket read 0 bytes', type=4)
</code>```

Here are last 3 lines from Hbase log:

It says that connection from 192.168.0.11 (client IP) is accepted, but immediately after that it throws an Exception causing close of session:

```<code>2017-06-06 10:48:10,634 INFO  [NIOServerCxn.Factory:0.0.0.0/0.0.0.0:2181] server.NIOServerCnxnFactory: Accepted socket connection from /192.168.0.11:58052
2017-06-06 10:48:11,841 WARN  [NIOServerCxn.Factory:0.0.0.0/0.0.0.0:2181] server.NIOServerCnxn: Exception causing close of session 0x0 due to java.io.IOException: Len error -2147418111
2017-06-06 10:48:11,842 INFO  [NIOServerCxn.Factory:0.0.0.0/0.0.0.0:2181] server.NIOServerCnxn: Closed socket connection for client /192.168.0.11:58052 (no session established for client)
</code>```

Any help would be greatly appreciated. Here is the host setup:

Hbase setup:

Host running Hbase: Ubuntu Server, Ubuntu 16.04.1 LTS (GNU/Linux 4.4.0-31-generic x86_64)

path to Hbase bin folder: /home/kirill/hbase/hbase-1.2.5/bin

IP of host: 192.168.0.18

conf/hbase-site.xml:

```<code><configuration>

    <property>
        <name>hbase.rootdir</name>
        <value>file:///home/kirill/hbase/hbase-1.2.5/</value>
    </property>

    <property>
        <name>hbase.zookeeper.property.dataDir</name>
        <value>/home/kirill/zookeeper</value>
    </property>

    <property>
        <name>hbase.zookeeper.property.clientPort</name>
        <value>2181</value>
    </property>
    <property>
        <name>hbase.zookeeper.quorum</name>
        <value>192.168.0.18</value>
    </property>

</configuration>
</code>```

/etc/hosts:

```<code>127.0.0.1   localhost
192.168.0.18    ubuntu
</code>```

答:
Found this issue opened for happybase python package: https://github.com/wbolster/happybase/issues/6

It works now.
2 things needed to be done differently:

hbase has to be started with Thrift like so:
/home/kirill/hbase/hbase-1.2.5/bin/hbase thrift start -threadpool

I should not be connecting to port specified under hbase.zookeeper.property.clientPort which is 2181, but rather the default port that is used in the happybase Connection() function, which I believe is 9090.

I have also changed my /etc/hosts file to this:

192.168.0.18    ubuntu.ubuntu-domain ubuntu localhost

Body:
I have been trying to setup HBase for the first time. I am able to successfully run the native Hbase shell on the server. But I am not able to connect remotely via a client.

I start Hbase using the following command on host:
/home/kirill/hbase/hbase-1.2.5/bin/start-hbase.sh

To connect from a client, I run the following in Python (Anaconda):

>>> import happybase
>>> co = happybase.Connection('192.168.0.18',2181)
>>> co.tables()

I get the following error after trying to list tables with co.tables():

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\soft\miniconda2\lib\site-packages\happybase\connection.py", line 242, in tables
    names = self.client.getTableNames()
  File "C:\soft\miniconda2\lib\site-packages\thriftpy\thrift.py", line 198, in _req
    return self._recv(_api)
  File "C:\soft\miniconda2\lib\site-packages\thriftpy\thrift.py", line 210, in _recv
    fname, mtype, rseqid = self._iprot.read_message_begin()
  File "C:\soft\miniconda2\lib\site-packages\thriftpy\protocol\binary.py", line 372, in read_message_begin
    self.trans, strict=self.strict_read)
  File "C:\soft\miniconda2\lib\site-packages\thriftpy\protocol\binary.py", line 164, in read_message_begin
    sz = unpack_i32(inbuf.read(4))
  File "C:\soft\miniconda2\lib\site-packages\thriftpy\transport\__init__.py", line 32, in read
    return readall(self._read, sz)
  File "C:\soft\miniconda2\lib\site-packages\thriftpy\transport\__init__.py", line 14, in readall
    chunk = read_fn(sz - have)
  File "C:\soft\miniconda2\lib\site-packages\thriftpy\transport\buffered\__init__.py", line 39, in _read
    self._rbuf = BytesIO(self._trans.read(max(sz, self._buf_size)))
  File "C:\soft\miniconda2\lib\site-packages\thriftpy\transport\socket.py", line 125, in read
    message='TSocket read 0 bytes')
thriftpy.transport.TTransportException: TTransportException(message='TSocket read 0 bytes', type=4)

Here are last 3 lines from Hbase log:

It says that connection from 192.168.0.11 (client IP) is accepted, but immediately after that it throws an Exception causing close of session:

2017-06-06 10:48:10,634 INFO  [NIOServerCxn.Factory:0.0.0.0/0.0.0.0:2181] server.NIOServerCnxnFactory: Accepted socket connection from /192.168.0.11:58052
2017-06-06 10:48:11,841 WARN  [NIOServerCxn.Factory:0.0.0.0/0.0.0.0:2181] server.NIOServerCnxn: Exception causing close of session 0x0 due to java.io.IOException: Len error -2147418111
2017-06-06 10:48:11,842 INFO  [NIOServerCxn.Factory:0.0.0.0/0.0.0.0:2181] server.NIOServerCnxn: Closed socket connection for client /192.168.0.11:58052 (no session established for client)

Any help would be greatly appreciated. Here is the host setup:

Hbase setup:

Host running Hbase: Ubuntu Server, Ubuntu 16.04.1 LTS (GNU/Linux 4.4.0-31-generic x86_64)

path to Hbase bin folder: /home/kirill/hbase/hbase-1.2.5/bin

IP of host: 192.168.0.18

conf/hbase-site.xml:

<configuration>

    <property>
        <name>hbase.rootdir</name>
        <value>file:///home/kirill/hbase/hbase-1.2.5/</value>
    </property>

    <property>
        <name>hbase.zookeeper.property.dataDir</name>
        <value>/home/kirill/zookeeper</value>
    </property>

    <property>
        <name>hbase.zookeeper.property.clientPort</name>
        <value>2181</value>
    </property>
    <property>
        <name>hbase.zookeeper.quorum</name>
        <value>192.168.0.18</value>
    </property>

</configuration>

/etc/hosts:

127.0.0.1   localhost
192.168.0.18    ubuntu


问:
Validation of input data via Scanner
I have a problem with if-statement. There is a file with the line admin.admin. I break the line into points and store it in an array. The first element of the array is the login. The first element of the array is compared with the input value (inputLogin = "admin" in the code String inputLogin = textField[0].getText()). I have to get the true, but I'm actually getting a false

first java file

```<code>package classPackage;

import java.awt.*;

import javax.swing.*;

public class ClassAuthorization extends JFrame {

private static final int WIDTH_AUTH = 400;
private static final int HEIGHT_AUTH = 500;

private JLabel[] label = new JLabel[3];
public JTextField[] textField = new JTextField[1];
public JPasswordField[] passwordField = new JPasswordField[1];
protected JButton[] button = new JButton[2];

private String[] text = {"Авторизуйтесь", "Логин:", "Пароль:", "Вход", "Я - участник"};

private Integer[] coordXAuth = {110, 39, 25, 110, 110, 25, 25};
private Integer[] coordYAuth = {20, 120, 170, 125, 175, 225, 285};

private Integer[] widthAuth = {200, 100, 100, 220, 220, 305, 305};
private Integer[] heightAuth = {30, 30, 30, 27, 26, 40, 40};

private Integer[] sizeFont = {24, 22, 22, 18, 18, 18, 18};

public ClassAuthorization() {

    setSize(WIDTH_AUTH, HEIGHT_AUTH);
    setLocationRelativeTo(null);

    JPanel panel = new JPanel();
    getContentPane().setLayout(null);
    setPanel(panel, 10, 11, 400, 500);
    getContentPane().add(panel);

    for (int i = 0; i < 3; i++) {
        if (i < 1) {
            addLabel(i, panel);
            addTextField(i, panel);
            addPasswordField(i, panel);
            addButton(i, panel);
        }
        else if (i == 1) {
        addLabel(i, panel);
        addButton(i, panel);
        }
        else if (i > 1) {
            addLabel(i, panel);
        }
    }

}

private JPanel setPanel (JPanel panel, int x, int y, int width, int height) {

    panel.setBounds(x, y, width, height);
    panel.setLayout(null);
    return panel;

}

private void addLabel(int i, JPanel panel) {

    label[i] = new JLabel();
    label[i].setText(text[i]);
    label[i].setBounds(coordXAuth[i], coordYAuth[i], widthAuth[i], heightAuth[i]);
    label[i].setFont(new Font("Segoe UI Light", Font.PLAIN, sizeFont[i]));
    panel.add(label[i]);

}

private void addTextField(int i, JPanel panel) {

    textField[i] = new JTextField();
    textField[i].setBounds(coordXAuth[i + 3], coordYAuth[i + 3], widthAuth[i + 3], heightAuth[i + 3]);
    textField[i].setFont(new Font("Segoe UI Light", Font.PLAIN, sizeFont[i + 3]));
    panel.add(textField[i]);
}

private void addPasswordField(int i, JPanel panel) {

    passwordField[i] = new JPasswordField();
    passwordField[i].setBounds(coordXAuth[i + 4], coordYAuth[i + 4], widthAuth[i + 4], heightAuth[i + 4]);
    panel.add(passwordField[i]);

}

private void addButton(int i, JPanel panel) {

    button[i] = new JButton();
    button[i].setText(text[i + 3]);
    button[i].setBounds(coordXAuth[i + 5], coordYAuth[i + 5], widthAuth[i + 5], heightAuth[i + 5]);
    button[i].setFont(new Font("Segoe UI Light", Font.PLAIN, sizeFont[i + 5]));
    panel.add(button[i]);
}

}
</code>```

Second java file

```<code>package mainPackage;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.util.Arrays;
import java.util.Scanner;

import javax.swing.JButton;

import classPackage.ClassAuthorization;

public class Authorization extends ClassAuthorization {

private String path = "src/putFile/Account.txt";

public Authorization() {
    checkAccess(button[0]);
}

private void checkAccess(JButton button) {

    button.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {

            File file = new File(path);
            Scanner scanner;

            try {

                scanner = new Scanner(file);

                do {

                    String account = scanner.nextLine();
                    String[] parts = account.split("\\.");
                    String login = parts[0].trim();
                    String pass = parts[1];
                    char [] password = pass.toCharArray();
                    String inputLogin = textField[0].getText();
                    char[] inputPassword = passwordField[0].getPassword();
                    System.out.println(inputPassword);

                    if (inputLogin.equals(login) == true && Arrays.equals(password, inputPassword) == true) { // BAD

                         System.out.println("GOOD");

                        break;
                    }
                    else {

                        System.out.println("BAD");
                    }
                } while (scanner.hasNextLine() == true);
            }
            catch (FileNotFoundException NotFoundFile) {
                NotFoundFile.printStackTrace();
            }
        }
    });
}

public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                Authorization frame = new Authorization();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

}
</code>```

Account.txt

```<code>admin.admin
</code>```

答:
Before I go into a real answer to your question, I must give some advices:

Avoid extending JFrame, as JFrame is a rigid container, instead build your GUI towards JPanels and instantiate a JFrame, take the answers in: Extends JFrame vs. creating it inside the program as a reference

Why create a whole array for these lines:

```<code>public JTextField[] textField = new JTextField[1];
public JPasswordField[] passwordField = new JPasswordField[1];
</code>```

if you're going to have a single element, an array is not needed.

The following lines, make no sense to me, because there's no need to wrap the numbers as Integer when you could use the primitive int, this affects the performance of the program.

```<code>private Integer[] coordXAuth = {110, 39, 25, 110, 110, 25, 25};
private Integer[] coordYAuth = {20, 120, 170, 125, 175, 225, 285};
</code>```

getContentPane().setLayout(null); STOP using null-layout! Please read carefully how to use the different layout managers, you can combine them and create cool GUIs.

Swing was designed to use them, because it has to deal with different OS, PLAFs, screen sizes and resolutions, pixel perfect GUIs are an illusion, here is an example of what happens when you use them.

See: Why is it frowned upon to use a null layout in Swing?, What's wrong with the Null Layout in Java? and Null layout is evil for more information.

Stop using setLayout(null) and setBounds(...), setLocation(...) methods right now!

These lines:

```<code>while (scanner.hasNextLine() == true);
if (inputLogin.equals(login) == true && Arrays.equals(password, inputPassword) == true) { // BAD
</code>```

could have been written like this:

```<code>while (scanner.hasNextLine()); //Removed == true
if (inputLogin.equals(login) && Arrays.equals(password, inputPassword)) { //Removed == true
</code>```

because those methods already return a boolean, so, there's no need to compare a boolean with another one, which is the same as if (true == true), why not if (true)? It's easier to read and understand.

However I must congratulate you for placing your program on the EDT.

Now, after we've said the above recommendations, let's move on to the program... it works fine for me:

This is the console output when I ran it:

```<code>admin
GOOD
</code>```

So, the problem is probably on your file, I recommend you to write it again maybe?

Here's an example that generates a similar output using:

A GridBagLayout for the outer pane.

A GridLayout for both user / password label and fields panes

Code:

```<code>import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Scanner;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

public class LoginSample {
    private JFrame frame;
    private JLabel userLabel;
    private JLabel passLabel;
    private JTextField userField;
    private JPasswordField passField;
    private JButton button;
    private JButton button2;
    private File file;
    private JPanel pane;
    private JPanel contentPane;

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            new LoginSample().createAndShowGui();
        });
    }

    private void createAndShowGui() {
        GridBagConstraints gbc = new GridBagConstraints();

        frame = new JFrame(getClass().getSimpleName());
        contentPane = new JPanel();
        contentPane.setLayout(new GridBagLayout());

        userLabel = new JLabel("User: ");
        passLabel = new JLabel("Password: ");
        userField = new JTextField(10);
        passField = new JPasswordField(10);

        pane = new JPanel();
        pane.setLayout(new GridLayout(1, 2));
        pane.add(userLabel);
        pane.add(userField);

        gbc.fill = GridBagConstraints.BOTH;
        gbc.insets = new Insets(5, 5, 5, 5);
        gbc.gridx = 0;
        gbc.gridy = 0;

        contentPane.add(pane, gbc);

        gbc.gridx = 0;
        gbc.gridy = 1;
        pane = new JPanel();
        pane.setLayout(new GridLayout(1, 2));
        pane.add(passLabel);
        pane.add(passField);
        contentPane.add(pane, gbc);

        button = new JButton("Click me!");
        button2 = new JButton("Do not click me");

        file = new File("src/sof/users.txt");
        System.out.println(file.getAbsolutePath());

        button.addActionListener(listener);
        button2.addActionListener(listener);

        gbc.gridx = 0;
        gbc.gridy = 2;
        contentPane.add(button, gbc);

        gbc.gridy = 3;
        contentPane.add(button2, gbc);

        frame.add(contentPane);

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }

    private ActionListener listener = e -> {
        if (e.getSource().equals(button)) {
            String s = "";
            Scanner sc = null;
            try {
                sc = new Scanner(file);
                while (sc.hasNext()) {
                    s = sc.nextLine();
                    System.out.println(s);
                }
            } catch (FileNotFoundException ex) {
                ex.printStackTrace();
            } finally {
                sc.close();
            }
            String[] parts = s.split("\\.");
            String user = parts[0].trim();
            String pass = parts[1].trim();
            System.out.println(user + " <<>> " + Arrays.toString(pass.toCharArray()));
            System.out.println(userField.getText() + " <<>> " + Arrays.toString(passField.getPassword()));
            System.out.println(user.equals(userField.getText()));
            System.out.println(Arrays.equals(pass.toCharArray(), passField.getPassword()));
        } else {
            System.out.println("Told you not to click me! You made me cry :'(");
        }
    };
}
</code>```

As you can see, the code is short, it's complete because you can copy-paste it and see the output with a single modification (file path), it's verifiable (it shows the same output as below), that's what you're expected to do when you're requested to do a MCVE. Without posting the relevant code, well, I couldn't have written the first five suggestions :)

My output vs yours, both are really similar, just change the fonts and it should look like the one before...

Title: Validation of input data via Scanner

Body:
I have a problem with if-statement. There is a file with the line admin.admin. I break the line into points and store it in an array. The first element of the array is the login. The first element of the array is compared with the input value (inputLogin = "admin" in the code String inputLogin = textField[0].getText()). I have to get the true, but I'm actually getting a false

first java file

package classPackage;

import java.awt.*;

import javax.swing.*;

public class ClassAuthorization extends JFrame {

private static final int WIDTH_AUTH = 400;
private static final int HEIGHT_AUTH = 500;

private JLabel[] label = new JLabel[3];
public JTextField[] textField = new JTextField[1];
public JPasswordField[] passwordField = new JPasswordField[1];
protected JButton[] button = new JButton[2];

private String[] text = {"Авторизуйтесь", "Логин:", "Пароль:", "Вход", "Я - участник"};

private Integer[] coordXAuth = {110, 39, 25, 110, 110, 25, 25};
private Integer[] coordYAuth = {20, 120, 170, 125, 175, 225, 285};

private Integer[] widthAuth = {200, 100, 100, 220, 220, 305, 305};
private Integer[] heightAuth = {30, 30, 30, 27, 26, 40, 40};

private Integer[] sizeFont = {24, 22, 22, 18, 18, 18, 18};

public ClassAuthorization() {

    setSize(WIDTH_AUTH, HEIGHT_AUTH);
    setLocationRelativeTo(null);

    JPanel panel = new JPanel();
    getContentPane().setLayout(null);
    setPanel(panel, 10, 11, 400, 500);
    getContentPane().add(panel);

    for (int i = 0; i < 3; i++) {
        if (i < 1) {
            addLabel(i, panel);
            addTextField(i, panel);
            addPasswordField(i, panel);
            addButton(i, panel);
        }
        else if (i == 1) {
        addLabel(i, panel);
        addButton(i, panel);
        }
        else if (i > 1) {
            addLabel(i, panel);
        }
    }

}

private JPanel setPanel (JPanel panel, int x, int y, int width, int height) {

    panel.setBounds(x, y, width, height);
    panel.setLayout(null);
    return panel;

}

private void addLabel(int i, JPanel panel) {

    label[i] = new JLabel();
    label[i].setText(text[i]);
    label[i].setBounds(coordXAuth[i], coordYAuth[i], widthAuth[i], heightAuth[i]);
    label[i].setFont(new Font("Segoe UI Light", Font.PLAIN, sizeFont[i]));
    panel.add(label[i]);

}

private void addTextField(int i, JPanel panel) {

    textField[i] = new JTextField();
    textField[i].setBounds(coordXAuth[i + 3], coordYAuth[i + 3], widthAuth[i + 3], heightAuth[i + 3]);
    textField[i].setFont(new Font("Segoe UI Light", Font.PLAIN, sizeFont[i + 3]));
    panel.add(textField[i]);
}

private void addPasswordField(int i, JPanel panel) {

    passwordField[i] = new JPasswordField();
    passwordField[i].setBounds(coordXAuth[i + 4], coordYAuth[i + 4], widthAuth[i + 4], heightAuth[i + 4]);
    panel.add(passwordField[i]);

}

private void addButton(int i, JPanel panel) {

    button[i] = new JButton();
    button[i].setText(text[i + 3]);
    button[i].setBounds(coordXAuth[i + 5], coordYAuth[i + 5], widthAuth[i + 5], heightAuth[i + 5]);
    button[i].setFont(new Font("Segoe UI Light", Font.PLAIN, sizeFont[i + 5]));
    panel.add(button[i]);
}

}

Second java file

package mainPackage;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.util.Arrays;
import java.util.Scanner;

import javax.swing.JButton;

import classPackage.ClassAuthorization;

public class Authorization extends ClassAuthorization {

private String path = "src/putFile/Account.txt";

public Authorization() {
    checkAccess(button[0]);
}

private void checkAccess(JButton button) {

    button.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {

            File file = new File(path);
            Scanner scanner;

            try {

                scanner = new Scanner(file);

                do {

                    String account = scanner.nextLine();
                    String[] parts = account.split("\\.");
                    String login = parts[0].trim();
                    String pass = parts[1];
                    char [] password = pass.toCharArray();
                    String inputLogin = textField[0].getText();
                    char[] inputPassword = passwordField[0].getPassword();
                    System.out.println(inputPassword);

                    if (inputLogin.equals(login) == true && Arrays.equals(password, inputPassword) == true) { // BAD

                         System.out.println("GOOD");

                        break;
                    }
                    else {

                        System.out.println("BAD");
                    }
                } while (scanner.hasNextLine() == true);
            }
            catch (FileNotFoundException NotFoundFile) {
                NotFoundFile.printStackTrace();
            }
        }
    });
}

public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                Authorization frame = new Authorization();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

}

Account.txt

admin.admin

Body:
Before I go into a real answer to your question, I must give some advices:

Avoid extending JFrame, as JFrame is a rigid container, instead build your GUI towards JPanels and instantiate a JFrame, take the answers in: Extends JFrame vs. creating it inside the program as a reference

Why create a whole array for these lines:

public JTextField[] textField = new JTextField[1];
public JPasswordField[] passwordField = new JPasswordField[1];

if you're going to have a single element, an array is not needed.

The following lines, make no sense to me, because there's no need to wrap the numbers as Integer when you could use the primitive int, this affects the performance of the program.

private Integer[] coordXAuth = {110, 39, 25, 110, 110, 25, 25};
private Integer[] coordYAuth = {20, 120, 170, 125, 175, 225, 285};

getContentPane().setLayout(null); STOP using null-layout! Please read carefully how to use the different layout managers, you can combine them and create cool GUIs.

Swing was designed to use them, because it has to deal with different OS, PLAFs, screen sizes and resolutions, pixel perfect GUIs are an illusion, here is an example of what happens when you use them.

See: Why is it frowned upon to use a null layout in Swing?, What's wrong with the Null Layout in Java? and Null layout is evil for more information.

Stop using setLayout(null) and setBounds(...), setLocation(...) methods right now!

These lines:

while (scanner.hasNextLine() == true);
if (inputLogin.equals(login) == true && Arrays.equals(password, inputPassword) == true) { // BAD

could have been written like this:

while (scanner.hasNextLine()); //Removed == true
if (inputLogin.equals(login) && Arrays.equals(password, inputPassword)) { //Removed == true

because those methods already return a boolean, so, there's no need to compare a boolean with another one, which is the same as if (true == true), why not if (true)? It's easier to read and understand.

However I must congratulate you for placing your program on the EDT.

Now, after we've said the above recommendations, let's move on to the program... it works fine for me:

This is the console output when I ran it:

admin
GOOD

So, the problem is probably on your file, I recommend you to write it again maybe?

Here's an example that generates a similar output using:

A GridBagLayout for the outer pane.

A GridLayout for both user / password label and fields panes

Code:

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Scanner;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

public class LoginSample {
    private JFrame frame;
    private JLabel userLabel;
    private JLabel passLabel;
    private JTextField userField;
    private JPasswordField passField;
    private JButton button;
    private JButton button2;
    private File file;
    private JPanel pane;
    private JPanel contentPane;

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            new LoginSample().createAndShowGui();
        });
    }

    private void createAndShowGui() {
        GridBagConstraints gbc = new GridBagConstraints();

        frame = new JFrame(getClass().getSimpleName());
        contentPane = new JPanel();
        contentPane.setLayout(new GridBagLayout());

        userLabel = new JLabel("User: ");
        passLabel = new JLabel("Password: ");
        userField = new JTextField(10);
        passField = new JPasswordField(10);

        pane = new JPanel();
        pane.setLayout(new GridLayout(1, 2));
        pane.add(userLabel);
        pane.add(userField);

        gbc.fill = GridBagConstraints.BOTH;
        gbc.insets = new Insets(5, 5, 5, 5);
        gbc.gridx = 0;
        gbc.gridy = 0;

        contentPane.add(pane, gbc);

        gbc.gridx = 0;
        gbc.gridy = 1;
        pane = new JPanel();
        pane.setLayout(new GridLayout(1, 2));
        pane.add(passLabel);
        pane.add(passField);
        contentPane.add(pane, gbc);

        button = new JButton("Click me!");
        button2 = new JButton("Do not click me");

        file = new File("src/sof/users.txt");
        System.out.println(file.getAbsolutePath());

        button.addActionListener(listener);
        button2.addActionListener(listener);

        gbc.gridx = 0;
        gbc.gridy = 2;
        contentPane.add(button, gbc);

        gbc.gridy = 3;
        contentPane.add(button2, gbc);

        frame.add(contentPane);

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }

    private ActionListener listener = e -> {
        if (e.getSource().equals(button)) {
            String s = "";
            Scanner sc = null;
            try {
                sc = new Scanner(file);
                while (sc.hasNext()) {
                    s = sc.nextLine();
                    System.out.println(s);
                }
            } catch (FileNotFoundException ex) {
                ex.printStackTrace();
            } finally {
                sc.close();
            }
            String[] parts = s.split("\\.");
            String user = parts[0].trim();
            String pass = parts[1].trim();
            System.out.println(user + " <<>> " + Arrays.toString(pass.toCharArray()));
            System.out.println(userField.getText() + " <<>> " + Arrays.toString(passField.getPassword()));
            System.out.println(user.equals(userField.getText()));
            System.out.println(Arrays.equals(pass.toCharArray(), passField.getPassword()));
        } else {
            System.out.println("Told you not to click me! You made me cry :'(");
        }
    };
}

As you can see, the code is short, it's complete because you can copy-paste it and see the output with a single modification (file path), it's verifiable (it shows the same output as below), that's what you're expected to do when you're requested to do a MCVE. Without posting the relevant code, well, I couldn't have written the first five suggestions :)

My output vs yours, both are really similar, just change the fonts and it should look like the one before...


问:
Better way to structure/new keyword
Some time ago I came across the following construct which I have rarely seen since, though I use it relatively frequently.  I use it typically when checking on a whole list of conditions are true and it prevents large levels of indentation.  Essentially it uses a for loop to provide a kind of structured goto.  My question is firstly whether there is better way to structure this, secondly whether people like it and thirdly whether a new keyword in java/c++ etc. such as unit { } which would only cause breaks to exit to the end of the unit would be useful and clearer.

ps I realise that it is on slip away from an infinite loop, but I think my paranoia about that has meant its never happened.

Edit: I have added some setup code for the further conditions to try to illuminate problems with chained if then elses

```<code>boolean valid = false;

// this loop never loops
for (;;)
{
    if (!condition1)
        break;

    condition2.setup();

    if (!condition2)
        break;

    condition3.setup();

    if (!condition3)
        break;

    valid = true;
    break;
}

if (valid) dosomething();
</code>```

EDIT:

I have just discovered that in fact there is a way to structure this in java without misusing loops etc. and wondered whether this would similarily be frowned on, though I guess I have missed the boat on this one.

The restructured code looks like this.

```<code>boolean valid = false;

breakout:
{
    if (!condition1)
        break breakout;

    condition2.setup();

    if (!condition2)
        break breakout;

    condition3.setup();

    if (!condition3)
        break breakout;

    valid = true;
}

if (valid) dosomething();
</code>```

Now that removes the misuse of the for loop which caused a lot of the complaints, and is actually a solution I think is quite neat and is what I was looking to find originally.
I am guessing that this structure is probably not well known since no one mentioned it, people object to this as strongly?

答: The reason for this construct is because goto is a dirty word in programming. But lets face it, you are effectively using the loop construct to do the same thing. My opinion on this is either be honest and use the goto or refactor the code.

Title: Better way to structure/new keyword

Body:
Some time ago I came across the following construct which I have rarely seen since, though I use it relatively frequently.  I use it typically when checking on a whole list of conditions are true and it prevents large levels of indentation.  Essentially it uses a for loop to provide a kind of structured goto.  My question is firstly whether there is better way to structure this, secondly whether people like it and thirdly whether a new keyword in java/c++ etc. such as unit { } which would only cause breaks to exit to the end of the unit would be useful and clearer.

ps I realise that it is on slip away from an infinite loop, but I think my paranoia about that has meant its never happened.

Edit: I have added some setup code for the further conditions to try to illuminate problems with chained if then elses

boolean valid = false;

// this loop never loops
for (;;)
{
    if (!condition1)
        break;

    condition2.setup();

    if (!condition2)
        break;

    condition3.setup();

    if (!condition3)
        break;

    valid = true;
    break;
}

if (valid) dosomething();

EDIT:

I have just discovered that in fact there is a way to structure this in java without misusing loops etc. and wondered whether this would similarily be frowned on, though I guess I have missed the boat on this one.

The restructured code looks like this.

boolean valid = false;

breakout:
{
    if (!condition1)
        break breakout;

    condition2.setup();

    if (!condition2)
        break breakout;

    condition3.setup();

    if (!condition3)
        break breakout;

    valid = true;
}

if (valid) dosomething();

Now that removes the misuse of the for loop which caused a lot of the complaints, and is actually a solution I think is quite neat and is what I was looking to find originally.
I am guessing that this structure is probably not well known since no one mentioned it, people object to this as strongly?


问:
How install OpenCV_contrib modules after installing opencv
I decided use some extra modules of opencv so i should install OPENCV_CONTRIB firstly,
I Downloaded contrib from this github repo. and extracted the same directory which i installed opencv.

```<code>opencv files : /programs/opencv3.0
opencv build:  /programs/opencv3.0/build
contrib folder:/programs/opencv3.0/opencv_contrib_master
</code>```

and then i added extra module path in CMake and while i press Configure button, i got an error:
Error in configuration process, project files may be invalid

and in the bottom window there is this error:

```<code>CMake Error at opencv_contrib-master/modules/dnn/cmake/OpenCVFindLibProtobuf.cmake:32 (ocv_download):
  Unknown CMake command "ocv_download".
Call Stack (most recent call first):
  opencv_contrib-master/modules/dnn/CMakeLists.txt:5 (include)
</code>```

please help me!

答:
You're trying to install contrib modules, which were released in 3.1 and changed a lot in 3.2. (google protobuff for nn is new feature)
So it might be a problem to build it now.
I built 3.2 with contrib on friday and it worked well. Just follow this tutorial very carefully  : http://docs.opencv.org/3.2.0/d3/d52/tutorial_windows_install.html </p>

Body:
I decided use some extra modules of opencv so i should install OPENCV_CONTRIB firstly,
I Downloaded contrib from this github repo. and extracted the same directory which i installed opencv.

opencv files : /programs/opencv3.0
opencv build:  /programs/opencv3.0/build
contrib folder:/programs/opencv3.0/opencv_contrib_master

and then i added extra module path in CMake and while i press Configure button, i got an error:
Error in configuration process, project files may be invalid

and in the bottom window there is this error:

CMake Error at opencv_contrib-master/modules/dnn/cmake/OpenCVFindLibProtobuf.cmake:32 (ocv_download):
  Unknown CMake command "ocv_download".
Call Stack (most recent call first):
  opencv_contrib-master/modules/dnn/CMakeLists.txt:5 (include)

please help me!


问:
Why is the width of my footer not reaching the full width on smartphone? I'm using Wordpress
I have a footer styled for my Wordpress site, which is not appearing to reach the full width of the site on mobile. Also, I am always able to scroll width ways, as if the site is wider than the mobile viewport. This only happens on mobile portrait, not on desktop or tablet.

I have all widths set to 100% (the header, the body, the footer and several others) but it seems the footer width renders as 1333px width whereas the header and body widths render as 1349px (as in inspect dev tools on laptop).

I have no fixed widths for any elements set in pixels of over 300px.

The footer is placed outside of the main and the main container but within the body.

I don't think any of the elements within the footer are the problem, as I have removed them and replaced them but the same problem still exists.

Photo included: Gap to right of footer

答:
Hi Hazem and thank you for your reply again. Update: I now know what was causing this problem. A left margin set in pixels on my content div that was set to 80% width was adding to the gap to the right of the footer, but only on mobile view. I then realised that my media queries were not working but I have now sorted that out, hence I have sorted the problem.
Thank you for your help.</p>


问:
side by side plotting in r for factors with same levels
Data looks like this-

```<code>ID  Day_start Day_end
1 Sa Sa
2 Sa Tu
3 Sa Tu
3 Sa NA
3 Tu Tr
</code>```

I want to get a side by side bar chart with frequency comparison of different days of Day_start and Day_end.
barplot looks for a vector or matrix but Day_start and Day_end are factors.

答:
If you want two separate barcharts next to each other you can use barplot() & table() in base R.

```<code>my_df <- read.table(text="ID  Day_start Day_end
                           1         Sa      Sa
                           2         Sa      Tu
                           3         Sa      Tu
                           3         Sa      NA
                           3         Tu      Tr", header=T)

par(mfrow=c(1,2))
barplot(table(my_df$Day_start))
barplot(table(my_df$Day_end))
par(mfrow=c(1,1))
</code>```

output

If you want a grouped barchart you can use ggplot2 (here I also use tidyr's gather() to convert the data to long format).  If you want to show empty space where there's a zero count you can view this SO question

```<code>library(ggplot2)
long_df <- tidyr::gather(my_df, day_cat, day, -ID)

ggplot(long_df, aes(x=factor(day), fill = day_cat)) +
  geom_bar(position = "dodge")
</code>```

output

Body:
Data looks like this-

ID  Day_start Day_end
1 Sa Sa
2 Sa Tu
3 Sa Tu
3 Sa NA
3 Tu Tr

I want to get a side by side bar chart with frequency comparison of different days of Day_start and Day_end.
barplot looks for a vector or matrix but Day_start and Day_end are factors.

Body:
If you want two separate barcharts next to each other you can use barplot() & table() in base R.

my_df <- read.table(text="ID  Day_start Day_end
                           1         Sa      Sa
                           2         Sa      Tu
                           3         Sa      Tu
                           3         Sa      NA
                           3         Tu      Tr", header=T)

par(mfrow=c(1,2))
barplot(table(my_df$Day_start))
barplot(table(my_df$Day_end))
par(mfrow=c(1,1))

output

If you want a grouped barchart you can use ggplot2 (here I also use tidyr's gather() to convert the data to long format).  If you want to show empty space where there's a zero count you can view this SO question

library(ggplot2)
long_df <- tidyr::gather(my_df, day_cat, day, -ID)

ggplot(long_df, aes(x=factor(day), fill = day_cat)) +
  geom_bar(position = "dodge")

output


问:
Vertical bar in Python bitwise assignment operator
There is a code and in class' method there is a line:

```<code>object.attribute |= variable
</code>```

I can't understand what it means. I didn't find (|=) in the list of basic Python operators.

答:
For an integer this would correspond to Python's "bitwise or" method. So in the below example we take the bitwise or of 4 and 1 to get 5 (or in binary 100 | 001 = 101):

```<code>Python 3.5.2 (default, Nov 17 2016, 17:05:23)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
    >>> a = 4
    >>> bin(a)
    '0b100'
    >>> a |= 1
    >>> bin(a)
    '0b101'
    >>> a
    5
</code>```

More generalised (as Alejandro says) is to call an object's or method, which can be defined for a class in the form:

```<code>def __or__(self, other):
    # your logic here
    pass
</code>```

So in the specific case of an integer, we are calling the or method which resolves to a bitwise or, as defined by Python.

Body:
There is a code and in class' method there is a line:

object.attribute |= variable

I can't understand what it means. I didn't find (|=) in the list of basic Python operators.

Body:
For an integer this would correspond to Python's "bitwise or" method. So in the below example we take the bitwise or of 4 and 1 to get 5 (or in binary 100 | 001 = 101):

Python 3.5.2 (default, Nov 17 2016, 17:05:23)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
    >>> a = 4
    >>> bin(a)
    '0b100'
    >>> a |= 1
    >>> bin(a)
    '0b101'
    >>> a
    5

More generalised (as Alejandro says) is to call an object's or method, which can be defined for a class in the form:

def __or__(self, other):
    # your logic here
    pass

So in the specific case of an integer, we are calling the or method which resolves to a bitwise or, as defined by Python.


问:
Typescript React stateless function with generic parameter/return types
How to define generic type in React stateless components based on parameter, or outside configuration?

Example component:

```<code>interface IProps<V> {
  value: V;
  doSomething: (val: V) => void;
}

const Comp: React.SFC<IProps<number>> = <T extends number>({
   value: T,
   doSomething
  }) => {
 return <div />;
}
</code>```

Above example will work, but only with numbers as values.

Is possible to do upgrade to achieve something like:

```<code>const Comp: React.SFC<IProps<??>> = <?? extends string | number>({
   value, /* of type ?? */
   doSomething
  }) => {
 return <div />;
}
</code>```

So that we can decide whatever we want numbers, or strings when using component.

Desired usage:

```<code>// This should setup generic type to string
<Comp value="string" ... />

// Or number
<Comp value={123} ... />

// Should be compilation error as we cannot use * on 'text' * 5
<Comp value="text" doSomething={val => val * 5} />
</code>```

Edit: Should do same job as function does:

```<code> function Comp <T>({value, doSomething}: IProps<T>) { ... }
</code>```

SFC Type has definition:

```<code>interface SFC<P> {
  (props: P & { children?: ReactNode }, context?: any): ReactElement<any>;
  ...
}
</code>```

答:
I was able to do this in TS 2.3. The point is to use 2 types for "inside" and "outside" of that component.</p>

```<code>interface IProps<V> {
    value: V;
    doSomething(val: V): void;
}

// type "inside" component
function _Comp<T>(props: IProps<T>) {
    return <div />;
}

// type for "outside" of component
interface GenericsSFC extends React.SFC<any> {
    <T>(props: IProps<T> & { children?: React.ReactNode }, context?: any): JSX.Element;
}

const Comp = _Comp as GenericsSFC;

// dont type check: v is of type "hey"
<Comp value={"hey"} doSomething={v => v - 1} />;
</code>```

Body:
How to define generic type in React stateless components based on parameter, or outside configuration?

Example component:

interface IProps<V> {
  value: V;
  doSomething: (val: V) => void;
}

const Comp: React.SFC<IProps<number>> = <T extends number>({
   value: T,
   doSomething
  }) => {
 return
;
}

Above example will work, but only with numbers as values.

Is possible to do upgrade to achieve something like:

const Comp: React.SFC<IProps<??>> = <?? extends string | number>({
   value, /* of type ?? */
   doSomething
  }) => {
 return
;
}

So that we can decide whatever we want numbers, or strings when using component.

Desired usage:

// This should setup generic type to string
<Comp value="string" ... />

// Or number
<Comp value={123} ... />

// Should be compilation error as we cannot use * on 'text' * 5
<Comp value="text" doSomething={val => val * 5} />

Edit: Should do same job as function does:

 function Comp <T>({value, doSomething}: IProps<T>) { ... }

SFC Type has definition:

interface SFC
 {
  (props: P & { children?: ReactNode }, context?: any): ReactElement<any>;
  ...
}

Body:
I was able to do this in TS 2.3. The point is to use 2 types for "inside" and "outside" of that component.

interface IProps<V> {
    value: V;
    doSomething(val: V): void;
}

// type "inside" component
function _Comp<T>(props: IProps<T>) {
    return <div />;
}

// type for "outside" of component
interface GenericsSFC extends React.SFC<any> {
    <T>(props: IProps<T> & { children?: React.ReactNode }, context?: any): JSX.Element;
}

const Comp = _Comp as GenericsSFC;

// dont type check: v is of type "hey"
<Comp value={"hey"} doSomething={v => v - 1} />;


答: Transferred from comments.  Likely the datetimes are slightly off in the two objects.  Use Date class instead of POSIXct to avoid that possibility.</p>

Title: merging xts series, times not lining up

Body:
I have two xts series I'm trying to merge:

ap1:

                ia       il
1997-01-01 12200000 11200000
1998-01-01 12500000 10600000
1999-01-01 12100000 10800000
2000-01-01 12300000 11200000
2001-01-01 11700000 11000000

apT:

               usa
1997-01-01 79537000
1998-01-01 80165000
1999-01-01 77386000
2000-01-01 79551000
2001-01-01 75702000

But after merge(apT, ap1)

it returns:

                usa       ia       il
1997-01-01 79537000       NA       NA
1997-01-01       NA 12200000 11200000
1998-01-01 80165000       NA       NA
1998-01-01       NA 12500000 10600000
1999-01-01 77386000       NA       NA
1999-01-01       NA 12100000 10800000
2000-01-01 79551000       NA       NA
2000-01-01       NA 12300000 11200000
2001-01-01 75702000       NA       NA
2001-01-01       NA 11700000 11000000

Why aren't the days lining up? I checked the timezones and they both return "America/New_York"


问:
Form issues sending an id to a new page for $_GET
Having trouble getting the $row['post_topic'] to actually pass the id over to reply page. If I input an ID manually, for example '2', it works absolutely fine.

```<code>echo '<form method="post" action="reply.php?id=' .$row['post_topic']. '">
          <textarea name="reply-content"></textarea>
          <input type="submit" value="Replyy" />
      </form>';
</code>```

Edit

An extra note, echo $row['post_topic']; works inside one of the While loops I have in the same file.

Query:

```<code>$sql= "SELECT
           posts.post_topic,
           posts.post_content,
           posts.post_date,
           posts.post_by,
           users.user_id,
           users.user_name
       FROM
           posts
       LEFT JOIN
           users
       ON
           posts.post_by = users.user_id
       WHERE
           posts.post_topic =
              '" .mysqli_real_escape_string($connect, $_GET['id']). "'";
</code>```

PHP:

```<code>$row = $resultpost->fetch_assoc();

echo $row['post_topic'];

echo '<br><table border="0"';
  echo '<tr>';
    echo '<th>';
      echo '<form method="post" action="reply.php?id='.$row['post_topic']. '">
                 <textarea name="reply-content"></textarea>
                 <input type="submit" value="Reply" />
            </form>';
    echo '</th>';
  echo '</tr>';
</code>```

答: Check the data type using gettype($row['post_topic']). This may be the issue.

Body:
Having trouble getting the $row['post_topic'] to actually pass the id over to reply page. If I input an ID manually, for example '2', it works absolutely fine.

echo '<form method="post" action="reply.php?id=' .$row['post_topic']. '">
          <textarea name="reply-content"></textarea>
          <input type="submit" value="Replyy" />
      </form>';

Edit

An extra note, echo $row['post_topic']; works inside one of the While loops I have in the same file.

Query:

$sql= "SELECT
           posts.post_topic,
           posts.post_content,
           posts.post_date,
           posts.post_by,
           users.user_id,
           users.user_name
       FROM
           posts
       LEFT JOIN
           users
       ON
           posts.post_by = users.user_id
       WHERE
           posts.post_topic =
              '" .mysqli_real_escape_string($connect, $_GET['id']). "'";

PHP:

$row = $resultpost->fetch_assoc();

echo $row['post_topic'];

echo '
<table border="0"';
  echo '
';
    echo '';
      echo '<form method="post" action="reply.php?id='.$row['post_topic']. '">
                 <textarea name="reply-content"></textarea>
                 <input type="submit" value="Reply" />
            </form>';
    echo '	';
  echo '
';


问:
How to get maven version in Jenkins pipeline
I am creating CI pipeline with Jenkins. Need to tag the docker images with the Maven version of the project, e.g. 0.0.1-SNAPSHOT.

Although, maven version is exposed as POM_VERSION based on this Jenkins issue, it seems to apply only to the "Maven project". I tried to use the variable in Pipeline's Jenkins file as ${POM_VERSION} and it did not recognize the property.

What is the best way to get the version number? Parse the pom.xml and grep the version with a bash script and call it inside Jenkinsfile?

答:
You can tag docker image with project version using Spotify docker maven plugin as follows :</p>

```<code><imageTags>
    <imageTag>${project.version}</imageTag>
    <imageTag>latest</imageTag>
</imageTags>

<imageName>${image.suffix}/${project.artifactId}:${project.version}</imageName>
</code>```

Body:
You can tag docker image with project version using Spotify docker maven plugin as follows :

<imageTags>
    <imageTag>${project.version}</imageTag>
    <imageTag>latest</imageTag>
</imageTags>

<imageName>${image.suffix}/${project.artifactId}:${project.version}</imageName>


问:
add a different random number to every cell in a pandas dataframe
I need to add some 'noise' to my data, so I would like to add a different random number to every cell in my pandas dataframe.  This code works, but seems unpythonic.  Is there a better way?</p>

```<code>import pandas as pd
import numpy as np
df = pd.DataFrame(0.0, index=[1,2,3,4,5], columns=list('ABC') )
print df
for x,line in df.iterrows():
  for col in df:
     line[col] = line[col] + (np.random.rand()-0.5)/1000.0
 print df
</code>```

答:
For nonzero data:

```<code>df + (np.random.rand(df.shape)-0.5)*0.001
</code>```

OR

```<code>df + np.random.uniform(-0.01,0.01,(df.shape)))
</code>```

For cases where your data frame contains zeros that you wish to keep as zero:

```<code>df * (1 + (np.random.rand(df.shape)-0.5)*0.001)
</code>```

OR

```<code>df * (1 + np.random.uniform(-0.01,0.01,(df.shape)))
</code>```

I think either of these should work, its a case of generating a same size "dataframe" (or perhaps array of arrays) as your existing df and adding it to your existing df (multiplying by 1 + random for cases where you wish zeros to remain zero). With the uniform function you can determine the scale of your noise by altering the 0.01 variable.

Body:
I need to add some 'noise' to my data, so I would like to add a different random number to every cell in my pandas dataframe.  This code works, but seems unpythonic.  Is there a better way?

import pandas as pd
import numpy as np
df = pd.DataFrame(0.0, index=[1,2,3,4,5], columns=list('ABC') )
print df
for x,line in df.iterrows():
  for col in df:
     line[col] = line[col] + (np.random.rand()-0.5)/1000.0
 print df

Body:
For nonzero data:

df + (np.random.rand(df.shape)-0.5)*0.001

OR

df + np.random.uniform(-0.01,0.01,(df.shape)))

For cases where your data frame contains zeros that you wish to keep as zero:

df * (1 + (np.random.rand(df.shape)-0.5)*0.001)

OR

df * (1 + np.random.uniform(-0.01,0.01,(df.shape)))

I think either of these should work, its a case of generating a same size "dataframe" (or perhaps array of arrays) as your existing df and adding it to your existing df (multiplying by 1 + random for cases where you wish zeros to remain zero). With the uniform function you can determine the scale of your noise by altering the 0.01 variable.


问:
regex for javascript pattern
```<code><input type="text" name="address" pattern="[0-9a-zA-Z ,\.\/\-&']{0,}">
</code>```

<p>It will allow all except of few special characters but i don't want '//' '///' or any special character repetition like this. what should i change ? </p>

答:
You can add a negative lookahead to check repetition :

(?!.*([ ,./&'-])\1)[0-9a-zA-Z ,./&'-]*

This will reject strings with a space, ,, ., /, &, ', or - repeated.

Title: regex for javascript pattern

Body:
<input type="text" name="address" pattern="[0-9a-zA-Z ,\.\/\-&']{0,}">

It will allow all except of few special characters but i don't want '//' '///' or any special character repetition like this. what should i change ?