问:
Boost tribool question about logical operations
Recently, I used boost::logic::tribool and something was strange for me.

```<code>#include <iostream>
#include "boost/logic/tribool.hpp"

int main()
{
    boost::logic::tribool test = true && boost::logic::indeterminate;

    if(test)
    {
     std::cout << "Executes?" << std::endl;
    }

    if (true && boost::logic::indeterminate)
    {
      std::cout << "Executes 2" << std::endl;
    }

}
</code>```

Prints Executes and Executes 2.
Why are these conditions true?
I was totally sure that AND operation with (indeterminate state, true) returns indeterminate state?

Quote from boost.org about boolean context in if

"returns true if the 3-state boolean is true, false otherwise"

EDIT: after comments I am adding this.
This is the most non-intuitive code I have ever read.

```<code>#include <iostream>
#include "boost/logic/tribool.hpp"

int main()
{
    boost::logic::tribool test = boost::logic::tribool(true) && boost::logic::indeterminate;

    if(test)
    {
     std::cout << "This will NOT execute" << std::endl;
    }

    boost::logic::tribool second = true && boost::logic::indeterminate;

    if (second)
    {
      std::cout << "This will execute" << std::endl;
    }

}
</code>```

EDIT2: I need to correct myself...
Anyone could explain?

```<code>#include <iostream>
#include "boost/logic/tribool.hpp"

boost::logic::tribool LOL( )
{
   return    boost::logic::indeterminate;
}

int main()
{

 boost::logic::tribool LOL_RESULT = LOL();

    if (boost::logic::indeterminate)
    {
        std::cout << "IT WILL BE EXECUTED" << std::endl;
    }

    if (LOL_RESULT)
    {
      std::cout << "IT WILL NOT BE EXECUTED"   << std::endl;
    }
}
</code>```

答:
```<code>TEST(junk, tribool)
{
    auto v = boost::logic::indeterminate;
    GTEST_MESSAGE() << typeid(v).name();
}

</code>```

Results in:

```<code>[----------] 1 test from junk
[ RUN      ] junk.tribool
[   NOTE   ] bool (__cdecl*)(class boost::logic::tribool,struct boost::logic::detail::indeterminate_t)
</code>```

boost::logic::indeterminate is a function. So it evaluates to true.

```<code>TEST(junk, tribool)
{
    boost::logic::tribool test = true && boost::logic::tribool{ boost::logic::indeterminate_keyword_t() };

    if (test)
    {
        GTEST_MESSAGE() << "Executes?" << std::endl;
    }

    if (true && boost::logic::tribool{ boost::logic::indeterminate_keyword_t() })
    {
        GTEST_MESSAGE() << "Executes 2" << std::endl;
    }
}
</code>```

Results in:

```<code>[----------] 1 test from junk
[ RUN      ] junk.tribool
[       OK ] junk.tribool (64970 ms)
[----------] 1 test from junk (68580 ms total)
</code>```

Body:
Recently, I used boost::logic::tribool and something was strange for me.

#include <iostream>
#include "boost/logic/tribool.hpp"

int main()
{
    boost::logic::tribool test = true && boost::logic::indeterminate;

    if(test)
    {
     std::cout << "Executes?" << std::endl;
    }

    if (true && boost::logic::indeterminate)
    {
      std::cout << "Executes 2" << std::endl;
    }

}

Prints Executes and Executes 2.
Why are these conditions true?
I was totally sure that AND operation with (indeterminate state, true) returns indeterminate state?

Quote from boost.org about boolean context in if

"returns true if the 3-state boolean is true, false otherwise"

EDIT: after comments I am adding this.
This is the most non-intuitive code I have ever read.

#include <iostream>
#include "boost/logic/tribool.hpp"

int main()
{
    boost::logic::tribool test = boost::logic::tribool(true) && boost::logic::indeterminate;

    if(test)
    {
     std::cout << "This will NOT execute" << std::endl;
    }

    boost::logic::tribool second = true && boost::logic::indeterminate;

    if (second)
    {
      std::cout << "This will execute" << std::endl;
    }

}

EDIT2: I need to correct myself...
Anyone could explain?

#include <iostream>
#include "boost/logic/tribool.hpp"

boost::logic::tribool LOL( )
{
   return    boost::logic::indeterminate;
}

int main()
{

 boost::logic::tribool LOL_RESULT = LOL();

    if (boost::logic::indeterminate)
    {
        std::cout << "IT WILL BE EXECUTED" << std::endl;
    }

    if (LOL_RESULT)
    {
      std::cout << "IT WILL NOT BE EXECUTED"   << std::endl;
    }
}

Body:
TEST(junk, tribool)
{
    auto v = boost::logic::indeterminate;
    GTEST_MESSAGE() << typeid(v).name();
}

Results in:

[----------] 1 test from junk
[ RUN      ] junk.tribool
[   NOTE   ] bool (__cdecl*)(class boost::logic::tribool,struct boost::logic::detail::indeterminate_t)

boost::logic::indeterminate is a function. So it evaluates to true.

TEST(junk, tribool)
{
    boost::logic::tribool test = true && boost::logic::tribool{ boost::logic::indeterminate_keyword_t() };

    if (test)
    {
        GTEST_MESSAGE() << "Executes?" << std::endl;
    }

    if (true && boost::logic::tribool{ boost::logic::indeterminate_keyword_t() })
    {
        GTEST_MESSAGE() << "Executes 2" << std::endl;
    }
}

Results in:

[----------] 1 test from junk
[ RUN      ] junk.tribool
[       OK ] junk.tribool (64970 ms)
[----------] 1 test from junk (68580 ms total)


来源: stackexchange

问:
How to group arrays in array by first element object key
Got an array of arrays like this:

```<code>    let arr = [
      [
        {"key":2, "other":123},
        {"key":2, "other":222}
      ],
      [
        {"key":3, "other":0}
      ],
      [
        {"key":1, "other":11},
        {"key":1, "other":23}
      ],
      [
        {"key":1, "other":22}
      ]
    ]
</code>```

I need to get this arr but with grouped arrays with the same "key" value of the first element so it will be look like:

```<code>  let arr = [
      [
        {"key":2, "other":123},
        {"key":2, "other":222}
      ],
      [
        {"key":3, "other":0}
      ],
      [
        [
          {"key":1, "other":11},
          {"key":1, "other":23}
        ],
        [
          {"key":1, "other":22}
        ]
      ],

    ]
</code>```

I tried to use reduce function, but the result was totally different.

```<code>let final = []
  for (let i=0; i<arr.length; i++) {

    let arr1 = i==0?arr:arr.slice(i)

    let final1 = arr1.reduce((acc,x)=> {

      acc = acc[0].key==x[0].key?acc.concat(x):acc
      return acc
    })
    arr1.length>1&&final.push(final1)
  }
</code>```

In this code the problem is that it compares arr[1] with arr[2], arr[3] and then again arr[2] with arr[3] and groups it(even though arr[1].key and arr[2].key and arr[3].key are the same) Can you give some tips or give the final function to do this?

答:
I think you want something like this, try running the snippet

let arr = [
    [
        {
            "key": 2
        },
        {
            "key": 2
        }
    ],
    [
        {
            "key": 3
        }
    ],
    [
        {
            "key": 1
        },
        {
            "key": 1
        }
    ],
    [
        {
            "key": 1
        }
    ]
]

let result = arr.reduce((res, array) => {
    array.forEach((value, index) => {
        const obj = res.find(a => {
            return !!a.find(({key}) => {
                return key === value.key
            })
        })
        if (obj) {
            obj.push(value)
        } else {
            res.push([value])
        }
    })
    return res;
}, [])

console.log(result);```

ContentLicense: CC BY-SA 4.0

Body:
Got an array of arrays like this:

    let arr = [
      [
        {"key":2, "other":123},
        {"key":2, "other":222}
      ],
      [
        {"key":3, "other":0}
      ],
      [
        {"key":1, "other":11},
        {"key":1, "other":23}
      ],
      [
        {"key":1, "other":22}
      ]
    ]

I need to get this arr but with grouped arrays with the same "key" value of the first element so it will be look like:

  let arr = [
      [
        {"key":2, "other":123},
        {"key":2, "other":222}
      ],
      [
        {"key":3, "other":0}
      ],
      [
        [
          {"key":1, "other":11},
          {"key":1, "other":23}
        ],
        [
          {"key":1, "other":22}
        ]
      ],

    ]

I tried to use reduce function, but the result was totally different.

let final = []
  for (let i=0; i<arr.length; i++) {

    let arr1 = i==0?arr:arr.slice(i)

    let final1 = arr1.reduce((acc,x)=> {

      acc = acc[0].key==x[0].key?acc.concat(x):acc
      return acc
    })
    arr1.length>1&&final.push(final1)
  }

In this code the problem is that it compares arr[1] with arr[2], arr[3] and then again arr[2] with arr[3] and groups it(even though arr[1].key and arr[2].key and arr[3].key are the same) Can you give some tips or give the final function to do this?


问:
Must declare the scalar variable "@id". Creating stored procedure with SQL Server
I am trying to create a stored procedure for updating a table according to id given but it is showing me error

```<code>CREATE PROCEDURE updateCategoryPro
    (@categoryName VARCHAR(64),
     @IsActive BIT,
     @IsSelected BIT,
     @mediaId INT,
     @pageTitle VARCHAR(128),
     @metaKeyword VARCHAR(512),
     @metaDescription VARCHAR(256),
     @createDate DATETIME,
     @createdBy INT,
     @updatedDate DATETIME,
     @updatedBy INT)
AS
BEGIN
    UPDATE CategoryMaster
    SET categoryName = @categoryName,
        @IsActive = IsActive,
        @IsSelected = IsSelected,
        @mediaId = mediaId,
        pageTitle = @pageTitle,
        metaKeyword = @metaKeyword,
        metaDescription = @metaDescription,
        @createDate = createDate,
        @createdBy = createdBy,
        @updatedDate = updatedDate,
        @updatedBy = updatedBy
    WHERE categoryId = @id
END
</code>```

Getting error at @id

答:
To validate your query result based on specific ID, you have to take it from the input of the procedure as below</p>

```<code>CREATE PROCEDURE updateCategoryPro
    @id int,
    @categoryName varchar(64),
    @IsActive bit,
    @IsSelected bit,
    @mediaId int,
    @pageTitle varchar(128),
    @metaKeyword varchar(512),
    @metaDescription varchar(256),
    @createDate datetime,
    @createdBy int,
    @updatedDate datetime,
    @updatedBy int
AS
BEGIN
    UPDATE CategoryMaster
    SET categoryName=@categoryName,
        IsActive = @IsActive,
        IsSelected = @IsSelected,
        mediaId = @mediaId,
        pageTitle=@pageTitle,
        metaKeyword=@metaKeyword,
        metaDescription=@metaDescription,
        createDate = @createDate,
        createdBy = @createdBy,
        updatedDate = @updatedDate,
        updatedBy = @updatedBy
    WHERE categoryId = @id
End
</code>```

Body:
I am trying to create a stored procedure for updating a table according to id given but it is showing me error

CREATE PROCEDURE updateCategoryPro
    (@categoryName VARCHAR(64),
     @IsActive BIT,
     @IsSelected BIT,
     @mediaId INT,
     @pageTitle VARCHAR(128),
     @metaKeyword VARCHAR(512),
     @metaDescription VARCHAR(256),
     @createDate DATETIME,
     @createdBy INT,
     @updatedDate DATETIME,
     @updatedBy INT)
AS
BEGIN
    UPDATE CategoryMaster
    SET categoryName = @categoryName,
        @IsActive = IsActive,
        @IsSelected = IsSelected,
        @mediaId = mediaId,
        pageTitle = @pageTitle,
        metaKeyword = @metaKeyword,
        metaDescription = @metaDescription,
        @createDate = createDate,
        @createdBy = createdBy,
        @updatedDate = updatedDate,
        @updatedBy = updatedBy
    WHERE categoryId = @id
END

Getting error at @id

Body:
To validate your query result based on specific ID, you have to take it from the input of the procedure as below

CREATE PROCEDURE updateCategoryPro
    @id int,
    @categoryName varchar(64),
    @IsActive bit,
    @IsSelected bit,
    @mediaId int,
    @pageTitle varchar(128),
    @metaKeyword varchar(512),
    @metaDescription varchar(256),
    @createDate datetime,
    @createdBy int,
    @updatedDate datetime,
    @updatedBy int
AS
BEGIN
    UPDATE CategoryMaster
    SET categoryName=@categoryName,
        IsActive = @IsActive,
        IsSelected = @IsSelected,
        mediaId = @mediaId,
        pageTitle=@pageTitle,
        metaKeyword=@metaKeyword,
        metaDescription=@metaDescription,
        createDate = @createDate,
        createdBy = @createdBy,
        updatedDate = @updatedDate,
        updatedBy = @updatedBy
    WHERE categoryId = @id
End


问:
ERROR: Couldn't connect to Docker daemon at http+docker://localhost - is it running?
I have a problem when trying to build or compile an environment with Docker Compose on an AWS instance. I have followed the steps of the official documentation for the installation of docker-compose and theoretically it installs without errors. The problem occurs when I run the docker-compose build command within my Dockerized environment.

Here's the installation tutorial I followed:

Error code:

ERROR: Couldn't connect to Docker daemon at http+docker://localhost - is it running?

If it's at a non-standard location, specify the URL with the DOCKER_HOST environment variable.

Error image:

答:
Firstly
Check with the following commands below:

docker-compose -version result in docker-compose version xx.xx, build yy12

docker -v result in Docker version xxx.xx, build yy12

If the above is okay then you either have to set up docker for non super users please read here Manage Docker as a non-root user

Or run docker-composer commands as a root user E.g sudo  docker-compose up or sudo  docker-compose start

Please note that xx.xx and yy12  are hypothetical


问:
Apply a function to all pairs in the same group
I want to apply a function to all pairs of items in the same group e.g.

Example input:

```<code>Group  Item   Value
A      1       89
A      2       76
A      3       2
B      4       21
B      5       10
</code>```

The desired output is a vector of the function output for all items in the same group.

e.g. for arguments sake if the function was:

```<code>addnums=function(x,y){
  x+y
}
</code>```

Then the desired output would be:

165, 91, 78, 31

I have tried to do this using summarize in the dplyr package but this can only be used if the output is a single value.

答:
We can split Value for each Group and then use combn to calculate sum for each pair.

```<code>sapply(split(df$Value, df$Group), combn, 2, sum)

#$A
#[1] 165  91  78

#$B
#[1] 31
</code>```

If needed as one vector we can use unlist.

```<code>unlist(sapply(split(df$Value, df$Group), combn, 2, sum), use.names = FALSE)
#[1] 165  91  78  31
</code>```

If you are interested in tidyverse solution using the same logic we can do

```<code>library(dplyr)
library(purrr)

df %>%
  group_split(Group) %>%
  map(~combn(.x %>% pull(Value), 2, sum)) %>% flatten_dbl

#[1] 165  91  78  31
</code>```

Body:
I want to apply a function to all pairs of items in the same group e.g.

Example input:

Group  Item   Value
A      1       89
A      2       76
A      3       2
B      4       21
B      5       10

The desired output is a vector of the function output for all items in the same group.

e.g. for arguments sake if the function was:

addnums=function(x,y){
  x+y
}

Then the desired output would be:

165, 91, 78, 31

I have tried to do this using summarize in the dplyr package but this can only be used if the output is a single value.

Body:
We can split Value for each Group and then use combn to calculate sum for each pair.

sapply(split(df$Value, df$Group), combn, 2, sum)

#$A
#[1] 165  91  78

#$B
#[1] 31

If needed as one vector we can use unlist.

unlist(sapply(split(df$Value, df$Group), combn, 2, sum), use.names = FALSE)
#[1] 165  91  78  31

If you are interested in tidyverse solution using the same logic we can do

library(dplyr)
library(purrr)

df %>%
  group_split(Group) %>%
  map(~combn(.x %>% pull(Value), 2, sum)) %>% flatten_dbl

#[1] 165  91  78  31


问:
How to print $1, $2 and then all remaining parameters together in AWK
I'm making a script that generates aliases/abbreviations from a base file. The base file structure is something like this:

```<code>sctl   sudo         systemctl
pac    sudo         pacman
</code>```

This works fine with the following code that reads the base file, removes comments and awks the abbreviation line on the abbreviation file:

```<code>    sed "s/\s*#.*$//;/^\s*$/d" $command_file |
    awk -v c=$cmd -v o="$comp" '{ print c" "$1""o"\""$2" "$3"\"" }' >> $file
</code>```

And the end result would be something like this:

```<code>abbr sctl "sudo systemctl"
abbr pac "sudo pacman"
</code>```

But this code doesn't work when the line has many parts after the 3rd parameter:

```<code>svu    playerctl    -p spotify volume +0.05
</code>```

How can i go about printing in that format? $1 $2 ($3..$N)

答:
You can erase the first two fields and trim the space from the remainder, eg.

```<code>{
  printf "%s %s ", $1, $2
  $1=$2=""; sub(/^\s*/, "", $0);
  printf "\"%s\"\n", $0
}
</code>```

With output like,

```<code>svu playerctl "-p spotify volume +0.05"
</code>```

Note: the \s regex requires gnu awk as pointed out by Ed Morton.

Body:
I'm making a script that generates aliases/abbreviations from a base file. The base file structure is something like this:

sctl   sudo         systemctl
pac    sudo         pacman

This works fine with the following code that reads the base file, removes comments and awks the abbreviation line on the abbreviation file:

    sed "s/\s*#.*$//;/^\s*$/d" $command_file |
    awk -v c=$cmd -v o="$comp" '{ print c" "$1""o"\""$2" "$3"\"" }' >> $file

And the end result would be something like this:

abbr sctl "sudo systemctl"
abbr pac "sudo pacman"

But this code doesn't work when the line has many parts after the 3rd parameter:

svu    playerctl    -p spotify volume +0.05

How can i go about printing in that format? $1 $2 ($3..$N)

Body:
You can erase the first two fields and trim the space from the remainder, eg.

{
  printf "%s %s ", $1, $2
  $1=$2=""; sub(/^\s*/, "", $0);
  printf "\"%s\"\n", $0
}

With output like,

svu playerctl "-p spotify volume +0.05"

Note: the \s regex requires gnu awk as pointed out by Ed Morton.


问:
Using Ansible copy module for remote to remote file transfer (same remote host)
I'm trying to move all files under a specific remote directory to another remote directory - on the same remote host - using Ansible's copy module.

The directory, and files, do exist on the remote host and I thought I'd use the Ansible copy module with remote_src: yes in order to achieve this.

However, so far I have been running into unforeseen issues with this approach - any help is appreciated, thank you!!

Task of concern

```<code>- name: copy remote to remote (same host)
  copy:
    src: "{{ item }}"
    dest: "{{ dir_base_path }}/go/to/my/nested/path"
    remote_src: yes
    owner: "{{ owner }}"
    group: "{{ group }}"
    mode: preserve
  with_fileglob:
    - "{{ dir_base_path }}/stay/at/parent_dir/*"
  when: status.changed and dir.stat.exists
</code>```

Remote Directory structure

```<code>--> parent path
   -- all-the-files-I-need
   --`nested_directory
      -- need-to-copy-files here
</code>```

Error Observed

```<code>TASK [playbook: copy remote to remote (same host)] ****************************************************************************************
 [WARNING]: Unable to find 'base_path/stay/at/parent_dir/' in expected paths (use -vvvvv to see paths)
</code>```

Version Information

```<code>ansible --version
ansible 2.7.10
  config file = /etc/ansible/ansible.cfg
  configured module search path = ['/root/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/local/lib/python3.6/dist-packages/ansible
  executable location = /usr/local/bin/ansible
  python version = 3.6.7 (default, Oct 22 2018, 11:32:17) [GCC 8.2.0]
</code>```

答:
As per documentation for fileglob - Matching is against local system files on the Ansible controller. To iterate a list of files on a remote node, use the find module.
Refer: https://docs.ansible.com/ansible/latest/plugins/lookup/fileglob.html

You can first use find command to find the files and then store using register and then copy those files.

Body:
I'm trying to move all files under a specific remote directory to another remote directory - on the same remote host - using Ansible's copy module.

The directory, and files, do exist on the remote host and I thought I'd use the Ansible copy module with remote_src: yes in order to achieve this.

However, so far I have been running into unforeseen issues with this approach - any help is appreciated, thank you!!

Task of concern

- name: copy remote to remote (same host)
  copy:
    src: "{{ item }}"
    dest: "{{ dir_base_path }}/go/to/my/nested/path"
    remote_src: yes
    owner: "{{ owner }}"
    group: "{{ group }}"
    mode: preserve
  with_fileglob:
    - "{{ dir_base_path }}/stay/at/parent_dir/*"
  when: status.changed and dir.stat.exists

Remote Directory structure

--> parent path
   -- all-the-files-I-need
   --`nested_directory
      -- need-to-copy-files here

Error Observed

TASK [playbook: copy remote to remote (same host)] ****************************************************************************************
 [WARNING]: Unable to find 'base_path/stay/at/parent_dir/' in expected paths (use -vvvvv to see paths)

Version Information

ansible --version
ansible 2.7.10
  config file = /etc/ansible/ansible.cfg
  configured module search path = ['/root/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/local/lib/python3.6/dist-packages/ansible
  executable location = /usr/local/bin/ansible
  python version = 3.6.7 (default, Oct 22 2018, 11:32:17) [GCC 8.2.0]


问:
Why does it always return true?
Beginner question, sorry if it's not the right place to ask
Trying to learn how logic works in JS, can't figure this out

```<code>if (firstSymbol === "A" || "a" || "D" || "d") {
    if (secondSymbol === "z") {
        alert("It does!");
        break;
    }
}
</code>```

I expect it to say "It does!" and break in case if the firstSymbol is A, a, D or d AND the secondSymbol is z , but for some reason it says "It does!" and breaks regardless of what the firstSymbol is and only checks if the secondSymbol is z.

答:
Because you're checking whether "a" is true - it is always true:

console.log(!!"a");```
</div>
</div>
</p>

<p>You should be using <code>includes</code> and AND <code>&&</code> in this case:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const firstSymbol = "D";
const secondSymbol = "z";
if (["A", "a", "D", "d"].includes(firstSymbol) && secondSymbol == "z") {
  console.log("It does!");
}</code>```

Title: Why does it always return true?

Body:
Beginner question, sorry if it's not the right place to ask
Trying to learn how logic works in JS, can't figure this out

if (firstSymbol === "A" || "a" || "D" || "d") {
    if (secondSymbol === "z") {
        alert("It does!");
        break;
    }
}

I expect it to say "It does!" and break in case if the firstSymbol is A, a, D or d AND the secondSymbol is z , but for some reason it says "It does!" and breaks regardless of what the firstSymbol is and only checks if the secondSymbol is z.

Body:
Because you're checking whether "a" is true - it is always true:

console.log(!!"a");

You should be using includes and AND && in this case:

const firstSymbol = "D";
const secondSymbol = "z";
if (["A", "a", "D", "d"].includes(firstSymbol) && secondSymbol == "z") {
  console.log("It does!");
}


问:
How to read markdown code from a file from an R markdown document
I'm writing an application in R markdown with Shiny. In one page "Explore", I would show some interactive plots and in another "About" I would write some description of the app and its usage.

I want this section also to be the README file in the GitLab repository where it will be submitted, so it needs to be in markdown. I'm wondering if there is a way to call that README file from the R markdown document, so I do not need to maintain the same text in two files.

Let's consider the following example.

R markdown file

```<code>---
title: "Example"
runtime: shiny
vertical_layout: fill
output:
  flexdashboard::flex_dashboard:
    orientation: rows
---

```{r setup, include=FALSE}
library(shiny)
library(tidyverse)
```

Explore
======================================================================

### PLOT 1
```{r}
mtcars %>% ggplot(aes(x=mpg, y=cyl)) + geom_point()
```

### PLOT 2
```{r}
mtcars %>% ggplot(aes(x=mpg, y=qsec)) + geom_point()
```

About
============================================================================

#### README

A brief description of the document.
</code>```

I'm asking specifically if the two text lines under "About" could be substituted by some function that reads a markdown file. So that the following file could be used as README and as about section in the app.

Markdown file

```<code>#### README

A brief description of the document.
</code>```

答:
Suggestion using readLines.

Define a function to read the .md-file using readLines(), then replace empty lines with newlines, \n, finally concatenate and print using cat

```<code>pasteReadme <- function(fileName){

  breakFun <- function(x){
    #function to replace empty lines with newline.
    if(nchar(x) == 0){
      return("\n\n") #double newline to give same space as in the .md-file
    } else {
      return(x)
    }
  }

  storeLines <- readLines(fileName)

  cat(paste0(lapply(storeLines, FUN=function(x) breakFun(x)), collapse=""))

}
</code>```

Output in .Rmd using chunk options results = 'asis'. Have tested with images (i.e. ![](http://example.com/logo.png)) and normal HTML code. Should work for  most cases. See example bellow.

about.md

```<code><!-- #### README -->

<!-- A brief description of the document. -->

#### README

A brief description of the document.

This is some more about text

##### This logo is important for the project

![optional caption text](https://www.rstudio.com/wp-content/uploads/2016/09/RStudio-Logo-Blue-Gray-125.png)

Works with **bold** and *italics*

###### Another Header

<span style="color:blue">text is blue</span>
</code>```

.Rmd-file

```<code>---
title: "Example"
runtime: shiny
vertical_layout: fill
output:
  flexdashboard::flex_dashboard:
    orientation: rows
---

```{r setup, include=FALSE}
library(shiny)
library(tidyverse)

pasteReadme <- function(fileName){

  breakFun <- function(x){
    #function to replace empty lines with newline.
    if(nchar(x) == 0){
      return("\n\n") #double newline to give same space as in the .md-file
    } else {
      return(x)
    }
  }

  storeLines <- readLines(fileName)

  cat(paste0(lapply(storeLines, FUN=function(x) breakFun(x)), collapse=""))

}

```

Explore
======================================================================

### PLOT 1
```{r}
mtcars %>% ggplot(aes(x=mpg, y=cyl)) + geom_point()
```

### PLOT 2
```{r}
mtcars %>% ggplot(aes(x=mpg, y=qsec)) + geom_point()
```

About
============================================================================

```{r, results='asis'}
pasteReadme("about.md")
```
</code>```

Body:
I'm writing an application in R markdown with Shiny. In one page "Explore", I would show some interactive plots and in another "About" I would write some description of the app and its usage.

I want this section also to be the README file in the GitLab repository where it will be submitted, so it needs to be in markdown. I'm wondering if there is a way to call that README file from the R markdown document, so I do not need to maintain the same text in two files.

Let's consider the following example.

R markdown file

---
title: "Example"
runtime: shiny
vertical_layout: fill
output:
  flexdashboard::flex_dashboard:
    orientation: rows
---

```{r setup, include=FALSE}
library(shiny)
library(tidyverse)
```

Explore
======================================================================

### PLOT 1
```{r}
mtcars %>% ggplot(aes(x=mpg, y=cyl)) + geom_point()
```

### PLOT 2
```{r}
mtcars %>% ggplot(aes(x=mpg, y=qsec)) + geom_point()
```

About
============================================================================

#### README

A brief description of the document.

I'm asking specifically if the two text lines under "About" could be substituted by some function that reads a markdown file. So that the following file could be used as README and as about section in the app.

Markdown file

#### README

A brief description of the document.

Body:
Suggestion using readLines.

Define a function to read the .md-file using readLines(), then replace empty lines with newlines, \n, finally concatenate and print using cat

pasteReadme <- function(fileName){

  breakFun <- function(x){
    #function to replace empty lines with newline.
    if(nchar(x) == 0){
      return("\n\n") #double newline to give same space as in the .md-file
    } else {
      return(x)
    }
  }

  storeLines <- readLines(fileName)

  cat(paste0(lapply(storeLines, FUN=function(x) breakFun(x)), collapse=""))

}

Output in .Rmd using chunk options results = 'asis'. Have tested with images (i.e. ![](http://example.com/logo.png)) and normal HTML code. Should work for  most cases. See example bellow.

about.md

<!-- #### README -->

<!-- A brief description of the document. -->

#### README

A brief description of the document.

This is some more about text

##### This logo is important for the project

![optional caption text](https://www.rstudio.com/wp-content/uploads/2016/09/RStudio-Logo-Blue-Gray-125.png)

Works with **bold** and *italics*

###### Another Header

<span style="color:blue">text is blue</span>

.Rmd-file

---
title: "Example"
runtime: shiny
vertical_layout: fill
output:
  flexdashboard::flex_dashboard:
    orientation: rows
---

```{r setup, include=FALSE}
library(shiny)
library(tidyverse)

pasteReadme <- function(fileName){

  breakFun <- function(x){
    #function to replace empty lines with newline.
    if(nchar(x) == 0){
      return("\n\n") #double newline to give same space as in the .md-file
    } else {
      return(x)
    }
  }

  storeLines <- readLines(fileName)

  cat(paste0(lapply(storeLines, FUN=function(x) breakFun(x)), collapse=""))

}

```

Explore
======================================================================

### PLOT 1
```{r}
mtcars %>% ggplot(aes(x=mpg, y=cyl)) + geom_point()
```

### PLOT 2
```{r}
mtcars %>% ggplot(aes(x=mpg, y=qsec)) + geom_point()
```

About
============================================================================

```{r, results='asis'}
pasteReadme("about.md")
```


问:
How to create a conditional string that's based on two variables without a bunch of if elses (JavaScript)
I am trying to create a custom string to be shown to the user, which is based on two variables.

Here is the example that I am trying to build:

let url1;
let url2;
if (containsData1) {
  url1 = "http://test";
}

if (containsData2) {
  url2 = "http://test2";
}

let finalString = '';
if (url1 && url2) {
  finalString = 'The url 1 is ' + url1 + ' and url 2 is ' + url2;
} else if (!url1 && url2) {
  finalString = 'There isnt data for url1. Url2 is ' + url2;
} else if (url1 && !url2) {
  finalString = 'The url 1 is ' + url1 + '. There isnt data for url2';
} else if (!url1 && !url2) {
  finalString = 'There isnt data for url1. There isnt data for url2';
}
```

However I would like to this in a proper way, without using this bunch of if elses, any suggestions on how to accomplish this?

Thanks.

答:
You could use ternary statements:

let url1;
let url2;
url1 = "http://test";
url2 = "http://test2";
let finalString = (url1 ? 'The url 1 is ' + url1 : 'There isnt data for url1.') +
  (url1 && url2 ? ' and t' : ' T') +
  (url2 ? 'he url 2 is ' + url2 : 'There isnt data for url2.');

console.log(finalString)```

Body:
I am trying to create a custom string to be shown to the user, which is based on two variables.

Here is the example that I am trying to build:

let url1;
let url2;
if (containsData1) {
  url1 = "http://test";
}

if (containsData2) {
  url2 = "http://test2";
}

let finalString = '';
if (url1 && url2) {
  finalString = 'The url 1 is ' + url1 + ' and url 2 is ' + url2;
} else if (!url1 && url2) {
  finalString = 'There isnt data for url1. Url2 is ' + url2;
} else if (url1 && !url2) {
  finalString = 'The url 1 is ' + url1 + '. There isnt data for url2';
} else if (!url1 && !url2) {
  finalString = 'There isnt data for url1. There isnt data for url2';
}

However I would like to this in a proper way, without using this bunch of if elses, any suggestions on how to accomplish this?

Thanks.


问:
How does the boolean keyword argument get evaluated in a method?
Hopefully this isn't too dumb/basic, but I think I am missing an essential building block.

I am writing a Python loop to rename files based on OCR results, but want to have the option to keep the original filename. I am new to Python and programming, and have a question to how boolean logic is computed. As background, I understand that True is True, False is False, not True is False, and not False is True.

As for the method/function, it checks to see if the keyword argument for rename = True or False. To do this, I have an if loop that just says "if rename:". By default rename is False. I am unsure why saying "if rename: then dont rename files" does not work, but  writing"if not rename: dont rename files" does work.

I figured out that if I type "if not rename: don't rename files", I get the expected result, but I am not sure why that works.

```<code>def pnid_rename(file_name, new_name, rename = False):
    if not rename:
        print('Not renaming')
        return
    else:
        print('Renaming ' + file_name)
        os.rename(file_name, str(new_name) + '.png')
        return
</code>```

To me, "if rename" is the same as "if False", as rename = False, so the files should not rename because it is True that False == False. Instead, this triggers the rename loop.

So why do I need 'not'?

答: I just realized that I was a bit too tired last night. The if statement will not go to the else condition if the if evaluates as true. And by saying not False, I ensure it is true. Thanks all of the help!</p>

Body:
Hopefully this isn't too dumb/basic, but I think I am missing an essential building block.

I am writing a Python loop to rename files based on OCR results, but want to have the option to keep the original filename. I am new to Python and programming, and have a question to how boolean logic is computed. As background, I understand that True is True, False is False, not True is False, and not False is True.

As for the method/function, it checks to see if the keyword argument for rename = True or False. To do this, I have an if loop that just says "if rename:". By default rename is False. I am unsure why saying "if rename: then dont rename files" does not work, but  writing"if not rename: dont rename files" does work.

I figured out that if I type "if not rename: don't rename files", I get the expected result, but I am not sure why that works.

def pnid_rename(file_name, new_name, rename = False):
    if not rename:
        print('Not renaming')
        return
    else:
        print('Renaming ' + file_name)
        os.rename(file_name, str(new_name) + '.png')
        return

To me, "if rename" is the same as "if False", as rename = False, so the files should not rename because it is True that False == False. Instead, this triggers the rename loop.

So why do I need 'not'?


问:
Returning array react-redux
I am trying to return an array in react-redux, but I get undefined when I try to get them in my react component.

How do I return an array, using the "GET_TODO", "GET_FINISHED", "GET_LATER" cases.

Reducer, ( GET_ is the one that should return an array )

```<code>const initialState = {
  today: [1, 2, 3],
  finished: [3, 2, 1, 3],
  later: [2, 3, 1, 4, 2, 5]
};

export default (state = initialState, action) => {

  switch (action.type) {

    case 'ADD_TODO':
      return [...state.today, action.payload]
    case 'DELETE_TODO':
      return state.today.filter((item, index) => index !== action.payload)
    case 'GET_TODO':
      return state.today
    case 'ADD_LATER':
      return [...state, action.payload]
    case 'DELETE_LATER':
      return state.filter((item, index) => index !== action.payload)
    case 'GET_LATER':
      return [...state.later]
    case 'ADD_FINISHED':
      return [...state, action.payload]
    case 'DELETE_FINISHED':
      return state.filter((item, index) => index !== action.payload)
    case 'GET_FINISHED':
      return [...state.finished]
    default:
      return state;
  }
}
</code>```

React component

```<code>componentDidMount() {
    this.props.get();
  }
</code>```

mapStateToProps & mapDispatchToProps

```<code>function mapStateToProps(state) {
  return {
    today: state.important.today ? state.important.today : [],
    finished: state.important.finished ? state.important.finished : [],
    later: state.important.later ? state.important.later : [],

  }
}
</code>```

```<code>function mapDispatchToProps(dispatch) {
  return {
    add: (value) => {
      dispatch({ type: 'ADD_TODO', payload: value })
    },
    remove: (index) => {
      dispatch({ type: 'DELETE_TODO', payload: index })
    },
    get: () => {
      dispatch({type:'GET_TODO'})
    },
    addToFinished: (value) => {
      dispatch({ type: 'ADD_FINISHED', payload: value })
    },
    removeFinished: (index) => {
      dispatch({ type: 'DELETE_FINISHED', payload: index })
    },
    addToLater: (value) => {
      dispatch({ type: 'ADD_LATER', payload: value })
    },
    removeLater: (index) => {
      dispatch({ type: 'DELETE_LATER', payload: index })
    }
  }
}
</code>```

答:
Some of your actions are being handled by your reducer in a way which will cause you to get undefined. As you have multiple keys on your object, you will need to make sure you are only handling the key in question, for instance:

    case 'DELETE_LATER':
      return state.filter((item, index) => index !== action.payload)
```

<p>Should presumably be:</p>

```    case 'DELETE_LATER':
      return {
         ...state,
         later: state.later.filter((item, index) => index !== action.payload)
      }
```

<p>And as another example, your ADD_TODO handler will cause problems:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const initialState = {
  today: [1, 2, 3],
  finished: [3, 2, 1, 3],
  later: [2, 3, 1, 4, 2, 5]
};

const reducer = (state = initialState, action) => {

  switch (action.type) {

    case 'ADD_TODO':
      return [...state.today, action.payload]
    case 'DELETE_TODO':
      return state.today.filter((item, index) => index !== action.payload)
    case 'GET_TODO':
      return state.today
    case 'ADD_LATER':
      return [...state, action.payload]
    case 'DELETE_LATER':
      return state.filter((item, index) => index !== action.payload)
    case 'GET_LATER':
      return [...state.later]
    case 'ADD_FINISHED':
      return [...state, action.payload]
    case 'DELETE_FINISHED':
      return state.filter((item, index) => index !== action.payload)
    case 'GET_FINISHED':
      return [...state.finished]
    default:
      return state;
  }
}

const newState = reducer(initialState, { type: 'ADD_TODO', payload: 3})

console.dir(newState)</code>```

Notice that you've now lost the other keys from your state.

As an additional comment, when you're returning an array, the code:

return [...array]
```

<p>Is equivalent to:</p>

<pre class="lang-js prettyprint-override"><code>return array
</code>```

Title: Returning array react-redux

Body:
I am trying to return an array in react-redux, but I get undefined when I try to get them in my react component.

How do I return an array, using the "GET_TODO", "GET_FINISHED", "GET_LATER" cases.

Reducer, ( GET_ is the one that should return an array )

const initialState = {
  today: [1, 2, 3],
  finished: [3, 2, 1, 3],
  later: [2, 3, 1, 4, 2, 5]
};

export default (state = initialState, action) => {

  switch (action.type) {

    case 'ADD_TODO':
      return [...state.today, action.payload]
    case 'DELETE_TODO':
      return state.today.filter((item, index) => index !== action.payload)
    case 'GET_TODO':
      return state.today
    case 'ADD_LATER':
      return [...state, action.payload]
    case 'DELETE_LATER':
      return state.filter((item, index) => index !== action.payload)
    case 'GET_LATER':
      return [...state.later]
    case 'ADD_FINISHED':
      return [...state, action.payload]
    case 'DELETE_FINISHED':
      return state.filter((item, index) => index !== action.payload)
    case 'GET_FINISHED':
      return [...state.finished]
    default:
      return state;
  }
}

React component

componentDidMount() {
    this.props.get();
  }

mapStateToProps & mapDispatchToProps

function mapStateToProps(state) {
  return {
    today: state.important.today ? state.important.today : [],
    finished: state.important.finished ? state.important.finished : [],
    later: state.important.later ? state.important.later : [],

  }
}

function mapDispatchToProps(dispatch) {
  return {
    add: (value) => {
      dispatch({ type: 'ADD_TODO', payload: value })
    },
    remove: (index) => {
      dispatch({ type: 'DELETE_TODO', payload: index })
    },
    get: () => {
      dispatch({type:'GET_TODO'})
    },
    addToFinished: (value) => {
      dispatch({ type: 'ADD_FINISHED', payload: value })
    },
    removeFinished: (index) => {
      dispatch({ type: 'DELETE_FINISHED', payload: index })
    },
    addToLater: (value) => {
      dispatch({ type: 'ADD_LATER', payload: value })
    },
    removeLater: (index) => {
      dispatch({ type: 'DELETE_LATER', payload: index })
    }
  }
}

Body:
Some of your actions are being handled by your reducer in a way which will cause you to get undefined. As you have multiple keys on your object, you will need to make sure you are only handling the key in question, for instance:

    case 'DELETE_LATER':
      return state.filter((item, index) => index !== action.payload)

Should presumably be:

    case 'DELETE_LATER':
      return {
         ...state,
         later: state.later.filter((item, index) => index !== action.payload)
      }

And as another example, your ADD_TODO handler will cause problems:

const initialState = {
  today: [1, 2, 3],
  finished: [3, 2, 1, 3],
  later: [2, 3, 1, 4, 2, 5]
};

const reducer = (state = initialState, action) => {

  switch (action.type) {

    case 'ADD_TODO':
      return [...state.today, action.payload]
    case 'DELETE_TODO':
      return state.today.filter((item, index) => index !== action.payload)
    case 'GET_TODO':
      return state.today
    case 'ADD_LATER':
      return [...state, action.payload]
    case 'DELETE_LATER':
      return state.filter((item, index) => index !== action.payload)
    case 'GET_LATER':
      return [...state.later]
    case 'ADD_FINISHED':
      return [...state, action.payload]
    case 'DELETE_FINISHED':
      return state.filter((item, index) => index !== action.payload)
    case 'GET_FINISHED':
      return [...state.finished]
    default:
      return state;
  }
}

const newState = reducer(initialState, { type: 'ADD_TODO', payload: 3})

console.dir(newState)

Notice that you've now lost the other keys from your state.

As an additional comment, when you're returning an array, the code:

return [...array]

Is equivalent to:

return array


问:
How to pass a Class<Descendant> into a Hashmap?
I am populating a HashMap object with pairs of the type
<String, Class<Ancestor>>, where Ancestor is some custom class. The idea behind is instantiating an object out of a microservice name.

I am getting a compilation error while putting like this:

EDITED

```<code>map.put("some label", Descendant.class);
</code>```

It is obvious that HashMap class expects a real Ancestor class and not any Descendant class that extends Ancestor.

As I have dozens of different descendant classes (microservices), does anybody can tell how to avoid this limitation with HashMap?

I have tried using Class<?> instead of Class<Ancestor> in the HashMap declaration. But then a casting warning is fired by Eclipse when recalling a microservice

```<code>Class<Ancestor> a = (Class<Ancestor>) map.get("some label");
</code>```

The strange warning says:

```<code>Type safety: unchecked cast from Class <capture#151-of ?> to Class <Ancestor>
</code>```

答:
You can try making the generic parameter of Class covariant, by using a HashMap<String, Class<? extends Ancestor>>.

And you should not cast the Class you get from the map to Class<Ancestor>, just use it as a Class<? extends Ancestor>:

```<code>Class<? extends Ancestor> clazz = map.get("...");
</code>```

Body:
I am populating a HashMap object with pairs of the type
<String, Class<Ancestor>>, where Ancestor is some custom class. The idea behind is instantiating an object out of a microservice name.

I am getting a compilation error while putting like this:

EDITED

map.put("some label", Descendant.class);

It is obvious that HashMap class expects a real Ancestor class and not any Descendant class that extends Ancestor.

As I have dozens of different descendant classes (microservices), does anybody can tell how to avoid this limitation with HashMap?

I have tried using Class<?> instead of Class<Ancestor> in the HashMap declaration. But then a casting warning is fired by Eclipse when recalling a microservice

Class<Ancestor> a = (Class<Ancestor>) map.get("some label");

The strange warning says:

Type safety: unchecked cast from Class <capture#151-of ?> to Class <Ancestor>

Body:
You can try making the generic parameter of Class covariant, by using a HashMap<String, Class<? extends Ancestor>>.

And you should not cast the Class you get from the map to Class<Ancestor>, just use it as a Class<? extends Ancestor>:

Class<? extends Ancestor> clazz = map.get("...");


问:
Which architecture should I use to preinitialize N dockers in one server?
I want to create in just one server an application that runs inside a docker. I want the server to always have N active dockers running and if an N+1 user enters, then a new docker is launched.

I think that I need this architecture:

Nginx for load balancing
Kubernetes, to orchestrate the dockers
Docker, with the app inside this docker.

Is this correct? I am not sure if Kubernetes is what I need when I´m only going to use just one server.

答:
You probably want to use the cluster autoscaler functionality of kubernetes. Docs here: https://kubernetes.io/docs/tasks/run-application/horizontal-pod-autoscale/

Your approach of using users number as a metric will probably work, but maybe you are better off using generic metrics, such as the CPU consumption or memory availability on your node. For that you define the maximal consumption that your containers are allowed to use.


问:
How to exclude elements with certain attribute?
I've got many checkboxes like

```<code><input type="checkbox" disabled="disabled" class="item-store">
</code>```

With jQuery, I can select them like that:

```<code>$('input.item-store:checkbox')
</code>```

I would like to exclude those which are not enabled. The following doesn't seem to work:

```<code>$('input.item-store[disabled!="disabled"]:checkbox')
// or
$('input[disabled!="disabled"].item-store:checkbox')
</code>```

With the above query, I still get those which are disabled... Can you give me a tipp?

sl3dg3

答:
You should be able to do</p>

```<code>$('input.item-store:checkbox:not(:disabled)')
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I've got many checkboxes like

<input type="checkbox" disabled="disabled" class="item-store">

With jQuery, I can select them like that:

$('input.item-store:checkbox')

I would like to exclude those which are not enabled. The following doesn't seem to work:

$('input.item-store[disabled!="disabled"]:checkbox')
// or
$('input[disabled!="disabled"].item-store:checkbox')

With the above query, I still get those which are disabled... Can you give me a tipp?

sl3dg3

Body:
You should be able to do

$('input.item-store:checkbox:not(:disabled)')


问:
How do I convert CSS to Styled-Components with input[type="submit"] attribute?
How do I convert standard CSS with special attributes like "type" and "active", to Styled-Components consts?

```<code>.box {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 400px;
  background: #fff;
  padding: 40px;
  border: 1px solid rgba(0, 0, 0, 0.1);
  box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
}

input[type='submit'] {
  background: #00aec9;
  color: #fff;
  cursor: pointer;
  margin-bottom: 0;
  text-transform: uppercase;
  width: 100%;
  border-radius: 5px;
  height: 35px;
  border-color: transparent;
  box-shadow: 0px;
  outline: none;
  transition: 0.15s;
  text-align: center;
}

input[type='submit']:active {
  background-color: #f1ac15;
}
</code>```

I managed to create the const for the .box CSS class but not sure how to achieve this with "input[type='submit']" and "input[type='submit']:active"

```<code>//---- .box class ------ //
const DivBox = styled.div`
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 400px;
  background: #fff;
  padding: 40px;
  border: 1px solid rgba(0, 0, 0, 0.1);
  box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
`
</code>```

Any assistance would be greatly appreciated

PS, I am using React and Nextjs

What I currently have:

What I want:

My current Component Code:

```<code>import Layout from '../components/MyLayout.js'
import styled from 'styled-components'

const DivBox = styled.div`
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 400px;
  background: #fff;
  padding: 40px;
  border: 1px solid rgba(0, 0, 0, 0.1);
  box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
`

const Input = styled.input.attrs({ type: 'submit' })`
  background: #00aec9;
  color: #fff;
  cursor: pointer;
  margin-bottom: 0;
  text-transform: uppercase;
  width: 100%;
  border-radius: 5px;
  height: 35px;
  border-color: transparent;
  box-shadow: 0px;
  outline: none;
  transition: 0.15s;
  text-align: center;
  &:active {
    background-color: #f1ac15;
  }
`

export default function About() {
  return (
    <Layout>
      <DivBox>
        <p>This is the about page</p>
        <h2>Sample Form</h2>
        <div className="form-label-group">
          <input
            type="email"
            id="inputEmail"
            className="form-control"
            placeholder="Email address"
            required
            autoFocus
          />
          <label htmlFor="inputEmail">Email address</label>
        </div>

        <div className="form-label-group">
          <input
            type="password"
            id="inputPassword"
            className="form-control"
            placeholder="Password"
            required
          />
          <label htmlFor="inputPassword">Password</label>
        </div>
        <div>
          <input type="submit" value="Submit" />
        </div>
      </DivBox>
    </Layout>
  )
}
</code>```

Additional CSS:

```<code>.form-control:focus {
  border-color: #00aec9;
  box-shadow: 0 0 0 0.2rem rgba(19, 162, 228, 0.25);
}

.form-label-group input:not(:placeholder-shown) ~ label {
  color: #00aec9;
}
</code>```

答:
I guess you can achieve that by:

const Input = styled.input.attrs({
  type: 'submit',
  value: 'Submit'
})`
  background: #00aec9;
  color: #fff;
  cursor: pointer;
  margin-bottom: 0;
  text-transform: uppercase;
  width: 100%;
  border-radius: 5px;
  height: 35px;
  border-color: transparent;
  box-shadow: 0px;
  outline: none;
  transition: 0.15s;
  text-align: center;
  &:active {
    background-color: #f1ac15;
  }
````
</div>
</div>
</p>

<p>And replace </p>

```<input type="submit" value="Submit" />
```

<p>with</p>

```<Input />
```

More informations on attrs here

Body:
How do I convert standard CSS with special attributes like "type" and "active", to Styled-Components consts?

.box {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 400px;
  background: #fff;
  padding: 40px;
  border: 1px solid rgba(0, 0, 0, 0.1);
  box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
}

input[type='submit'] {
  background: #00aec9;
  color: #fff;
  cursor: pointer;
  margin-bottom: 0;
  text-transform: uppercase;
  width: 100%;
  border-radius: 5px;
  height: 35px;
  border-color: transparent;
  box-shadow: 0px;
  outline: none;
  transition: 0.15s;
  text-align: center;
}

input[type='submit']:active {
  background-color: #f1ac15;
}

I managed to create the const for the .box CSS class but not sure how to achieve this with "input[type='submit']" and "input[type='submit']:active"

//---- .box class ------ //
const DivBox = styled.div`
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 400px;
  background: #fff;
  padding: 40px;
  border: 1px solid rgba(0, 0, 0, 0.1);
  box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
`

Any assistance would be greatly appreciated

PS, I am using React and Nextjs

What I currently have:

What I want:

My current Component Code:

import Layout from '../components/MyLayout.js'
import styled from 'styled-components'

const DivBox = styled.div`
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 400px;
  background: #fff;
  padding: 40px;
  border: 1px solid rgba(0, 0, 0, 0.1);
  box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
`

const Input = styled.input.attrs({ type: 'submit' })`
  background: #00aec9;
  color: #fff;
  cursor: pointer;
  margin-bottom: 0;
  text-transform: uppercase;
  width: 100%;
  border-radius: 5px;
  height: 35px;
  border-color: transparent;
  box-shadow: 0px;
  outline: none;
  transition: 0.15s;
  text-align: center;
  &:active {
    background-color: #f1ac15;
  }
`

export default function About() {
  return (
    <Layout>
      <DivBox>

This is the about page

Sample Form

          <input
            type="email"
            id="inputEmail"
            className="form-control"
            placeholder="Email address"
            required
            autoFocus
          />
          Email address

          <input
            type="password"
            id="inputPassword"
            className="form-control"
            placeholder="Password"
            required
          />
          Password

          <input type="submit" value="Submit" />

      </DivBox>
    </Layout>
  )
}

Additional CSS:

.form-control:focus {
  border-color: #00aec9;
  box-shadow: 0 0 0 0.2rem rgba(19, 162, 228, 0.25);
}

.form-label-group input:not(:placeholder-shown) ~ label {
  color: #00aec9;
}

Body:
I guess you can achieve that by:

const Input = styled.input.attrs({
  type: 'submit',
  value: 'Submit'
})`
  background: #00aec9;
  color: #fff;
  cursor: pointer;
  margin-bottom: 0;
  text-transform: uppercase;
  width: 100%;
  border-radius: 5px;
  height: 35px;
  border-color: transparent;
  box-shadow: 0px;
  outline: none;
  transition: 0.15s;
  text-align: center;
  &:active {
    background-color: #f1ac15;
  }
`

And replace

<input type="submit" value="Submit" />

with

<Input />

More informations on attrs here


问:
PHP CRUD with MySQL on two Files
I am very New with php and Database...

I have a File where Display the Comment, contact.php , here to schow it and my Css, because codepen have only for JS , the Comment form not to Display , the Code for Comment to be call classprove.php it have in PHP and it is here , people help me, for build these Code...

Than have the File kommenter_verwalter.php where i will to Display my Comments output on Tabelle .

So , i have Two Files for my Comments , classprove.php for Administrate my Comments , and kommenter_verwalter.php , where i will they to Display.

I to try with these Code to build a File for delete with a button beside each row so that if I want to delete that row I click the delete button .

Edit new my Code

Now to search my Code without connect to my classprove.php File .

The Code from kommenter_verwalter.php,

```<code><?php

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

class ClassProveContakt2
{

          private $dbHost = 'localhost'; # Host der Datenbank
          private $dbName = 'meine';      # Name der Datenbank
          private $dbUser = 'root';      # Name phpmyadmin
          private $dbPass = 'pass';      # Passwort

          private $name;
          private $email;
          private $message;
          private $datetime;
          private $ip;
          private $db;
          private $connection;
          private $id;
          private $sql;
          private $statement;
          private $success;

          function CommentToDatabase()
          {
              // Establish connection with MYSQL Server
            try
            {
              $db = new PDO("mysql:host=localhost;dbname=meine", "root", "pass");
            }
             catch (PDOException $pe)
            {
               echo "<br>Cannot connect to database: " . $pe->getMessage();
                return false;
            }

            if(isset($_POST["delete"])) {
             try {

                   $connection = new PDO($id, $name, $email, $message, $datetime, $ip);

                   $id = $_POST["id"];

                   $sql = "DELETE FROM mela WHERE id = :id";

                   $statement = $connection->prepare($sql);
                   $statement->bindValue(':id', $id);
                   $statement->execute();

                   $success = "User successfully deleted";
                  }catch(PDOException $error) {
                        echo $sql . "<br>" . $error->getMessage();
                   }

             }
           }
           function tabelle()
           {
              $db = $this ->CommentToDatabase();

              if ($db)
              {

                 echo "<table id='user' class='table table-bordered'>

                    <tr>
                      <th>id</th>
                      <th>name</th>
                      <th>email</th>
                      <th>message</th>
                      <th>datetime</th>
                      <th>ip</th>
                       <th>Delete User</th>
                      </tr>";

                     foreach ($db as $row){

                        echo <<<EOT
                           <tr>
                              <td>{$row['id']}</td>
                              <td>{$row['name']}</td>
                              <td>{$row['email']}</td>
                              <td>{$row['message']}</td>
                              <td>{$row['datetime']}</td>
                              <td>{$row['ip']}</td>
                              <td><button type "submit" name="delete" value="{$row['id']}">löschen</button>
                            </tr>

EOT;
                     }

                    echo "</table>";

                 }

           }
}

$News = new ClassProveContakt2;
$News -> CommentToDatabase();
$News -> tabelle();
?>
</code>```

When write sudo tail -n0 -f /var/log/apache2/error.log /var/log/mysql/error.log

Now to come not error , but nothing Display...

I to observe that i have not,

$_POST["delete"]

and

$_POST["id"];

I to build my form with only (name, email and message) , id have with phpmyadmin to build . . These piece Code have in internet to found...

Can Please anyone tell me , how can to change these part the Code .

How to show my Tabelle on phpmyadmin ,

I to want that the the File kommenter_verwalter.php (there which here give) , the output Display only the comments(name, email , message,..) on a Table whith the button , delete as this Screeshot to show...,and the File classprove.php to stay as Administrate for Comment .

Can Please anyone help me with this Problem , Thanks !

答:
Because are People on stackoverflow which not to let my another Question to answer ,they to hiding it.....Titel name from it "How to use CRUD on SQL" , and because it is very similar as these , i answer here ....

Now can Display the File kommenter_verwalter.php  without connect to my classprove.php File .

I has some mistakes therefore can't Display it....

How have now my kommenter_verwalter.php,

```<code>class ClassProveContakt2
{

      private $conn;

   function __construct() {

      $dbHost = 'localhost'; # Host der Datenbank
      $dbName = 'meine';      # Name der Datenbank
      $dbUser = 'root';      # Name der Datenbank
      $dbPass = 'pass';      # Passwort

      // declare the object conn, which conect to the Datebase .

          $this->conn = new mysqli($dbHost,$dbUser,$dbPass,$dbName);
    }
     // mit these function delete the Comment .

    function deleteComment($id){

      /* build a Variable to delete the Comment ,on **id=?** , give **?**
       because i will the Comment to delete on hand (with the Bottom "delete")
       give not Value to **id**  , the **?** . */

      $sql = "DELETE FROM mela WHERE id=?";

       // prepare and bind the connection to Database .

       $statement= $this->conn->prepare($sql);
       $statement -> bind_param('i',$id);
       $statement->execute();
    }
    function printAdminTable() {

        //connect to the Table , name "mela" and the Rows which are in it .

         $sql = "SELECT id, name, email, message, datetime,ip FROM mela ORDER BY datetime DESC";

       // prepare and bind the connection to the Table .

       $statement= $this->conn->prepare($sql);
       $statement->execute();

       $result = $statement-> get_result();

         //On *if* Statement asked if all is ok on the connection with sql
        // when yes ,build the Table .

       if ( $result ) {
            echo "
        <form action=\"prove_comment.php\" method=\"POST\">\n
        <table id='user' class='table table-bordered' border= '1px solid';>
                <tr>
                 <th>ID</th>
                  <th>Name</th>
                  <th>E-mail</th>
                  <th>Message</th>
                  <th>Datetime</th>
                  <th>IP</th>
                   <th>Delete</th>
                  </tr>";

              while($row = $result->fetch_assoc()){

                echo <<<EOT
                  <tr>
                      <td>{$row['id']}</td>
                      <td>{$row['name']}</td>
                      <td>{$row['email']}</td>
                      <td>{$row['message']}</td>
                      <td>{$row['datetime']}</td>
                      <td>{$row['ip']}</td>
                      <td><button type="submit" name="delete" value="{$row['id']}">löschen</button>
                  </tr>

EOT;
              }
             echo '</table></form>';
            // when not connection on sql .
            } else {
          echo '<p class="error">Hm. $arrRows enthält nichts oder false. '
            .'Entweder ist die Datenbank noch leer oder da ist was falsch.</p>';
     }
    }
        // connection to sql closse .
     function __destruct(){
       $this->conn->close();
     }
    }   // Build the call to the method .
    $News = new ClassProveContakt2();
       /* Because befor have add 'delete' on my POST Method
        (Linne 77 ,  "<td><button type="....) , with the **if** Statement asked if
        it is , when yes , delete it . */
    if (isset($_POST['delete'])){
    $News -> deleteComment($_POST['delete']);
    }
    $News -> printAdminTable();
</code>```

Screehot how to show now my File kommenter_verwalter.php , how to show it

Title: PHP CRUD with MySQL on two Files

Body:
I am very New with php and Database...

I have a File where Display the Comment, contact.php , here to schow it and my Css, because codepen have only for JS , the Comment form not to Display , the Code for Comment to be call classprove.php it have in PHP and it is here , people help me, for build these Code...

Than have the File kommenter_verwalter.php where i will to Display my Comments output on Tabelle .

So , i have Two Files for my Comments , classprove.php for Administrate my Comments , and kommenter_verwalter.php , where i will they to Display.

I to try with these Code to build a File for delete with a button beside each row so that if I want to delete that row I click the delete button .

Edit new my Code

Now to search my Code without connect to my classprove.php File .

The Code from kommenter_verwalter.php,

<?php

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

class ClassProveContakt2
{

          private $dbHost = 'localhost'; # Host der Datenbank
          private $dbName = 'meine';      # Name der Datenbank
          private $dbUser = 'root';      # Name phpmyadmin
          private $dbPass = 'pass';      # Passwort

          private $name;
          private $email;
          private $message;
          private $datetime;
          private $ip;
          private $db;
          private $connection;
          private $id;
          private $sql;
          private $statement;
          private $success;

          function CommentToDatabase()
          {
              // Establish connection with MYSQL Server
            try
            {
              $db = new PDO("mysql:host=localhost;dbname=meine", "root", "pass");
            }
             catch (PDOException $pe)
            {
               echo "
Cannot connect to database: " . $pe->getMessage();
                return false;
            }

            if(isset($_POST["delete"])) {
             try {

                   $connection = new PDO($id, $name, $email, $message, $datetime, $ip);

                   $id = $_POST["id"];

                   $sql = "DELETE FROM mela WHERE id = :id";

                   $statement = $connection->prepare($sql);
                   $statement->bindValue(':id', $id);
                   $statement->execute();

                   $success = "User successfully deleted";
                  }catch(PDOException $error) {
                        echo $sql . "
" . $error->getMessage();
                   }

             }
           }
           function tabelle()
           {
              $db = $this ->CommentToDatabase();

              if ($db)
              {

                 echo "

                      id
                      name
                      email
                      message
                      datetime
                      ip
                       Delete User

";

                     foreach ($db as $row){

                        echo <<<EOT

                              {$row['id']}
                              {$row['name']}
                              {$row['email']}
                              {$row['message']}
                              {$row['datetime']}
                              {$row['ip']}
                              <button type "submit" name="delete" value="{$row['id']}">löschen</button>

EOT;
                     }

                    echo "
";

                 }

           }
}

$News = new ClassProveContakt2;
$News -> CommentToDatabase();
$News -> tabelle();
?>

When write sudo tail -n0 -f /var/log/apache2/error.log /var/log/mysql/error.log

Now to come not error , but nothing Display...

I to observe that i have not,

$_POST["delete"]

and

$_POST["id"];

I to build my form with only (name, email and message) , id have with phpmyadmin to build . . These piece Code have in internet to found...

Can Please anyone tell me , how can to change these part the Code .

How to show my Tabelle on phpmyadmin ,

I to want that the the File kommenter_verwalter.php (there which here give) , the output Display only the comments(name, email , message,..) on a Table whith the button , delete as this Screeshot to show...,and the File classprove.php to stay as Administrate for Comment .

Can Please anyone help me with this Problem , Thanks !

Body:
Because are People on stackoverflow which not to let my another Question to answer ,they to hiding it.....Titel name from it "How to use CRUD on SQL" , and because it is very similar as these , i answer here ....

Now can Display the File kommenter_verwalter.php  without connect to my classprove.php File .

I has some mistakes therefore can't Display it....

How have now my kommenter_verwalter.php,

class ClassProveContakt2
{

      private $conn;

   function __construct() {

      $dbHost = 'localhost'; # Host der Datenbank
      $dbName = 'meine';      # Name der Datenbank
      $dbUser = 'root';      # Name der Datenbank
      $dbPass = 'pass';      # Passwort

      // declare the object conn, which conect to the Datebase .

          $this->conn = new mysqli($dbHost,$dbUser,$dbPass,$dbName);
    }
     // mit these function delete the Comment .

    function deleteComment($id){

      /* build a Variable to delete the Comment ,on **id=?** , give **?**
       because i will the Comment to delete on hand (with the Bottom "delete")
       give not Value to **id**  , the **?** . */

      $sql = "DELETE FROM mela WHERE id=?";

       // prepare and bind the connection to Database .

       $statement= $this->conn->prepare($sql);
       $statement -> bind_param('i',$id);
       $statement->execute();
    }
    function printAdminTable() {

        //connect to the Table , name "mela" and the Rows which are in it .

         $sql = "SELECT id, name, email, message, datetime,ip FROM mela ORDER BY datetime DESC";

       // prepare and bind the connection to the Table .

       $statement= $this->conn->prepare($sql);
       $statement->execute();

       $result = $statement-> get_result();

         //On *if* Statement asked if all is ok on the connection with sql
        // when yes ,build the Table .

       if ( $result ) {
            echo "
        <form action=\"prove_comment.php\" method=\"POST\">\n
        <table id='user' class='table table-bordered' border= '1px solid';>
                <tr>
                 <th>ID</th>
                  <th>Name</th>
                  <th>E-mail</th>
                  <th>Message</th>
                  <th>Datetime</th>
                  <th>IP</th>
                   <th>Delete</th>
                  </tr>";

              while($row = $result->fetch_assoc()){

                echo <<<EOT
                  <tr>
                      <td>{$row['id']}</td>
                      <td>{$row['name']}</td>
                      <td>{$row['email']}</td>
                      <td>{$row['message']}</td>
                      <td>{$row['datetime']}</td>
                      <td>{$row['ip']}</td>
                      <td><button type="submit" name="delete" value="{$row['id']}">löschen</button>
                  </tr>

EOT;
              }
             echo '</table></form>';
            // when not connection on sql .
            } else {
          echo '<p class="error">Hm. $arrRows enthält nichts oder false. '
            .'Entweder ist die Datenbank noch leer oder da ist was falsch.</p>';
     }
    }
        // connection to sql closse .
     function __destruct(){
       $this->conn->close();
     }
    }   // Build the call to the method .
    $News = new ClassProveContakt2();
       /* Because befor have add 'delete' on my POST Method
        (Linne 77 ,  "<td><button type="....) , with the **if** Statement asked if
        it is , when yes , delete it . */
    if (isset($_POST['delete'])){
    $News -> deleteComment($_POST['delete']);
    }
    $News -> printAdminTable();

Screehot how to show now my File kommenter_verwalter.php , how to show it


问:
Could not get unknown property 'file' for project ':app' of type org.gradle.api.Project
I keep getting this error in the app project on my Music Streaming App:

Could not get unknown property 'file' for project ':app' of type org.gradle.api.Project.

I would like to know what i am doing wrong. I keep getting stuck no matter what i try.

Here is the App Project from Android Studio.

```<code>apply plugin: 'kotlin-kapt'
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'com.android.application'
apply plugin: 'io.fabric'

repositories {
    mavenCentral()
    maven { url 'https://maven.fabric.io/public' }
}

android {

    buildTypes {
        release {
            ndk {
                abiFilters "armeabi-v7a" // includes ARM SO files only, so no x86 SO file
            }
        }
    }

//    packagingOptions {
//        exclude "lib/mips"
//    }

    compileSdkVersion 28
    defaultConfig {
        applicationId "cloud.veezee.android"
        minSdkVersion 21
        targetSdkVersion 28
        versionCode 10
        versionName "1.1"
        renderscriptTargetApi 21
        renderscriptSupportModeEnabled true
        multiDexEnabled true

//        buildConfigField 'String', 'GoogleAndroidClientId', GoogleAndroidClientId
        buildConfigField 'String', 'GoogleServerClientId', GoogleServerClientId
    }
    signingConfigs {
        release {
            storeFile file("../keystore.jks")
            storePassword ANDROID_STORE_PASSWORD
            keyAlias ANDROID_STORE_ALIAS
            keyPassword ANDROID_KEY_PASSWORD
        }
        buildTypes {
            release {
//                minifyEnabled true
//                proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
                signingConfig signingConfigs.release
            }
            debug {
                signingConfig signingConfigs.release
            }
        }
    }

    dataBinding {
        enabled = true
    }

    dependencies {
        implementation fileTree(dir: 'libs', include: ['*.jar'])
        implementation "org.jetbrains.anko:anko-commons:0.10.7"
        implementation "com.android.support:appcompat-v7:28.0.0"
        implementation "com.android.support:support-media-compat:28.0.0"
        implementation "com.android.support:support-v4:28.0.0"
        implementation 'com.android.support:cardview-v7:28.0.0'
        implementation 'com.android.support:design:28.0.0'
        implementation 'com.android.support.constraint:constraint-layout:1.1.3'
        implementation 'com.google.android.gms:play-services-auth:16.0.1'
        implementation 'me.everything:overscroll-decor-android:1.0.4'
        implementation 'com.miguelcatalan:materialsearchview:1.4.0'
        implementation 'com.google.android.exoplayer:exoplayer:2.7.0'
        implementation 'com.android.volley:volley:1.1.0'
        implementation 'com.google.code.gson:gson:2.8.2'
        implementation 'com.sothree.slidinguppanel:library:3.4.0'
        implementation 'com.appsee:appsee-android:2.4.1'
        implementation 'com.danikula:videocache:2.7.0'
        implementation 'com.couchbase.lite:couchbase-lite-android:2.0.0'
        implementation 'com.github.bumptech.glide:glide:4.7.1'
        implementation 'io.reactivex.rxjava2:rxkotlin:2.2.0'
        implementation 'com.yarolegovich:discrete-scrollview:1.4.9'
        implementation 'jp.wasabeef:glide-transformations:3.3.0'
        kapt 'com.github.bumptech.glide:compiler:4.7.1'

        implementation('com.crashlytics.sdk.android:crashlytics:2.9.1@aar') {
            transitive = true
        }
    }
}

afterEvaluate {
    initFabricPropertiesIfNeeded()
}

def initFabricPropertiesIfNeeded() {
    def propertiesFile = file
    if (!propertiesFile.exists()) {
        ant.propertyfile(file: "fabric.properties", comment: commentMessage) {
            entry(key: "apiSecret", value: FabricSecretKey)
            entry(key: "apiKey", value: FabricApiKey)
        }
    }
}
</code>```

答:
App: Could not get unknown property 'file' for project ':app' of type org.gradle.api.Project.

The issue is in this line:

```<code>def initFabricPropertiesIfNeeded() {
    def propertiesFile = file
    //....
}
</code>```

You can check the official doc.

The Project.file(java.lang.Object) method is used to create a file or directory path relative to the current project and is a common way to make build scripts work regardless of the project path.

You have to change your script in something like:

```<code>def propertiesFile = file('myFile.properties')
</code>```

(may be but I can't be sure def propertiesFile = file('fabric.properties'))

Body:
I keep getting this error in the app project on my Music Streaming App:

Could not get unknown property 'file' for project ':app' of type org.gradle.api.Project.

I would like to know what i am doing wrong. I keep getting stuck no matter what i try.

Here is the App Project from Android Studio.

apply plugin: 'kotlin-kapt'
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'com.android.application'
apply plugin: 'io.fabric'

repositories {
    mavenCentral()
    maven { url 'https://maven.fabric.io/public' }
}

android {

    buildTypes {
        release {
            ndk {
                abiFilters "armeabi-v7a" // includes ARM SO files only, so no x86 SO file
            }
        }
    }

//    packagingOptions {
//        exclude "lib/mips"
//    }

    compileSdkVersion 28
    defaultConfig {
        applicationId "cloud.veezee.android"
        minSdkVersion 21
        targetSdkVersion 28
        versionCode 10
        versionName "1.1"
        renderscriptTargetApi 21
        renderscriptSupportModeEnabled true
        multiDexEnabled true

//        buildConfigField 'String', 'GoogleAndroidClientId', GoogleAndroidClientId
        buildConfigField 'String', 'GoogleServerClientId', GoogleServerClientId
    }
    signingConfigs {
        release {
            storeFile file("../keystore.jks")
            storePassword ANDROID_STORE_PASSWORD
            keyAlias ANDROID_STORE_ALIAS
            keyPassword ANDROID_KEY_PASSWORD
        }
        buildTypes {
            release {
//                minifyEnabled true
//                proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
                signingConfig signingConfigs.release
            }
            debug {
                signingConfig signingConfigs.release
            }
        }
    }

    dataBinding {
        enabled = true
    }

    dependencies {
        implementation fileTree(dir: 'libs', include: ['*.jar'])
        implementation "org.jetbrains.anko:anko-commons:0.10.7"
        implementation "com.android.support:appcompat-v7:28.0.0"
        implementation "com.android.support:support-media-compat:28.0.0"
        implementation "com.android.support:support-v4:28.0.0"
        implementation 'com.android.support:cardview-v7:28.0.0'
        implementation 'com.android.support:design:28.0.0'
        implementation 'com.android.support.constraint:constraint-layout:1.1.3'
        implementation 'com.google.android.gms:play-services-auth:16.0.1'
        implementation 'me.everything:overscroll-decor-android:1.0.4'
        implementation 'com.miguelcatalan:materialsearchview:1.4.0'
        implementation 'com.google.android.exoplayer:exoplayer:2.7.0'
        implementation 'com.android.volley:volley:1.1.0'
        implementation 'com.google.code.gson:gson:2.8.2'
        implementation 'com.sothree.slidinguppanel:library:3.4.0'
        implementation 'com.appsee:appsee-android:2.4.1'
        implementation 'com.danikula:videocache:2.7.0'
        implementation 'com.couchbase.lite:couchbase-lite-android:2.0.0'
        implementation 'com.github.bumptech.glide:glide:4.7.1'
        implementation 'io.reactivex.rxjava2:rxkotlin:2.2.0'
        implementation 'com.yarolegovich:discrete-scrollview:1.4.9'
        implementation 'jp.wasabeef:glide-transformations:3.3.0'
        kapt 'com.github.bumptech.glide:compiler:4.7.1'

        implementation('com.crashlytics.sdk.android:crashlytics:2.9.1@aar') {
            transitive = true
        }
    }
}

afterEvaluate {
    initFabricPropertiesIfNeeded()
}

def initFabricPropertiesIfNeeded() {
    def propertiesFile = file
    if (!propertiesFile.exists()) {
        ant.propertyfile(file: "fabric.properties", comment: commentMessage) {
            entry(key: "apiSecret", value: FabricSecretKey)
            entry(key: "apiKey", value: FabricApiKey)
        }
    }
}

Body:
App: Could not get unknown property 'file' for project ':app' of type org.gradle.api.Project.

The issue is in this line:

def initFabricPropertiesIfNeeded() {
    def propertiesFile = file
    //....
}

You can check the official doc.

The Project.file(java.lang.Object) method is used to create a file or directory path relative to the current project and is a common way to make build scripts work regardless of the project path.

You have to change your script in something like:

def propertiesFile = file('myFile.properties')

(may be but I can't be sure def propertiesFile = file('fabric.properties'))


问:
how to get all the multi valued attributes into a csv file
I have a sample data as below .Below attributes are belong to [data] dictionary.   In "XXXX" i have value "Naveen" and in "YYYYY" i have "Kumar" and "Rajesh" . i am trying with the below code to get 2 recorded output

Please help with any suggestion

```<code>    {
  "data": [
  {
      "Empid": "1234",
      "Empname": "ABC",
       "data1": {
          "XXXX": [
            {
              "relative": {
                "id": "Naveen"
              }
            }
          ],
          "YYYYY": [
            {
              "relative": {
                "id": "Kumar"
              }
            },
            {
              "relative": {
                "id": "Rajesh"
              }
            }
          ]
          }

     }
     ]
}
</code>```

Please find below code ( i am trying )

```<code>df = pd.DataFrame()
for i in range(len(json_file['data'])):
    temp = {}
    temp['Empid'] = json_file['data'][i]['Empid']
    temp['EmpName'] = json_file['data'][i]['EmpName']
        for key in json_file['data'][i]['data1'].keys():
                try:
                    for j in range(len(json_file['data'][i]['data1'][key])):
                        temp[key]  = json_file['data'][i]['data1'][key][j]['relative']['id']
                except:
                    temp[key] = None
        temp_df = pd.DataFrame([temp])
        df = pd.concat([df, temp_df], sort=True)
</code>```

Final output i am trying to achieve

```<code> EmpID EmpName XXXX   YYYYY
 1234  ABC     Naveen  Kumar
 1234  ABC     Nan     Rajesh
</code>```

but i am getting only 1 record

```<code> EmpID EmpName XXXX   YYYYY
 1234  ABC     Naveen  Kumar
</code>```

Please help me with any suggestion

答:
An other answer with DataFrame :

```<code>df = pd.DataFrame()
for key in json_file['data'][0].keys():
    for j in range(len(json_file['data'][0][key])):
        df.loc[j,key] = json_file['data'][0][key][j]['relative']['id']
</code>```

Result :

```<code>
XXXX    YYYYY
0   Naveen  Kumar
1   NaN Rajesh
</code>```

Body:
I have a sample data as below .Below attributes are belong to [data] dictionary.   In "XXXX" i have value "Naveen" and in "YYYYY" i have "Kumar" and "Rajesh" . i am trying with the below code to get 2 recorded output

Please help with any suggestion

    {
  "data": [
  {
      "Empid": "1234",
      "Empname": "ABC",
       "data1": {
          "XXXX": [
            {
              "relative": {
                "id": "Naveen"
              }
            }
          ],
          "YYYYY": [
            {
              "relative": {
                "id": "Kumar"
              }
            },
            {
              "relative": {
                "id": "Rajesh"
              }
            }
          ]
          }

     }
     ]
}

Please find below code ( i am trying )

df = pd.DataFrame()
for i in range(len(json_file['data'])):
    temp = {}
    temp['Empid'] = json_file['data'][i]['Empid']
    temp['EmpName'] = json_file['data'][i]['EmpName']
        for key in json_file['data'][i]['data1'].keys():
                try:
                    for j in range(len(json_file['data'][i]['data1'][key])):
                        temp[key]  = json_file['data'][i]['data1'][key][j]['relative']['id']
                except:
                    temp[key] = None
        temp_df = pd.DataFrame([temp])
        df = pd.concat([df, temp_df], sort=True)

Final output i am trying to achieve

 EmpID EmpName XXXX   YYYYY
 1234  ABC     Naveen  Kumar
 1234  ABC     Nan     Rajesh

but i am getting only 1 record

 EmpID EmpName XXXX   YYYYY
 1234  ABC     Naveen  Kumar

Please help me with any suggestion

Body:
An other answer with DataFrame :

df = pd.DataFrame()
for key in json_file['data'][0].keys():
    for j in range(len(json_file['data'][0][key])):
        df.loc[j,key] = json_file['data'][0][key][j]['relative']['id']

Result :

XXXX    YYYYY
0   Naveen  Kumar
1   NaN Rajesh


问:
Get hexadecimal representation of an integer as string in Mathematica
Is there a built-in way in Mathematica to get the hexadecimal representation of a positive integer as a string (using letters of the alphabet as higher digits)?  Currently I use my own implementation as

```<code>toHexString[n_Integer] :=
 StringJoin[
  ToString /@
   (IntegerDigits[n, 16] /. Thread[Range[10, 15] -> CharacterRange["A", "F"]])
 ]
</code>```

答:
```<code>In[254]:= IntegerString[{16, 34, 110, 5676767}, 16]

Out[254]= {"10", "22", "6e", "569edf"}
</code>```

or, if you don't like the standard lowercase characters in the result:

```<code>In[255]:= ToUpperCase[IntegerString[{16, 34, 110, 5676767}, 16]]

Out[255]= {"10", "22", "6E", "569EDF"}
</code>```

Please note that IntegerString has an optional third argument that is very helpful in  generating series of filenames that sort in the correct order when sorted alphabetically:

```<code>In[256]:= Table["filename" <> IntegerString[i, 10, 4] <> ".jpg", {i, 1, 7}]

Out[256]= {"filename0001.jpg", "filename0002.jpg",
"filename0003.jpg", "filename0004.jpg", "filename0005.jpg",
"filename0006.jpg", "filename0007.jpg"}
</code>```

Body:
Is there a built-in way in Mathematica to get the hexadecimal representation of a positive integer as a string (using letters of the alphabet as higher digits)?  Currently I use my own implementation as

toHexString[n_Integer] :=
 StringJoin[
  ToString /@
   (IntegerDigits[n, 16] /. Thread[Range[10, 15] -> CharacterRange["A", "F"]])
 ]

Body:
In[254]:= IntegerString[{16, 34, 110, 5676767}, 16]

Out[254]= {"10", "22", "6e", "569edf"}

or, if you don't like the standard lowercase characters in the result:

In[255]:= ToUpperCase[IntegerString[{16, 34, 110, 5676767}, 16]]

Out[255]= {"10", "22", "6E", "569EDF"}

Please note that IntegerString has an optional third argument that is very helpful in  generating series of filenames that sort in the correct order when sorted alphabetically:

In[256]:= Table["filename" <> IntegerString[i, 10, 4] <> ".jpg", {i, 1, 7}]

Out[256]= {"filename0001.jpg", "filename0002.jpg",
"filename0003.jpg", "filename0004.jpg", "filename0005.jpg",
"filename0006.jpg", "filename0007.jpg"}


答:
function matchSecondSymbol(firstSymbol, secondSymbol) {
  // By making FirstSymbol Uppercase, we can remove the other two conditions
  firstSymbol = firstSymbol.toUpperCase();
  if (['A', 'D'].includes(firstSymbol) && secondSymbol === "z") {
      console.log('it Does');
  }
  else {
      console.log('it does not');
  }
}

matchSecondSymbol('a', 'z');
matchSecondSymbol('z', 'z');
matchSecondSymbol('a', 'y');```

Title: Why does it always return true?

Body:
Beginner question, sorry if it's not the right place to ask
Trying to learn how logic works in JS, can't figure this out

if (firstSymbol === "A" || "a" || "D" || "d") {
    if (secondSymbol === "z") {
        alert("It does!");
        break;
    }
}

I expect it to say "It does!" and break in case if the firstSymbol is A, a, D or d AND the secondSymbol is z , but for some reason it says "It does!" and breaks regardless of what the firstSymbol is and only checks if the secondSymbol is z.


问:
NgWebDriver working only after reloading the page . Why?
I am using selenium and NgWebDriver for angular testing angular app. When I use ngWebDriver, It is taking long time for the testing but once I refresh the page It is working smoothly and all the tests pass withing short period of time.
Why I need to refresh  the page ?
Or What can be done to avoid refreshing the page ?
Suggestions please.</p>

答: Use driver.navigate().refresh() after your page loads</p>


问:
Colorize Eclasses and EReferenzes in .ecore_diagram (GMF)
Is there a "normal" way to Colorize the Nodes and Edges in the .ecore_diagram programaticaly?

My Code so far:

```<code>private static void saveDiagram(ResourceSet resourceSet,
        EPackage epackage, String path) {
    URI uri= URI.createFileURI(path);
    Resource overlapResource = resourceSet.createResource(uri, "ecore");

    overlapResource.getContents().add(epackage);
    Diagram d = createDiagram(epackage);

    URI diagUri = URI.createFileURI(path + "_diagram");
    Resource diagramResource = resourceSet.createResource(diagUri, "ecore");
    d.setName(diagUri.lastSegment());
    diagramResource.getContents().add(d);

    diagramResource.save(null); //In try catch block
    overlapResource.save(null); //In try catch block
}

public static Diagram createDiagram(EObject object) {
    Diagram diagram = NotationFactory.eINSTANCE.createDiagram();
    diagram.setMeasurementUnit(MeasurementUnit.PIXEL_LITERAL);
    diagram.setElement(object);
    diagram.setType("Ecore");
    return diagram;
}
</code>```

I have the ecore file, ecore_diagram file and the EPackage...
I dont know.. should I go throw all EClasses and EReferences and ... what?

Thx for Help!

答:
Here is a way for doing it in the case of a node for example :

In someway get the group of my odesign :

Group group = odesign.getGroup()

You  create first a UserColorPalette :

```<code>UserColorsPalette colorPallette = org.eclipse.sirius.viewpoint.description.DescriptionFactory.eINSTANCE
                .createUserColorsPalette();
group.getUserColorsPalettes().add(colorPallette);
UserFixedColor fixedColor = org.eclipse.sirius.viewpoint.description.DescriptionFactory.eINSTANCE
            .createUserFixedColor();
colorPallette.getEntries().add(fixedColor);
fixedColor.setBlue(226);
fixedColor.setGreen(189);
fixedColor.setRed(161);
</code>```

Then you add you use your style in your Node.

```<code> NodeMapping nmd = DescriptionFactory.eINSTANCE.createNodeMapping();
 SquareDescription sd = StyleFactory.eINSTANCE.createSquareDescription();
 sd.setColor(attributesFixedColor);
 nmd.setStyle(sd);
</code>```

Body:
Is there a "normal" way to Colorize the Nodes and Edges in the .ecore_diagram programaticaly?

My Code so far:

private static void saveDiagram(ResourceSet resourceSet,
        EPackage epackage, String path) {
    URI uri= URI.createFileURI(path);
    Resource overlapResource = resourceSet.createResource(uri, "ecore");

    overlapResource.getContents().add(epackage);
    Diagram d = createDiagram(epackage);

    URI diagUri = URI.createFileURI(path + "_diagram");
    Resource diagramResource = resourceSet.createResource(diagUri, "ecore");
    d.setName(diagUri.lastSegment());
    diagramResource.getContents().add(d);

    diagramResource.save(null); //In try catch block
    overlapResource.save(null); //In try catch block
}

public static Diagram createDiagram(EObject object) {
    Diagram diagram = NotationFactory.eINSTANCE.createDiagram();
    diagram.setMeasurementUnit(MeasurementUnit.PIXEL_LITERAL);
    diagram.setElement(object);
    diagram.setType("Ecore");
    return diagram;
}

I have the ecore file, ecore_diagram file and the EPackage...
I dont know.. should I go throw all EClasses and EReferences and ... what?

Thx for Help!

Body:
Here is a way for doing it in the case of a node for example :

In someway get the group of my odesign :

Group group = odesign.getGroup()

You  create first a UserColorPalette :

UserColorsPalette colorPallette = org.eclipse.sirius.viewpoint.description.DescriptionFactory.eINSTANCE
                .createUserColorsPalette();
group.getUserColorsPalettes().add(colorPallette);
UserFixedColor fixedColor = org.eclipse.sirius.viewpoint.description.DescriptionFactory.eINSTANCE
            .createUserFixedColor();
colorPallette.getEntries().add(fixedColor);
fixedColor.setBlue(226);
fixedColor.setGreen(189);
fixedColor.setRed(161);

Then you add you use your style in your Node.

 NodeMapping nmd = DescriptionFactory.eINSTANCE.createNodeMapping();
 SquareDescription sd = StyleFactory.eINSTANCE.createSquareDescription();
 sd.setColor(attributesFixedColor);
 nmd.setStyle(sd);


问:
Executing a TCL script from line N
I have a TCL script that say, has 30 lines of automation code which I am executing in the dc shell (Synopsys Design Compiler). I want to stop and exit the script at line 10, exit the dc shell and bring it back up again after performing a manual review. However, this time, I want to run the script starting from line number 11, without having to execute the first 10 lines.

Instead of having two scripts, one which contains code till line number 10 and the other having the rest, I would like to make use of only one script and try to execute it from, let's say, line number N.

Something like:
    source a.tcl -line 11

How can I do this?

答:
The simplest way is to open the text file, parse it to get the first N commands (info complete is useful there), and then evaluate those (or the rest of the script). Doing this efficiently produces slightly different code when you're dropping the tail as opposed to when you're dropping the prefix.

```<code>proc ReadAllLines {filename} {
    set f [open $filename]
    set lines {}
    # A little bit careful in case you're working with very large scripts
    while {[gets $f line] >= 0} {
        lappend lines $line
    }
    close $f
    return $lines
}

proc SourceFirstN {filename n} {
    set lines [ReadAllLines $filename]
    set i 0
    set script {}
    foreach line $lines {
        append script $line "\n"
        if {[info complete $script] && [incr i] >= $n} {
            break
        }
    }
    info script $filename
    unset lines
    uplevel 1 $script
}

proc SourceTailN {filename n} {
    set lines [ReadAllLines $filename]
    set i 0
    set script {}
    for {set j 0} {$j < [llength $lines]} {incr j} {
        set line [lindex $lines $j]
        append script $line "\n"
        if {[info complete $script]} {
            if {[incr i] >= $n} {
                info script $filename
                set realScript [join [lrange $lines [incr j] end] "\n"]
                unset lines script
                return [uplevel 1 $realScript]
            }
            # Dump the prefix we don't need any more
            set script {}
        }
    }
    # If we get here, the script had fewer than n lines so there's nothing to do
}
</code>```

Be aware that the kinds of files you're dealing with can get pretty large, and Tcl currently has some hard memory limits. On the other hand, if you can source the file at all, you're already within that limit…

Title: Executing a TCL script from line N

Body:
The simplest way is to open the text file, parse it to get the first N commands (info complete is useful there), and then evaluate those (or the rest of the script). Doing this efficiently produces slightly different code when you're dropping the tail as opposed to when you're dropping the prefix.

proc ReadAllLines {filename} {
    set f [open $filename]
    set lines {}
    # A little bit careful in case you're working with very large scripts
    while {[gets $f line] >= 0} {
        lappend lines $line
    }
    close $f
    return $lines
}

proc SourceFirstN {filename n} {
    set lines [ReadAllLines $filename]
    set i 0
    set script {}
    foreach line $lines {
        append script $line "\n"
        if {[info complete $script] && [incr i] >= $n} {
            break
        }
    }
    info script $filename
    unset lines
    uplevel 1 $script
}

proc SourceTailN {filename n} {
    set lines [ReadAllLines $filename]
    set i 0
    set script {}
    for {set j 0} {$j < [llength $lines]} {incr j} {
        set line [lindex $lines $j]
        append script $line "\n"
        if {[info complete $script]} {
            if {[incr i] >= $n} {
                info script $filename
                set realScript [join [lrange $lines [incr j] end] "\n"]
                unset lines script
                return [uplevel 1 $realScript]
            }
            # Dump the prefix we don't need any more
            set script {}
        }
    }
    # If we get here, the script had fewer than n lines so there's nothing to do
}

Be aware that the kinds of files you're dealing with can get pretty large, and Tcl currently has some hard memory limits. On the other hand, if you can source the file at all, you're already within that limit…