问:
How to change react-dates input css
I am using react-dates but I can't find any way of changing the css of the input field.

e.g. border, background color etc. since the regular css doesn't work with react-dates.

```<code><SingleDatePicker
    date={this.state.dateOfPurchase}
    onDateChange={date => {
        this.setState({ dateOfPurchase: date })

    }}
    focused={this.state.focused}
    onFocusChange={({ focused }) => this.setState({ focused })}
    id="your_unique_id"
    isOutsideRange={day => !isInclusivelyBeforeDay(day, moment())}
    numberOfMonths= "1"
/>
</code>```

答:
it is possible to create a component for encapsulating styles and connecting libraries styled-system and grid-styled

```<code>import {Box} from 'grid-styled'
import {themeGet} from 'styled-system'
</code>```

and

```<code>const StyledWrapp = Box.extend`
    .DateRangePickerInput {
        border-radius: 4px;
   `;
</code>```

Title: How to change react-dates input css

Body:
I am using react-dates but I can't find any way of changing the css of the input field.

e.g. border, background color etc. since the regular css doesn't work with react-dates.

<SingleDatePicker
    date={this.state.dateOfPurchase}
    onDateChange={date => {
        this.setState({ dateOfPurchase: date })

    }}
    focused={this.state.focused}
    onFocusChange={({ focused }) => this.setState({ focused })}
    id="your_unique_id"
    isOutsideRange={day => !isInclusivelyBeforeDay(day, moment())}
    numberOfMonths= "1"
/>

Body:
it is possible to create a component for encapsulating styles and connecting libraries styled-system and grid-styled

import {Box} from 'grid-styled'
import {themeGet} from 'styled-system'

and

const StyledWrapp = Box.extend`
    .DateRangePickerInput {
        border-radius: 4px;
   `;


来源: stackexchange

问:
Run a job with Spring @Scheduled annotation at two different times on different days of the week
I have a job that has to be run

at 8:00 on weekdays

at 10:00 on weekends

My thinking is - Either

the CRON expression has to handle both of it together so that it can be given inside the @Scheduled annotation

Otherwise, a single @Scheduled annotation has to take in 2 CRON expression.

Is this possible?

答:
If your method does exactly the same work then write it once and call it twice with two different CRONs.        </p>

```<code>public void doStuff(){
//do stuff
}

@Scheduled //With 8 AM Weekdays CRON
doStuff();

@Scheduled //With 10 AM Weekends CRON
doStuff();
</code>```

ContentLicense: CC BY-SA 4.0

Body:
If your method does exactly the same work then write it once and call it twice with two different CRONs.

public void doStuff(){
//do stuff
}

@Scheduled //With 8 AM Weekdays CRON
doStuff();

@Scheduled //With 10 AM Weekends CRON
doStuff();


问:
Fixed button on scroll
Managed to add a fixed button when I scroll down the page, but I want to have this hidden until a certain point (when the nav is out of view).

I will show you my code so far and you guys can hopefully show me where I have gone wrong.

CSS

```<code>.fixed-btn {
    position: fixed;
    top: 60px;
    right: 80px;
    height: 100px;
    z-index: 999;
    display: none;
}
</code>```

HTML

```<code><div class="fixed-btn">
    <a onclick="fatsomaEventsWidget.showEvent('akvmo30l')" href="#event_id=akvmo30l" class="btn btn--white-bg" href="#" role="button">Get Wristbands</a>
</div>
</code>```

JS

```<code>var wristbands = $(".fixed-btn");

wristbands.on("scroll", function (e) {

    if (this.scrollTop > 900) {
        wristbands.css('display: block;');
    } else {
        wristbands.css('display: none;');
    }

});
</code>```

答:
simply add this css to your div or button.. tag

```<code>style="position: sticky;"
</code>```

enjoy

ContentLicense: CC BY-SA 3.0

Title: Fixed button on scroll

Body:
Managed to add a fixed button when I scroll down the page, but I want to have this hidden until a certain point (when the nav is out of view).

I will show you my code so far and you guys can hopefully show me where I have gone wrong.

CSS

.fixed-btn {
    position: fixed;
    top: 60px;
    right: 80px;
    height: 100px;
    z-index: 999;
    display: none;
}

HTML

    Get Wristbands

JS

var wristbands = $(".fixed-btn");

wristbands.on("scroll", function (e) {

    if (this.scrollTop > 900) {
        wristbands.css('display: block;');
    } else {
        wristbands.css('display: none;');
    }

});

Body:
simply add this css to your div or button.. tag

style="position: sticky;"

enjoy


问:
Cant activate environment from Visual Studio Code
I use Python mostly in Spyder for data science. Both Visual Studio Code and virtual environments is fairly new to me.

Anyway, using the terminal in Visual Studio Code I try to switch between environments. I have tried both conda activate venv and activate venv. I get no error message but using conda env list to see which environment is active I seem stuck in Base.

Doing the same thing in the Anaconda Prompt I am allowed to switch between environments.

I use Windows and I start Visual Studio Code from the Anaconda Navigator.

What is going on?

答:
You need to set your VScode terminal as cmd.exe and not as PowerShell.

#########UPADTE##########

The solution under is deprecated, the new solution can be found in the documentation here:

#########################

Here is how to change your default terminal,

or you can change your settings.json file as follow:

```<code>"terminal.integrated.shell.windows": "C:\\Windows\\System32\\cmd.exe"
</code>```

From documentation:

Note: conda environments cannot be automatically activated in the
integrated terminal if PowerShell is set as the integrated shell.

Body:
You need to set your VScode terminal as cmd.exe and not as PowerShell.

#########UPADTE##########

The solution under is deprecated, the new solution can be found in the documentation here:

#########################

Here is how to change your default terminal,

or you can change your settings.json file as follow:

"terminal.integrated.shell.windows": "C:\\Windows\\System32\\cmd.exe"

From documentation:

Note: conda environments cannot be automatically activated in the
integrated terminal if PowerShell is set as the integrated shell.


问:
C++ Writing to file vector of byte
I have:

```<code>typedef unsigned char;
std::vector<byte> data;
</code>```

I tried to save data in file this way (but I have error):

```<code>fstream file(filename,ios::out);
file.write(&data, data.size());
</code>```

How to process or cast data to write it in file.

答:
A lot of these solutions are only partially complete (lacking includes & casts), so let me post a full working example:</p>

```<code>#include <vector>
#include <fstream>

int main()
{
    std::vector<std::byte> dataVector(10, std::byte{ 'Z' });

    const std::string filename = "C:\\test_file.txt";

    std::ofstream outfile(filename, std::ios::out | std::ios::binary);
    outfile.write(reinterpret_cast<const char*>(dataVector.data()), dataVector.size());

    return 0;
}
</code>```

Title: C++ Writing to file vector of byte

Body:
I have:

typedef unsigned char;
std::vector<byte> data;

I tried to save data in file this way (but I have error):

fstream file(filename,ios::out);
file.write(&data, data.size());

How to process or cast data to write it in file.

Body:
A lot of these solutions are only partially complete (lacking includes & casts), so let me post a full working example:

#include <vector>
#include <fstream>

int main()
{
    std::vector<std::byte> dataVector(10, std::byte{ 'Z' });

    const std::string filename = "C:\\test_file.txt";

    std::ofstream outfile(filename, std::ios::out | std::ios::binary);
    outfile.write(reinterpret_cast<const char*>(dataVector.data()), dataVector.size());

    return 0;
}


问:
PHP Fatal error: Allowed memory size of 2097152 bytes exhausted (tried to allocate 12288 bytes)
I know this is a repeated question, but I couldn't find a solution after trying all the answers discussed here.

When I run php bin/magento setup:upgrade command, it shows error like

PHP Fatal error:  Allowed memory size of 2097152 bytes exhausted (tried to allocate 12288 bytes) in /var/www/html/mysite/vendor/paragonie/sodium_compat/lib/sodium_compat.php on line 214

Modified memory_limit value in php.ini file, but still issue exists. Any other solutions for this problem?

答:
Make sure you edited the correct php.ini.PHP executed via the web server, and run via command line, often use two different ones

Just add this below line to before line of you getting error in your file

```<code>ini_set('memory_limit', '-1');
</code>```

It will take unlimited memory usage of server.

OR

in yourr PHP.ini file, change the line in PHP.ini
If your line shows 32M try 64M:
memory_limit = 64M ; Maximum amount of memory a script may consume (64MB)

If you don't have access to PHP.ini try adding this to an .htaccess file:
php_value memory_limit 64M

Body:
Make sure you edited the correct php.ini.PHP executed via the web server, and run via command line, often use two different ones

Just add this below line to before line of you getting error in your file

ini_set('memory_limit', '-1');

It will take unlimited memory usage of server.

OR

in yourr PHP.ini file, change the line in PHP.ini
If your line shows 32M try 64M:
memory_limit = 64M ; Maximum amount of memory a script may consume (64MB)

If you don't have access to PHP.ini try adding this to an .htaccess file:
php_value memory_limit 64M


问:
Where is the business logic in MVP design pattern?
I am trying to understand how the MVP pattern works using a simple example.

I want to show the box content when the user clicks a button.

function reveal(number){
  let content;
  if(number==1) content = "candy"
  else if(number==2) content = "chicken"
  else content = "pencil"
  document.getElementById("box").innerHTML = "It's a " + content
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button onclick="reveal(1)"> box 1</button>
<button onclick="reveal(2)"> box 2</button>
<button onclick="reveal(3)"> box 3</button><br>
<h3 id="box"> </h3></code>```

YES, I do know it is not the best idea to use such a complicated pattern for this snippet code. I just think this example would be really easy to understand.

Now my questions:

Should I put the logic (if...elseif..) in the presenter or in the model?

For Question 1, If I put the logic in the presenter, does that mean that the model will be useless?

答:
IMO it should go in the view, there is no need to go to the server and have to wait for a response, the data can all be loaded instantly when the user makes the selection.

the MVP pattern consists of

EventHandling = Presenter

DOM Manipulation = View

AJAX calls = Model

What you have shown is a clip of HTML and a small bit of the corresponding javascript, that together manipulate the DOM. It could be argued that the javascript part handles the event caused by the users selection and put it in the Presenter part of MVP

Body:
I am trying to understand how the MVP pattern works using a simple example.

I want to show the box content when the user clicks a button.

function reveal(number){
  let content;
  if(number==1) content = "candy"
  else if(number==2) content = "chicken"
  else content = "pencil"
  document.getElementById("box").innerHTML = "It's a " + content
}

<button onclick="reveal(1)"> box 1</button>
<button onclick="reveal(2)"> box 2</button>
<button onclick="reveal(3)"> box 3</button>

YES, I do know it is not the best idea to use such a complicated pattern for this snippet code. I just think this example would be really easy to understand.

Now my questions:

Should I put the logic (if...elseif..) in the presenter or in the model?

For Question 1, If I put the logic in the presenter, does that mean that the model will be useless?


问:
Multiply each row of one dataframe by all rows of a second dataframe
Am struggling with operation as my datasets are very large and i have provided an example of what i want.

I have two dataframes.

df1 - contains sampling-derived iterations for each parameter of a variable defined as the column name (10,000 rows)

df2 - contains the actual value of each of the variable defined as the column name (4,000 rows)

I want a df3 which is effectively the multiplication of each row of df2 by df1 and would therefore be 4000*10000 rows

As a short example i have provided a minimal example of df1 and df2. I have provided the output that i would be looking at shown in df3.

```<code>df1 <- structure(list(intercept = c(3.4, 3.6, 3.7), age = c(0.08, 0.05,
0.06), male = c(0.07, 0.06, 0.07)), class = "data.frame", row.names = c(NA,
-3L))

df2 <- structure(list(id = structure(1:2, .Label = c("a", "b"), class = "factor"),
intercept = c(1L, 1L), age = c(40L, 45L), male = 1:0), class = "data.frame", row.names = c(NA,
-2L))

df3 <- structure(list(id = structure(c(1L, 1L, 1L, 2L, 2L, 2L), .Label = c("a",
"b"), class = "factor"), intercept = c(3.4, 3.6, 3.7, 3.4, 3.6,
3.7), age = c(3.2, 2, 2.4, 3.6, 2.25, 2.7), male = c(0.07, 0.06,
0.07, 0, 0, 0)), class = "data.frame", row.names = c(NA, -6L))
</code>```

Can somebody point me to an efficient way to do this in R?

答:
You could repeat rows in both the dataframes based on number of rows in other dataframe and multiply them directly

```<code>df1[rep(seq(nrow(df1)), nrow(df2)),] * df2[rep(seq(nrow(df2)), each = nrow(df1)),-1]

#    intercept  age male
#1         3.4 3.20 0.07
#2         3.6 2.00 0.06
#3         3.7 2.40 0.07
#1.1       3.4 3.60 0.00
#2.1       3.6 2.25 0.00
#3.1       3.7 2.70 0.00
</code>```

To also get id column

```<code>new1 <- df1[rep(seq(nrow(df1)), nrow(df2)), ]
new2 <- df2[rep(seq(nrow(df2)), each = nrow(df1)),]
out <- cbind(new2[1], new1 * new2[-1])
rownames(out) <- NULL

out
#  id intercept  age male
#1  a       3.4 3.20 0.07
#2  a       3.6 2.00 0.06
#3  a       3.7 2.40 0.07
#4  b       3.4 3.60 0.00
#5  b       3.6 2.25 0.00
#6  b       3.7 2.70 0.00
</code>```

Body:
Am struggling with operation as my datasets are very large and i have provided an example of what i want.

I have two dataframes.

df1 - contains sampling-derived iterations for each parameter of a variable defined as the column name (10,000 rows)

df2 - contains the actual value of each of the variable defined as the column name (4,000 rows)

I want a df3 which is effectively the multiplication of each row of df2 by df1 and would therefore be 4000*10000 rows

As a short example i have provided a minimal example of df1 and df2. I have provided the output that i would be looking at shown in df3.

df1 <- structure(list(intercept = c(3.4, 3.6, 3.7), age = c(0.08, 0.05,
0.06), male = c(0.07, 0.06, 0.07)), class = "data.frame", row.names = c(NA,
-3L))

df2 <- structure(list(id = structure(1:2, .Label = c("a", "b"), class = "factor"),
intercept = c(1L, 1L), age = c(40L, 45L), male = 1:0), class = "data.frame", row.names = c(NA,
-2L))

df3 <- structure(list(id = structure(c(1L, 1L, 1L, 2L, 2L, 2L), .Label = c("a",
"b"), class = "factor"), intercept = c(3.4, 3.6, 3.7, 3.4, 3.6,
3.7), age = c(3.2, 2, 2.4, 3.6, 2.25, 2.7), male = c(0.07, 0.06,
0.07, 0, 0, 0)), class = "data.frame", row.names = c(NA, -6L))

Can somebody point me to an efficient way to do this in R?

Body:
You could repeat rows in both the dataframes based on number of rows in other dataframe and multiply them directly

df1[rep(seq(nrow(df1)), nrow(df2)),] * df2[rep(seq(nrow(df2)), each = nrow(df1)),-1]

#    intercept  age male
#1         3.4 3.20 0.07
#2         3.6 2.00 0.06
#3         3.7 2.40 0.07
#1.1       3.4 3.60 0.00
#2.1       3.6 2.25 0.00
#3.1       3.7 2.70 0.00

To also get id column

new1 <- df1[rep(seq(nrow(df1)), nrow(df2)), ]
new2 <- df2[rep(seq(nrow(df2)), each = nrow(df1)),]
out <- cbind(new2[1], new1 * new2[-1])
rownames(out) <- NULL

out
#  id intercept  age male
#1  a       3.4 3.20 0.07
#2  a       3.6 2.00 0.06
#3  a       3.7 2.40 0.07
#4  b       3.4 3.60 0.00
#5  b       3.6 2.25 0.00
#6  b       3.7 2.70 0.00


问:
Equal space after li of unordered list
I've removed dot(.) after the
 of
 and gave '|' after the number.

I've achieved it by using below code:

```<code>ol {
    counter-reset: item;
}
ol li::before {
    content: counter(item) " ";
    counter-increment: item;
    padding-right: 15px;
    border-right: 2.5px solid rgba(37, 194, 240, 0.8);
    margin-right: 15px;
}
</code>```

But the space after the numbers are not equal.

I need uniform spacing after the numbers.
Please help me to resolve this issue.

ol{counter-reset: item;columns: 2;}
ol li{display:block;margin-bottom:10px;}
ol li::before {
 content: counter(item) " ";
 counter-increment: item;
 padding-right: 15px;
 border-right: 2.5px solid rgba(37, 194, 240, 0.8);
 margin-right: 15px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ol>
<li>My abc</li>
<li>LiveColor</li>
<li>LiveFood</li>
<li>Ola</li>
<li>Uber</li>
<li>Good Chat</li>
<li>Food Panda</li>
<li>Domino'd</li>
<li>Clickfood</li>
<li>Smartyo</li>
<li>Tide</li>
<li>Webseries</li>
<li>GoPro</li>
<li>Liveshow</li>
</ol></code>```

In addition to it, the font-family is such a way that all the numbers have different spaces.

答:
Add a set width (say 3em)...and align the text to the right.

ol {
  counter-reset: item;
  columns: 2;
}

ol li {
  display: block;
  margin-bottom: 10px;
}

ol li::before {
  content: counter(item) " ";
  counter-increment: item;
  padding-right: 15px;
  border-right: 2.5px solid rgba(37, 194, 240, 0.8);
  margin-right: 15px;
  width: 3em;
  text-align: right;
  display: inline-block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ol>
  <li>My abc</li>
  <li>LiveColor</li>
  <li>LiveFood</li>
  <li>Ola</li>
  <li>Uber</li>
  <li>Good Chat</li>
  <li>Food Panda</li>
  <li>Domino'd</li>
  <li>Clickfood</li>
  <li>Smartyo</li>
  <li>Tide</li>
  <li>Webseries</li>
  <li>GoPro</li>
  <li>Liveshow</li>
</ol></code>```

Title: Equal space after li of unordered list

Body:
I've removed dot(.) after the
 of
 and gave '|' after the number.

I've achieved it by using below code:

ol {
    counter-reset: item;
}
ol li::before {
    content: counter(item) " ";
    counter-increment: item;
    padding-right: 15px;
    border-right: 2.5px solid rgba(37, 194, 240, 0.8);
    margin-right: 15px;
}

But the space after the numbers are not equal.

I need uniform spacing after the numbers.
Please help me to resolve this issue.

ol{counter-reset: item;columns: 2;}
ol li{display:block;margin-bottom:10px;}
ol li::before {
 content: counter(item) " ";
 counter-increment: item;
 padding-right: 15px;
 border-right: 2.5px solid rgba(37, 194, 240, 0.8);
 margin-right: 15px;
}

My abc

LiveColor

LiveFood

Ola

Uber

Good Chat

Food Panda

Domino'd

Clickfood

Smartyo

Tide

Webseries

GoPro

Liveshow

In addition to it, the font-family is such a way that all the numbers have different spaces.

Body:
Add a set width (say 3em)...and align the text to the right.

ol {
  counter-reset: item;
  columns: 2;
}

ol li {
  display: block;
  margin-bottom: 10px;
}

ol li::before {
  content: counter(item) " ";
  counter-increment: item;
  padding-right: 15px;
  border-right: 2.5px solid rgba(37, 194, 240, 0.8);
  margin-right: 15px;
  width: 3em;
  text-align: right;
  display: inline-block;
}

<ol>
  <li>My abc</li>
  <li>LiveColor</li>
  <li>LiveFood</li>
  <li>Ola</li>
  <li>Uber</li>
  <li>Good Chat</li>
  <li>Food Panda</li>
  <li>Domino'd</li>
  <li>Clickfood</li>
  <li>Smartyo</li>
  <li>Tide</li>
  <li>Webseries</li>
  <li>GoPro</li>
  <li>Liveshow</li>
</ol>


问:
Android - Custom Button gets stuck "Pressed"
I've created a custom button in my Android app that has basically two different views.  There is an image for when the button isn't being pressed and another image for use while it is being pressed.  Below is how I've implemented the button and how it responds to the user.

```<code>private void registerListeners() {

    calcButton.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            calcButton.requestFocusFromTouch();
            calcButton.setImageResource(R.drawable.calc_button_pressed);
            return false;
        }
    });

    calcButton.setOnFocusChangeListener(new View.OnFocusChangeListener() {

        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            calcButton.setImageResource(R.drawable.calc_button_not_pressed);
        }
    });

    calcButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            mathCalculation();
            calcButton.setImageResource(R.drawable.calc_button_not_pressed);
        }
    });
}
</code>```

My problem is that there is a "bug" where if the user touches the button and drags their figure off the button the button stay pressed down.  The one work around I've implemented above is the "setOnFocusChangeListener" so once the user select something it else it will pop back up.

I want to have it so the button pops back out when the user drags there touched figure off the button.

All suggestions are greatly appreciated!!!

Thank you,

答:
It's because the click event "happens" only when touching and releasing. If you're touching and moving outside that's not a click.

To do what you want use a StateListDrawable, it's made just for that.

Body:
I've created a custom button in my Android app that has basically two different views.  There is an image for when the button isn't being pressed and another image for use while it is being pressed.  Below is how I've implemented the button and how it responds to the user.

private void registerListeners() {

    calcButton.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            calcButton.requestFocusFromTouch();
            calcButton.setImageResource(R.drawable.calc_button_pressed);
            return false;
        }
    });

    calcButton.setOnFocusChangeListener(new View.OnFocusChangeListener() {

        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            calcButton.setImageResource(R.drawable.calc_button_not_pressed);
        }
    });

    calcButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            mathCalculation();
            calcButton.setImageResource(R.drawable.calc_button_not_pressed);
        }
    });
}

My problem is that there is a "bug" where if the user touches the button and drags their figure off the button the button stay pressed down.  The one work around I've implemented above is the "setOnFocusChangeListener" so once the user select something it else it will pop back up.

I want to have it so the button pops back out when the user drags there touched figure off the button.

All suggestions are greatly appreciated!!!

Thank you,


问:
How does OkHttp get Json string?
Solution:
It was a mistake on my side.

The right way is response.body().string() other than response.body.toString()

Im using Jetty servlet, the URL ishttp://172.16.10.126:8789/test/path/jsonpage, every time request this URL it will return

```<code>{"employees":[
    {"firstName":"John", "lastName":"Doe"},
    {"firstName":"Anna", "lastName":"Smith"},
    {"firstName":"Peter", "lastName":"Jones"}
]}
</code>```

It shows up when type the url into a browser, unfortunately it shows kind of memory address other than the json string when I request with Okhttp.

```<code>TestActivity﹕ com.squareup.okhttp.internal.http.RealResponseBody@537a7f84
</code>```

The Okhttp code Im using:

```<code>OkHttpClient client = new OkHttpClient();

String run(String url) throws IOException {
  Request request = new Request.Builder()
      .url(url)
      .build();

  Response response = client.newCall(request).execute();
  return response.body().string();
}
</code>```

Can anyone helpe?

答:
Below code is for getting data from online server using GET method and okHTTP library for android kotlin...

Log.e("Main",response.body!!.string())

in above line !! is the thing using which you can get the json from response body

```<code>val client = OkHttpClient()
            val request: Request = Request.Builder()
                .get()
                .url("http://172.16.10.126:8789/test/path/jsonpage")
                .addHeader("", "")
                .addHeader("", "")
                .build()
            client.newCall(request).enqueue(object : Callback {
                override fun onFailure(call: Call, e: IOException) {
                    // Handle this
                    Log.e("Main","Try again latter!!!")
                }

                override fun onResponse(call: Call, response: Response) {
                    // Handle this
                    Log.e("Main",response.body!!.string())
                }
            })
</code>```

Title: How does OkHttp get Json string?

Body:
Solution:
It was a mistake on my side.

The right way is response.body().string() other than response.body.toString()

Im using Jetty servlet, the URL ishttp://172.16.10.126:8789/test/path/jsonpage, every time request this URL it will return

{"employees":[
    {"firstName":"John", "lastName":"Doe"},
    {"firstName":"Anna", "lastName":"Smith"},
    {"firstName":"Peter", "lastName":"Jones"}
]}

It shows up when type the url into a browser, unfortunately it shows kind of memory address other than the json string when I request with Okhttp.

TestActivity﹕ com.squareup.okhttp.internal.http.RealResponseBody@537a7f84

The Okhttp code Im using:

OkHttpClient client = new OkHttpClient();

String run(String url) throws IOException {
  Request request = new Request.Builder()
      .url(url)
      .build();

  Response response = client.newCall(request).execute();
  return response.body().string();
}

Can anyone helpe?

Body:
Below code is for getting data from online server using GET method and okHTTP library for android kotlin...

Log.e("Main",response.body!!.string())

in above line !! is the thing using which you can get the json from response body

val client = OkHttpClient()
            val request: Request = Request.Builder()
                .get()
                .url("http://172.16.10.126:8789/test/path/jsonpage")
                .addHeader("", "")
                .addHeader("", "")
                .build()
            client.newCall(request).enqueue(object : Callback {
                override fun onFailure(call: Call, e: IOException) {
                    // Handle this
                    Log.e("Main","Try again latter!!!")
                }

                override fun onResponse(call: Call, response: Response) {
                    // Handle this
                    Log.e("Main",response.body!!.string())
                }
            })


问:
Iterate a SQL Query through multiple parameters one at a time and union the results
I have a query I have written for SQL Server 2012 to take a dynamic list of personnel and determine how long they spend each day in certain areas. When I run the query a person at a time, I get good results. However, if I pass all the parameters within an IN clause then I not only get less results, but some of the values are different and just plain wrong.

This will eventually be run within a report in SSRS, but even running the data straight in SSMS it is showing the same behavior.

The @People is a separate query that gathers a list of the people which were actually in the area that day. @Yesterday and @Today are just variables for dates.

```<code>SELECT *
FROM
    (SELECT
         AdmitType,
         Time,
         Person,
         Door,
         Direction,
         CASE
            WHEN Direction LIKE 'In' AND LEAD(Direction, 1) OVER(ORDER BY Time ASC) LIKE 'Out'
               THEN DATEDIFF (second, Time, LEAD(Time, 1) OVER(ORDER BY Time ASC))
               ELSE NULL
         END AS 'Duration'
     FROM
         ActivityLog
     WHERE
         Door IN ('Room1', 'Room2', 'Room3')
         AND Time BETWEEN @Yesterday AND @Today
         AND Person IN @People) s1
ORDER BY
    Person, Door, Time ASC
</code>```

If I run the above query and pass the @People parameter with a value of ('Tom', 'Dick', 'Harry') then I will get something like this back for Tom's entries (eliminating some columns and multiple people and doors for clarity):

```<code>Time    Direction    Duration
-----------------------------
7:12:04 IN           922
7:27:26 OUT          NULL
8:40:37 IN           NULL
9:07:04 OUT          NULL
</code>```

But If I run the query with just Tom listed in the IN clause, I get the following which is correct:

```<code>Time    Direction    Duration
-----------------------------
7:12:04 IN           922
7:27:26 OUT          NULL
8:40:37 IN           1587
9:07:04 OUT          NULL
</code>```

How can I either fix my query so that it returns the correct information with everyone selected (approximately 25 people usually) or take the parameter and run each person one at a time and union the results?

I have seen a query which passes a list one at a time and unions all the results, but I do not know how to write that in such a way as to accept the parameter input that would be passed from SSRS.

Additional Data Added from Alan Schofield suggestion:
When I added the PARTITION BY Clause I am now getting data for those previous NULLs, but it is not correct data.

```<code>SELECT *
FROM
    (SELECT
         AdmitType,
         Time,
         Person,
         Door,
         Direction,
         CASE
            WHEN Direction LIKE 'In' AND LEAD(Direction, 1) OVER(PARTITION BY Person, Door ORDER BY Time ASC) LIKE 'Out'
               THEN DATEDIFF (second, Time, LEAD(Time, 1) OVER(ORDER BY Time ASC))
               ELSE NULL
         END AS 'Duration'
     FROM
         ActivityLog
     WHERE
         Door IN ('Room1', 'Room2', 'Room3')
         AND Time BETWEEN @Yesterday AND @Today
         AND Person IN @People) s1
ORDER BY
    Person, Door, Time ASC
</code>```

HERE is a larger example data set with the new PARTITION BY clause results:

```<code>Time      Person     Door    Direction    Duration
18:07:22  John       Room1   IN           1308  (Correct)
18:29:10  John       Room1   Out          NULL
17:42:18  John       Room3   IN           1406  (Correct)
18:05:44  John       Room3   Out          NULL
7:12:04   Tom        Room1   IN           922   (Correct)
7:27:26   Tom        Room1   Out          NULL
8:40:37   Tom        Room1   IN           2    (Previously NULL, Now 2, should be 1587 and is when queried alone)
9:07:04   Tom        Room1   Out          NULL
9:09:07   Tom        Room1   IN           31   (Previously NULL, Now 31, should be 1256 and is when queried alone)
9:30:03   Tom        Room1   Out          NULL
9:38:48   Tom        Room1   IN           48   (Correct)
9:39:36   Tom        Room1   Out          NULL
9:39:45   Tom        Room1   Out          NULL
9:40:36   Tom        Room1   IN           90   (Correct)
9:42:06   Tom        Room1   Out          NULL
10:25:0   Tom        Room1   IN           47   (Previously 47, Now 47, Should be 8939 and is when queried alone)
12:54:08  Tom        Room1   Out          NULL
14:09:42  Tom        Room1   IN           39   (Correct)
14:10:21  Tom        Room1   Out          NULL
14:39:03  Tom        Room1   IN           1316 (Previously NULL, Now 1316, should be 4178 and is when queried alone)
15:48:41  Tom        Room1   Out          NULL
15:49:20  Tom        Room1   IN           52   (Previously NULL, Now 52, should be 1542 and is when queried alone)
16:15:02  Tom        Room1   Out          NULL
16:22:26  Tom        Room1   IN           292  (Previously 292, Now 292, should be 1504 and is when queried alone)
16:47:30  Tom        Room1   Out          NULL
</code>```

The data continues a lot more but hopefully this gives a better idea.

答:
It looks like you need to add a PARTITION BY to you Windowed functions. At the moment

```<code>LEAD(Direction, 1) OVER(ORDER BY Time ASC)
</code>```

Is looking for the next record, regardless of which person is referenced in the record. Try adding the PARTITION BY clause to the relevant windowed functons.

```<code>LEAD(Direction, 1) OVER(PARTITION BY Person ORDER BY Time ASC)
</code>```

I'm not sure if you need to include Door in windowed functions too, hard to know without seeing the data.
If this does not help, please edit your question to show some sample data and expected results based on the sample data.

Body:
I have a query I have written for SQL Server 2012 to take a dynamic list of personnel and determine how long they spend each day in certain areas. When I run the query a person at a time, I get good results. However, if I pass all the parameters within an IN clause then I not only get less results, but some of the values are different and just plain wrong.

This will eventually be run within a report in SSRS, but even running the data straight in SSMS it is showing the same behavior.

The @People is a separate query that gathers a list of the people which were actually in the area that day. @Yesterday and @Today are just variables for dates.

SELECT *
FROM
    (SELECT
         AdmitType,
         Time,
         Person,
         Door,
         Direction,
         CASE
            WHEN Direction LIKE 'In' AND LEAD(Direction, 1) OVER(ORDER BY Time ASC) LIKE 'Out'
               THEN DATEDIFF (second, Time, LEAD(Time, 1) OVER(ORDER BY Time ASC))
               ELSE NULL
         END AS 'Duration'
     FROM
         ActivityLog
     WHERE
         Door IN ('Room1', 'Room2', 'Room3')
         AND Time BETWEEN @Yesterday AND @Today
         AND Person IN @People) s1
ORDER BY
    Person, Door, Time ASC

If I run the above query and pass the @People parameter with a value of ('Tom', 'Dick', 'Harry') then I will get something like this back for Tom's entries (eliminating some columns and multiple people and doors for clarity):

Time    Direction    Duration
-----------------------------
7:12:04 IN           922
7:27:26 OUT          NULL
8:40:37 IN           NULL
9:07:04 OUT          NULL

But If I run the query with just Tom listed in the IN clause, I get the following which is correct:

Time    Direction    Duration
-----------------------------
7:12:04 IN           922
7:27:26 OUT          NULL
8:40:37 IN           1587
9:07:04 OUT          NULL

How can I either fix my query so that it returns the correct information with everyone selected (approximately 25 people usually) or take the parameter and run each person one at a time and union the results?

I have seen a query which passes a list one at a time and unions all the results, but I do not know how to write that in such a way as to accept the parameter input that would be passed from SSRS.

Additional Data Added from Alan Schofield suggestion:
When I added the PARTITION BY Clause I am now getting data for those previous NULLs, but it is not correct data.

SELECT *
FROM
    (SELECT
         AdmitType,
         Time,
         Person,
         Door,
         Direction,
         CASE
            WHEN Direction LIKE 'In' AND LEAD(Direction, 1) OVER(PARTITION BY Person, Door ORDER BY Time ASC) LIKE 'Out'
               THEN DATEDIFF (second, Time, LEAD(Time, 1) OVER(ORDER BY Time ASC))
               ELSE NULL
         END AS 'Duration'
     FROM
         ActivityLog
     WHERE
         Door IN ('Room1', 'Room2', 'Room3')
         AND Time BETWEEN @Yesterday AND @Today
         AND Person IN @People) s1
ORDER BY
    Person, Door, Time ASC

HERE is a larger example data set with the new PARTITION BY clause results:

Time      Person     Door    Direction    Duration
18:07:22  John       Room1   IN           1308  (Correct)
18:29:10  John       Room1   Out          NULL
17:42:18  John       Room3   IN           1406  (Correct)
18:05:44  John       Room3   Out          NULL
7:12:04   Tom        Room1   IN           922   (Correct)
7:27:26   Tom        Room1   Out          NULL
8:40:37   Tom        Room1   IN           2    (Previously NULL, Now 2, should be 1587 and is when queried alone)
9:07:04   Tom        Room1   Out          NULL
9:09:07   Tom        Room1   IN           31   (Previously NULL, Now 31, should be 1256 and is when queried alone)
9:30:03   Tom        Room1   Out          NULL
9:38:48   Tom        Room1   IN           48   (Correct)
9:39:36   Tom        Room1   Out          NULL
9:39:45   Tom        Room1   Out          NULL
9:40:36   Tom        Room1   IN           90   (Correct)
9:42:06   Tom        Room1   Out          NULL
10:25:0   Tom        Room1   IN           47   (Previously 47, Now 47, Should be 8939 and is when queried alone)
12:54:08  Tom        Room1   Out          NULL
14:09:42  Tom        Room1   IN           39   (Correct)
14:10:21  Tom        Room1   Out          NULL
14:39:03  Tom        Room1   IN           1316 (Previously NULL, Now 1316, should be 4178 and is when queried alone)
15:48:41  Tom        Room1   Out          NULL
15:49:20  Tom        Room1   IN           52   (Previously NULL, Now 52, should be 1542 and is when queried alone)
16:15:02  Tom        Room1   Out          NULL
16:22:26  Tom        Room1   IN           292  (Previously 292, Now 292, should be 1504 and is when queried alone)
16:47:30  Tom        Room1   Out          NULL

The data continues a lot more but hopefully this gives a better idea.

Body:
It looks like you need to add a PARTITION BY to you Windowed functions. At the moment

LEAD(Direction, 1) OVER(ORDER BY Time ASC)

Is looking for the next record, regardless of which person is referenced in the record. Try adding the PARTITION BY clause to the relevant windowed functons.

LEAD(Direction, 1) OVER(PARTITION BY Person ORDER BY Time ASC)

I'm not sure if you need to include Door in windowed functions too, hard to know without seeing the data.
If this does not help, please edit your question to show some sample data and expected results based on the sample data.


问:
Spring boot call to a Sql file
I have a small query regarding the Spring boot logic of calling the sql files. I know that the schema sql files are called automatically if they are kept inside the resource directory of the spring boot app project.
But i would like to call them from a different directory. I have written the below code to try and achieve that but fails with below error message.

Code :

```<code>public void executeSqlScript()throws SQLException{
  Connection connection = dataSource.getConnection();
  connection.setAutoCommit(false);
  ScriptUtils.executeSqlScript(connection, new EncodedResource(new ClassPathResource("C:\\react-file-upload-master\\createConfigurationTableAndData.sql")));
  connection.commit();
}
</code>```

Error Message : java.io.FileNotFoundException: class path resource [C:/react-file-upload-master/createConfigurationTableAndData.sql] cannot be opened because it does not exist.

Its is not reading my directory. Would be greatfull if you could educate me on the same. Thank you.

答:
try using FileSystemResource instead of ClassPathResource and give absolute path.

```<code>public void executeSqlScript()throws SQLException{
  Connection connection = dataSource.getConnection();
  connection.setAutoCommit(false);
  ScriptUtils.executeSqlScript(connection, new FileSystemResource("C:\\react-file-upload-master\\createConfigurationTableAndData.sql"));
  connection.commit();
}
</code>```

because ClassPathResource will point to class path only. assuming your file is not in classpath.

Title: Spring boot call to a Sql file

Body:
I have a small query regarding the Spring boot logic of calling the sql files. I know that the schema sql files are called automatically if they are kept inside the resource directory of the spring boot app project.
But i would like to call them from a different directory. I have written the below code to try and achieve that but fails with below error message.

Code :

public void executeSqlScript()throws SQLException{
  Connection connection = dataSource.getConnection();
  connection.setAutoCommit(false);
  ScriptUtils.executeSqlScript(connection, new EncodedResource(new ClassPathResource("C:\\react-file-upload-master\\createConfigurationTableAndData.sql")));
  connection.commit();
}

Error Message : java.io.FileNotFoundException: class path resource [C:/react-file-upload-master/createConfigurationTableAndData.sql] cannot be opened because it does not exist.

Its is not reading my directory. Would be greatfull if you could educate me on the same. Thank you.

Body:
try using FileSystemResource instead of ClassPathResource and give absolute path.

public void executeSqlScript()throws SQLException{
  Connection connection = dataSource.getConnection();
  connection.setAutoCommit(false);
  ScriptUtils.executeSqlScript(connection, new FileSystemResource("C:\\react-file-upload-master\\createConfigurationTableAndData.sql"));
  connection.commit();
}

because ClassPathResource will point to class path only. assuming your file is not in classpath.


问:
Using dash upload component to upload csv file and generate a graph
I want to upload a csv file and generate a graph that outputs the data from the csv file, I am able to upload the csv and display the data using dash_table, but I am unable to get the graph to work.
My error after uploading the csv file: Invalid argument figure.data passed into Graph with ID "Mygraph".
Expected an array.
Was supplied type object.

```<code>import base64
import datetime
import io
import plotly.graph_objs as go
import cufflinks as cf

import dash
from dash.dependencies import Input, Output, State
import dash_core_components as dcc
import dash_html_components as html
import dash_table

import pandas as pd

external_stylesheets = ["https://codepen.io/chriddyp/pen/bWLwgP.css"]

app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
server = app.server

colors = {"graphBackground": "#F5F5F5", "background": "#ffffff", "text": "#000000"}

app.layout = html.Div(
    [
        dcc.Upload(
            id="upload-data",
            children=html.Div(["Drag and Drop or ", html.A("Select Files")]),
            style={
                "width": "100%",
                "height": "60px",
                "lineHeight": "60px",
                "borderWidth": "1px",
                "borderStyle": "dashed",
                "borderRadius": "5px",
                "textAlign": "center",
                "margin": "10px",
            },
            # Allow multiple files to be uploaded
            multiple=True,
        ),
        dcc.Graph(id="Mygraph"),
        html.Div(id="output-data-upload"),
    ]
)

@app.callback(
    Output("Mygraph", "figure"),
    [Input("upload-data", "contents"), Input("upload-data", "filename")],
)
def update_graph(contents, filename):
    fig = {
        "layout": go.Layout(
            plot_bgcolor=colors["graphBackground"],
            paper_bgcolor=colors["graphBackground"],
        )
    }

    if contents:
        contents = contents[0]
        filename = filename[0]
        df = parse_data(contents, filename)
        df = df.set_index(df.columns[0])
        fig["data"] = df.iplot(
            asFigure=True, kind="scatter", mode="lines+markers", size=1
        )

    return fig

def parse_data(contents, filename):
    content_type, content_string = contents.split(",")

    decoded = base64.b64decode(content_string)
    try:
        if "csv" in filename:
            # Assume that the user uploaded a CSV or TXT file
            df = pd.read_csv(io.StringIO(decoded.decode("utf-8")))
        elif "xls" in filename:
            # Assume that the user uploaded an excel file
            df = pd.read_excel(io.BytesIO(decoded))
        elif "txt" or "tsv" in filename:
            # Assume that the user upl, delimiter = r'\s+'oaded an excel file
            df = pd.read_csv(io.StringIO(decoded.decode("utf-8")), delimiter=r"\s+")
    except Exception as e:
        print(e)
        return html.Div(["There was an error processing this file."])

    return df

@app.callback(
    Output("output-data-upload", "children"),
    [Input("upload-data", "contents"), Input("upload-data", "filename")],
)

def update_table(contents, filename):
    table = html.Div()

    if contents:
        contents = contents[0]
        filename = filename[0]
        df = parse_data(contents, filename)

        table = html.Div(
            [
                html.H5(filename),
                dash_table.DataTable(
                    data=df.to_dict("rows"),
                    columns=[{"name": i, "id": i} for i in df.columns],
                ),
                html.Hr(),
                html.Div("Raw Content"),
                html.Pre(
                    contents[0:200] + "...",
                    style={"whiteSpace": "pre-wrap", "wordBreak": "break-all"},
                ),
            ]
        )

    return table

if __name__ == "__main__":
    app.run_server(debug=True)
</code>```

Error:

答:
You need to create a go.Figure object and return it, e.g.:

```<code>@app.callback(Output('Mygraph', 'figure'), [
Input('upload-data', 'contents'),
Input('upload-data', 'filename')
])
def update_graph(contents, filename):
    x = []
    y = []
    if contents:
        contents = contents[0]
        filename = filename[0]
        df = parse_data(contents, filename)
        df = df.set_index(df.columns[0])
        x=df['DATE']
        y=df['TMAX']
    fig = go.Figure(
        data=[
            go.Scatter(
                x=x,
                y=y,
                mode='lines+markers')
            ],
        layout=go.Layout(
            plot_bgcolor=colors["graphBackground"],
            paper_bgcolor=colors["graphBackground"]
        ))
    return fig
</code>```

Depending on what kind of graph you want (e.g. go.Scatter) and the type of values to display (x and y values).
To add more lines to the plot, you can add more go.Scatter objects to data array with different values.

Body:
I want to upload a csv file and generate a graph that outputs the data from the csv file, I am able to upload the csv and display the data using dash_table, but I am unable to get the graph to work.
My error after uploading the csv file: Invalid argument figure.data passed into Graph with ID "Mygraph".
Expected an array.
Was supplied type object.

import base64
import datetime
import io
import plotly.graph_objs as go
import cufflinks as cf

import dash
from dash.dependencies import Input, Output, State
import dash_core_components as dcc
import dash_html_components as html
import dash_table

import pandas as pd

external_stylesheets = ["https://codepen.io/chriddyp/pen/bWLwgP.css"]

app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
server = app.server

colors = {"graphBackground": "#F5F5F5", "background": "#ffffff", "text": "#000000"}

app.layout = html.Div(
    [
        dcc.Upload(
            id="upload-data",
            children=html.Div(["Drag and Drop or ", html.A("Select Files")]),
            style={
                "width": "100%",
                "height": "60px",
                "lineHeight": "60px",
                "borderWidth": "1px",
                "borderStyle": "dashed",
                "borderRadius": "5px",
                "textAlign": "center",
                "margin": "10px",
            },
            # Allow multiple files to be uploaded
            multiple=True,
        ),
        dcc.Graph(id="Mygraph"),
        html.Div(id="output-data-upload"),
    ]
)

@app.callback(
    Output("Mygraph", "figure"),
    [Input("upload-data", "contents"), Input("upload-data", "filename")],
)
def update_graph(contents, filename):
    fig = {
        "layout": go.Layout(
            plot_bgcolor=colors["graphBackground"],
            paper_bgcolor=colors["graphBackground"],
        )
    }

    if contents:
        contents = contents[0]
        filename = filename[0]
        df = parse_data(contents, filename)
        df = df.set_index(df.columns[0])
        fig["data"] = df.iplot(
            asFigure=True, kind="scatter", mode="lines+markers", size=1
        )

    return fig

def parse_data(contents, filename):
    content_type, content_string = contents.split(",")

    decoded = base64.b64decode(content_string)
    try:
        if "csv" in filename:
            # Assume that the user uploaded a CSV or TXT file
            df = pd.read_csv(io.StringIO(decoded.decode("utf-8")))
        elif "xls" in filename:
            # Assume that the user uploaded an excel file
            df = pd.read_excel(io.BytesIO(decoded))
        elif "txt" or "tsv" in filename:
            # Assume that the user upl, delimiter = r'\s+'oaded an excel file
            df = pd.read_csv(io.StringIO(decoded.decode("utf-8")), delimiter=r"\s+")
    except Exception as e:
        print(e)
        return html.Div(["There was an error processing this file."])

    return df

@app.callback(
    Output("output-data-upload", "children"),
    [Input("upload-data", "contents"), Input("upload-data", "filename")],
)

def update_table(contents, filename):
    table = html.Div()

    if contents:
        contents = contents[0]
        filename = filename[0]
        df = parse_data(contents, filename)

        table = html.Div(
            [
                html.H5(filename),
                dash_table.DataTable(
                    data=df.to_dict("rows"),
                    columns=[{"name": i, "id": i} for i in df.columns],
                ),
                html.Hr(),
                html.Div("Raw Content"),
                html.Pre(
                    contents[0:200] + "...",
                    style={"whiteSpace": "pre-wrap", "wordBreak": "break-all"},
                ),
            ]
        )

    return table

if __name__ == "__main__":
    app.run_server(debug=True)

Error:

Body:
You need to create a go.Figure object and return it, e.g.:

@app.callback(Output('Mygraph', 'figure'), [
Input('upload-data', 'contents'),
Input('upload-data', 'filename')
])
def update_graph(contents, filename):
    x = []
    y = []
    if contents:
        contents = contents[0]
        filename = filename[0]
        df = parse_data(contents, filename)
        df = df.set_index(df.columns[0])
        x=df['DATE']
        y=df['TMAX']
    fig = go.Figure(
        data=[
            go.Scatter(
                x=x,
                y=y,
                mode='lines+markers')
            ],
        layout=go.Layout(
            plot_bgcolor=colors["graphBackground"],
            paper_bgcolor=colors["graphBackground"]
        ))
    return fig

Depending on what kind of graph you want (e.g. go.Scatter) and the type of values to display (x and y values).
To add more lines to the plot, you can add more go.Scatter objects to data array with different values.


问:
How to change the background color for Bootstrap's carousel plugin?
So I'm having trouble trying to change the background color for the carousel. No matter what I do, it seems like the background is always white. I used the code from https://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_carousel&stacked=h for my carousel.

```<code><div class="container" id="slides">
  <div id="myCarousel" class="carousel slide" data-ride="carousel">
    <!-- Indicators -->
    <ol class="carousel-indicators">
      <li data-target="#myCarousel" data-slide-to="0" class="active"></li>
      <li data-target="#myCarousel" data-slide-to="1"></li>
      <li data-target="#myCarousel" data-slide-to="2"></li>
    </ol>

    <!-- Wrapper for slides -->
    <div class="carousel-inner">
      <div class="item active">
        <img src="https://photos-3.dropbox.com/t/2/AADPmL6gjWHr1iYlah93suqa28cVuGlQ32aryhnqDI5JzA/12/611886439/jpeg/32x32/1/_/1/2/ConnectK%20carousel.jpg/ELbFkPkEGO0BIAIoAg/3oq_ZcBwruMHDZh7EsNU5B8UTbQE8n0KIgLWHmtklMQ?size=1280x960&size_mode=3" alt="Connect K project" style="width:100%;">
      </div>

      <div class="item">
        <img src="https://photos-4.dropbox.com/t/2/AADn_i5Z_NwIjiBSH8pnZB7nPAYz-tmRqxlDtEMGsRfOww/12/611886439/jpeg/32x32/1/_/1/2/DigitalBraille.jpg/ELbFkPkEGO0BIAIoAg/TzOhuN9b1r5yKEmQ43BWI7NkmaaSwdLR0ikRW4DnaXc?size=1280x960&size_mode=3" alt="Chicago" style="width:100%;">
      </div>

      <div class="item">
        <img src="https://photos-4.dropbox.com/t/2/AADJdh6q_qeKgWjhsL07M2NQH81JFg8Mx51O7G60oeRlGw/12/611886439/jpeg/32x32/1/_/1/2/MedAppJam.JPG/ELbFkPkEGPMBIAIoAg/aQ1lqISwGTPXaGi6jgbJoeMmDcQUtcKoIyWTrZADmPI?size=1280x960&size_mode=3" alt="MedAppJam project" style="width:100%;">
      </div>
    </div>

    <!-- Left and right controls -->
    <a class="left carousel-control" href="#myCarousel" data-slide="prev">
      <span class="glyphicon glyphicon-chevron-left"></span>
      <span class="sr-only">Previous</span>
    </a>
    <a class="right carousel-control" href="#myCarousel" data-slide="next">
      <span class="glyphicon glyphicon-chevron-right"></span>
      <span class="sr-only">Next</span>
    </a>
  </div>
</div>
</code>```

I've tried using CSS styles to change the background but for some reason, it doesn't seem to work. And I'm not sure why. Here's the CSS I added to try to change the background color.

```<code>#slides{
  color: grey;
  background-color: grey !important;
}

.carousel{
  color: grey;
  background-color: grey !important;
}
.carousel .item{
  color: grey;
  background-color: grey;
}
</code>```

https://codepen.io/chukt/pen/wqQqyL?editors=1100#0 That's the link to my complete code. Sorry for all the weird colors. I was just messing around with it. Anyway, I've also checked out other questions like this one change twitter bootstrap carousel background? and it doesn't seem to work. Can anyone explain this to me?

答:
Simply use the already existing class "carousel-inner" in your css file as below, here for example change the background color to black :</p>

```<code>.carousel-inner {
background-color: black !important;
}
</code>```

Body:
So I'm having trouble trying to change the background color for the carousel. No matter what I do, it seems like the background is always white. I used the code from https://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_carousel&stacked=h for my carousel.

      Previous

      Next

I've tried using CSS styles to change the background but for some reason, it doesn't seem to work. And I'm not sure why. Here's the CSS I added to try to change the background color.

#slides{
  color: grey;
  background-color: grey !important;
}

.carousel{
  color: grey;
  background-color: grey !important;
}
.carousel .item{
  color: grey;
  background-color: grey;
}

https://codepen.io/chukt/pen/wqQqyL?editors=1100#0 That's the link to my complete code. Sorry for all the weird colors. I was just messing around with it. Anyway, I've also checked out other questions like this one change twitter bootstrap carousel background? and it doesn't seem to work. Can anyone explain this to me?

Body:
Simply use the already existing class "carousel-inner" in your css file as below, here for example change the background color to black :

.carousel-inner {
background-color: black !important;
}


问:
Assign the same color choosen randomly from an array to all element with the same class
I have this function to assign the same color choosen randomly from an array to all elements with the same class but the elements get different colors at same time.
Now the function works but each h2 element get different color.
I would like to have that all the h2 element with "change_color" class get the same color every time.

```<code>jQuery(document).ready(function() {
var colors = ["#FFB24A", "#ED145B", "#55D3D2", "#E8390F", "#787878"];
jQuery(".change_color h2").each(function() {
    jQuery(this).css("color", colors[Math.floor(Math.random() * colors.length)]);
});
});
</code>```

What do I need to change to apply the same color to all the elements?
Thank you.

答:
The way you have implemented calculates the range for each iteration. First, you need to get the random color, then you assign to all H2.</p>

```<code>jQuery(document).ready(function() {
    var colors = ["#FFB24A", "#ED145B", "#55D3D2", "#E8390F", "#787878"];
    var randomColor = colors[Math.floor(Math.random() * colors.length)];
    jQuery(".change_color h2").each(function() {
        jQuery(this).css("color", randomColor);
    });
});
</code>```

Body:
I have this function to assign the same color choosen randomly from an array to all elements with the same class but the elements get different colors at same time.
Now the function works but each h2 element get different color.
I would like to have that all the h2 element with "change_color" class get the same color every time.

jQuery(document).ready(function() {
var colors = ["#FFB24A", "#ED145B", "#55D3D2", "#E8390F", "#787878"];
jQuery(".change_color h2").each(function() {
    jQuery(this).css("color", colors[Math.floor(Math.random() * colors.length)]);
});
});

What do I need to change to apply the same color to all the elements?
Thank you.

Body:
The way you have implemented calculates the range for each iteration. First, you need to get the random color, then you assign to all H2.

jQuery(document).ready(function() {
    var colors = ["#FFB24A", "#ED145B", "#55D3D2", "#E8390F", "#787878"];
    var randomColor = colors[Math.floor(Math.random() * colors.length)];
    jQuery(".change_color h2").each(function() {
        jQuery(this).css("color", randomColor);
    });
});


问:
Can't print String from function (in react tictactoe tutorial)
I'm trying to implement the first improvement after completing the tictactoe react tutorial: Display the location for each move in the format (col, row) in the move history list.

But my (col,row)'s, despite being correctly calculated, aren't being printed in the buttons. My buttons get texts like Go to move #1 (undefined). The (col,row) value should be printed instead of that undefined.

Why is it happening?

Here's my code:

```<code> render() {
  const history = this.state.history;
  const current = history[this.state.stepNumber];
  const winner = calculateWinner(current.squares);

  const moves = history.map((step,move) => {
    const desc = move ? 'Go to move # ' + move + ' ('+getRowCol(history, move)+ ')': 'Go to game start';
    return (
      <li key={move}><button onClick={() => this.jumpTo(move)}>{desc}</button></li>
    )
  });

 (...)

 function getRowCol(history, move){
  let array1 = history[move].squares;
  let array2 = history[move-1].squares;
  array1.forEach((item,index) => {
   if(item !== array2[index]){
    return nomearIndice(index);
   }
  });
 }
 function nomearIndice(indice){
  let retorno = indice < 3 ? '1,' : indice < 6 ? '2,' : '3,';
  if([0,3,6].includes(indice)){
   return retorno + '1';
  } if([1,4,7].includes(indice)){
   return retorno + '2';
  } if([2,5,8].includes(indice)){
   return retorno + '3';
  }
 }
</code>```

So I run history.map in line 6 of the code sample, this method calls getRowCol function and, as far as I can tell by putting a million console.logs in the code, it works fine. I guess JS isn't waiting until my getRowCol function returns and is producing this undesired result. Is it the problem? If so, how can I fix it?

Thanks in advance

答:
It doesn't look like you are returning anything from getRowCol
Try

```<code>function getRowCol(history, move) {
  let array1 = history[move].squares;
  let array2 = history[move - 1].squares;
  return array1.map((item, index) => {
    if (item !== array2[index]) {
      return nomearIndice(index);
    }
  });
}
</code>```

Here is a demo using map and returning the result. However, I'm not sure what output you are expecting.

Can you explain what result you want from getRowCol (eg an example) and I can try to help.

I've updated the demo to reflect the behaviour you are after using

function getRowCol(history, move) {
  let array1 = history[move].squares;
  let array2 = history[move - 1].squares;

  return array1.reduce((accumulator, item, index) => {
    return (item === array2[index]) ? accumulator : nomearIndice(index);
  }, '');
}
```

Body:
I'm trying to implement the first improvement after completing the tictactoe react tutorial: Display the location for each move in the format (col, row) in the move history list.

But my (col,row)'s, despite being correctly calculated, aren't being printed in the buttons. My buttons get texts like Go to move #1 (undefined). The (col,row) value should be printed instead of that undefined.

Why is it happening?

Here's my code:

 render() {
  const history = this.state.history;
  const current = history[this.state.stepNumber];
  const winner = calculateWinner(current.squares);

  const moves = history.map((step,move) => {
    const desc = move ? 'Go to move # ' + move + ' ('+getRowCol(history, move)+ ')': 'Go to game start';
    return (

<button onClick={() => this.jumpTo(move)}>{desc}</button>

    )
  });

 (...)

 function getRowCol(history, move){
  let array1 = history[move].squares;
  let array2 = history[move-1].squares;
  array1.forEach((item,index) => {
   if(item !== array2[index]){
    return nomearIndice(index);
   }
  });
 }
 function nomearIndice(indice){
  let retorno = indice < 3 ? '1,' : indice < 6 ? '2,' : '3,';
  if([0,3,6].includes(indice)){
   return retorno + '1';
  } if([1,4,7].includes(indice)){
   return retorno + '2';
  } if([2,5,8].includes(indice)){
   return retorno + '3';
  }
 }

So I run history.map in line 6 of the code sample, this method calls getRowCol function and, as far as I can tell by putting a million console.logs in the code, it works fine. I guess JS isn't waiting until my getRowCol function returns and is producing this undesired result. Is it the problem? If so, how can I fix it?

Thanks in advance

Body:
It doesn't look like you are returning anything from getRowCol
Try

function getRowCol(history, move) {
  let array1 = history[move].squares;
  let array2 = history[move - 1].squares;
  return array1.map((item, index) => {
    if (item !== array2[index]) {
      return nomearIndice(index);
    }
  });
}

Here is a demo using map and returning the result. However, I'm not sure what output you are expecting.

Can you explain what result you want from getRowCol (eg an example) and I can try to help.

I've updated the demo to reflect the behaviour you are after using

function getRowCol(history, move) {
  let array1 = history[move].squares;
  let array2 = history[move - 1].squares;

  return array1.reduce((accumulator, item, index) => {
    return (item === array2[index]) ? accumulator : nomearIndice(index);
  }, '');
}


问:
Laravel having column name in where clause static method
Recently I just realized that Laravel generates a static method with column name when joined in a where clause using camel case

example

```<code>$user = User::whereName('john')->first(); // added `name` as a column name
</code>```

When called this code to SQL it generates

```<code>$user = User::whereName('john')->toSql();

//it returns
select * from `users` where `name` = ?
</code>```

This indeed gives expected result as it returns a user with name john.

I have searched Laravel documentation but can't find this function or where it was defined.

All I need is clarification if this method is good or best so that I can continue using it and as well know how the method is generated inside Laravel framework or any other means

答:
This approach is completely legit, thou not well documented. In Query\Builder it utilize the __call function overwrite to produce the functionality and you can see the exact function here.

The subject of magic methods and the __call function, is often highly debatable if they are for the better. If you utilize IDE helper. It will actually type hint the methods for you and therefor alleviate some of the magical approaches it takes and provide you with a smooth IDE experience.

An example of the generated type hints from a local project i have.

```<code>* @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User whereId($value)
* @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User whereEmail($value)
</code>```

Therefor i would not be worried that this is not the best approach. There are many ways of doing what you are doing, but this one is one of the correct ones.

Body:
Recently I just realized that Laravel generates a static method with column name when joined in a where clause using camel case

example

$user = User::whereName('john')->first(); // added `name` as a column name

When called this code to SQL it generates

$user = User::whereName('john')->toSql();

//it returns
select * from `users` where `name` = ?

This indeed gives expected result as it returns a user with name john.

I have searched Laravel documentation but can't find this function or where it was defined.

All I need is clarification if this method is good or best so that I can continue using it and as well know how the method is generated inside Laravel framework or any other means

Body:
This approach is completely legit, thou not well documented. In Query\Builder it utilize the __call function overwrite to produce the functionality and you can see the exact function here.

The subject of magic methods and the __call function, is often highly debatable if they are for the better. If you utilize IDE helper. It will actually type hint the methods for you and therefor alleviate some of the magical approaches it takes and provide you with a smooth IDE experience.

An example of the generated type hints from a local project i have.

* @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User whereId($value)
* @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User whereEmail($value)

Therefor i would not be worried that this is not the best approach. There are many ways of doing what you are doing, but this one is one of the correct ones.


问:
Efficiently erase a unique_ptr from an unordered_set
I am storing the ownership of some objects inside an unordered_set, using unique_ptrs.
But I don't know a good way to erase one of them from the set, when the time comes.

Code looks something like this:

```<code>typedef unique_ptr<MyType> MyPtr;

unordered_set<MyPtr> owner;

MyPtr p = make_unique<MyType>("foo")
MyType *pRaw = p.get();
owner.insert(std::move(p));

// Later ...

// I want to do something like this (cannot be written as-is, of course):
// owner.erase(pRaw);
</code>```

Is there a way to do this?
I can, of course, iterate the entire set with begin() and end(), but the whole point of putting them in the set is to make these lookups efficient.

Some things I have thought of already:

Use shared_ptr. This is the wrong abstraction for my case. Ownership is unique.

Use raw pointers, and forget about unique_ptr. This abandons all the advantages that unique_ptr provides.

Find the bucket with unordered_set::begin(key). As far as I know, there is no way for me to create a key that will match the unique_ptr I want to delete. But I'm happy to be proven wrong (:

(In truth, I solved this using eastl::unordered_set, with its find_as function for custom keys)

答:
In C++20, std::unordered_set::find can use equivalent key with transparent hash and KeyEqual, then you might do something similar to:

```<code>struct MyHash
{
    using is_transparent = void;

    auto operator()(MyType* p) const { return std::hash<MyType*>{}(p); }
    auto operator()(const MyPtr& p) const { return std::hash<MyType*>{}(p.get()); }
};

struct MyEqual
{
    using is_transparent = void;

    template <typename LHS, typename RHS>
    auto operator()(const LHS& lhs, const RHS& rhs) const
    {
        return AsPtr(lhs) == AsPtr(rhs);
    }
private:
    static const MyType* AsPtr(const MyType* p) { return p; }
    static const MyType* AsPtr(const MyPtr& p) { return p.get(); }

};

int main()
{
    std::unordered_set<MyPtr, MyHash, MyEqual> owner;

    MyPtr p = std::make_unique<MyType>();
    MyType *pRaw = p.get();
    owner.insert(std::move(p));

    auto it = owner.find(pRaw);
    if (it != owner.end()) {
        owner.erase(it);
    }
}
</code>```

Body:
I am storing the ownership of some objects inside an unordered_set, using unique_ptrs.
But I don't know a good way to erase one of them from the set, when the time comes.

Code looks something like this:

typedef unique_ptr<MyType> MyPtr;

unordered_set<MyPtr> owner;

MyPtr p = make_unique<MyType>("foo")
MyType *pRaw = p.get();
owner.insert(std::move(p));

// Later ...

// I want to do something like this (cannot be written as-is, of course):
// owner.erase(pRaw);

Is there a way to do this?
I can, of course, iterate the entire set with begin() and end(), but the whole point of putting them in the set is to make these lookups efficient.

Some things I have thought of already:

Use shared_ptr. This is the wrong abstraction for my case. Ownership is unique.

Use raw pointers, and forget about unique_ptr. This abandons all the advantages that unique_ptr provides.

Find the bucket with unordered_set::begin(key). As far as I know, there is no way for me to create a key that will match the unique_ptr I want to delete. But I'm happy to be proven wrong (:

(In truth, I solved this using eastl::unordered_set, with its find_as function for custom keys)

Body:
In C++20, std::unordered_set::find can use equivalent key with transparent hash and KeyEqual, then you might do something similar to:

struct MyHash
{
    using is_transparent = void;

    auto operator()(MyType* p) const { return std::hash<MyType*>{}(p); }
    auto operator()(const MyPtr& p) const { return std::hash<MyType*>{}(p.get()); }
};

struct MyEqual
{
    using is_transparent = void;

    template <typename LHS, typename RHS>
    auto operator()(const LHS& lhs, const RHS& rhs) const
    {
        return AsPtr(lhs) == AsPtr(rhs);
    }
private:
    static const MyType* AsPtr(const MyType* p) { return p; }
    static const MyType* AsPtr(const MyPtr& p) { return p.get(); }

};

int main()
{
    std::unordered_set<MyPtr, MyHash, MyEqual> owner;

    MyPtr p = std::make_unique<MyType>();
    MyType *pRaw = p.get();
    owner.insert(std::move(p));

    auto it = owner.find(pRaw);
    if (it != owner.end()) {
        owner.erase(it);
    }
}


问:
How to generate primefaces PickList component programmatically?
```<code>public void populateForm(ComponentSystemEvent event) {
    HtmlForm form = (HtmlForm) event.getComponent();

    List<String> citiesSource = new ArrayList<String>();
    List<String> citiesTarget = new ArrayList<String>();
    citiesSource.add("San Francisco");
    citiesSource.add("London");
    citiesSource.add("Paris");
    citiesSource.add("Istanbul");
    citiesSource.add("Berlin");
    citiesSource.add("Barcelona");
    citiesSource.add("Rome");

    cities = new DualListModel<String>(citiesSource, citiesTarget);

    PickList pickList = new PickList();
    pickList.setId("pickList");
    pickList.setValue(cities);
    pickList.setVar("cities");
    pickList.setItemLabel(pickList.getVar());
    pickList.setItemValue(cities);

     form.getChildren().add(pickList);
}
</code>```

This was my approach, and output I got is:

But if I add
 in my xhtml, I get this output:

What is going on here?

答:
This is how I solved the PickList issue:

```<code>FacesContext context = FacesContext.getCurrentInstance();
ExpressionFactory ef = context.getApplication().getExpressionFactory();

PickList pickList = new PickList();

ValueExpression pickListValue = ef.createValueExpression(
    context.getELContext(), "#{ruleManagedBean.cities}",DualListModel.class);

ValueExpression pickListVar = ef.createValueExpression(
            context.getELContext(), "cities", String.class);

ValueExpression pickListItemLabel = ef.createValueExpression(
            context.getELContext(), "#{cities}", String.class);

ValueExpression pickListItemValue = ef.createValueExpression(
            context.getELContext(), "#{cities}", String.class);

pickList.setId("pickList");
pickList.setValueExpression("value", pickListValue);
pickList.setValueExpression("var", pickListVar);
pickList.setValueExpression("itemLabel", pickListItemLabel);
pickList.setValueExpression("itemValue", pickListItemValue);

form.getChildren().add(pickList);
</code>```

Note: ruleManagedBean.cities refers to the DualListModel, populated as

```<code>List<String> citiesSource = new ArrayList<String>();
List<String> citiesTarget = new ArrayList<String>();
citiesSource.add("San Francisco");
citiesSource.add("London");
citiesSource.add("Paris");
citiesSource.add("Istanbul");
citiesSource.add("Berlin");
citiesSource.add("Barcelona");
citiesSource.add("Rome");

cities.setSource(citiesSource);
cities.setTarget(citiesTarget);
</code>```

Make sure that you have declared this DualListModel globally as below and has getter setter methods

```<code>private DualListModel<String> cities = new DualListModel<String>();
</code>```

Body:
public void populateForm(ComponentSystemEvent event) {
    HtmlForm form = (HtmlForm) event.getComponent();

    List<String> citiesSource = new ArrayList<String>();
    List<String> citiesTarget = new ArrayList<String>();
    citiesSource.add("San Francisco");
    citiesSource.add("London");
    citiesSource.add("Paris");
    citiesSource.add("Istanbul");
    citiesSource.add("Berlin");
    citiesSource.add("Barcelona");
    citiesSource.add("Rome");

    cities = new DualListModel<String>(citiesSource, citiesTarget);

    PickList pickList = new PickList();
    pickList.setId("pickList");
    pickList.setValue(cities);
    pickList.setVar("cities");
    pickList.setItemLabel(pickList.getVar());
    pickList.setItemValue(cities);

     form.getChildren().add(pickList);
}

This was my approach, and output I got is:

But if I add
 in my xhtml, I get this output:

What is going on here?

Body:
This is how I solved the PickList issue:

FacesContext context = FacesContext.getCurrentInstance();
ExpressionFactory ef = context.getApplication().getExpressionFactory();

PickList pickList = new PickList();

ValueExpression pickListValue = ef.createValueExpression(
    context.getELContext(), "#{ruleManagedBean.cities}",DualListModel.class);

ValueExpression pickListVar = ef.createValueExpression(
            context.getELContext(), "cities", String.class);

ValueExpression pickListItemLabel = ef.createValueExpression(
            context.getELContext(), "#{cities}", String.class);

ValueExpression pickListItemValue = ef.createValueExpression(
            context.getELContext(), "#{cities}", String.class);

pickList.setId("pickList");
pickList.setValueExpression("value", pickListValue);
pickList.setValueExpression("var", pickListVar);
pickList.setValueExpression("itemLabel", pickListItemLabel);
pickList.setValueExpression("itemValue", pickListItemValue);

form.getChildren().add(pickList);

Note: ruleManagedBean.cities refers to the DualListModel, populated as

List<String> citiesSource = new ArrayList<String>();
List<String> citiesTarget = new ArrayList<String>();
citiesSource.add("San Francisco");
citiesSource.add("London");
citiesSource.add("Paris");
citiesSource.add("Istanbul");
citiesSource.add("Berlin");
citiesSource.add("Barcelona");
citiesSource.add("Rome");

cities.setSource(citiesSource);
cities.setTarget(citiesTarget);

Make sure that you have declared this DualListModel globally as below and has getter setter methods

private DualListModel<String> cities = new DualListModel<String>();


问:
Track local files locally, but ignore them on remote

Context

I want to keep track of the history of a local script in a project root folder using git, but I do not want to push it on remote.

Therefore, this file is now referenced in my .gitignore file, so it is not tracked locally.

But I would like to track it on my local machine (while always keeping the remote without this file).

Ideas

This seemed to be a solution; Track files in local Git repo but ignore in remote but it needs the creation of a subfolder, which I don't want to create for different reasons, and thus keeping all my script files at the root of my folder.

Question

Is there a simple way to do so?

答:
I think your best choice is making it into a submodule but as you already mentioned that's not an option, my best bet would be doing it using Git hooks (haven't tried tho').

If you can add a pre-receive or post-receive hook then you could do something similar to this but instead of rejecting you could remove the files from the commit and amend it.

Again, not even sure if this is possible as that would create a new commit and hash and pulling from the same branch wouldn't be possible as references would be totally different. You would need to always push like git push origin local_branch:remote_branch for it to even make sense.


问:
Remove padding on category page on mobile
On a website I'm editing - minimauk.com

The website owner wants the description on the category pages to have padding on both the left and right so it aligns more in the middle (see image below). I've done this by adding this code into the category description box:

desktop category description padding

However, when this is viewed on mobile the text appears as one word per line (see image below).

mobile category description padding

Is it possible to remove the padding on mobile for this?

Thank you.

答:
Your padding stays in place as the screen gets more narrow hence the extra space around your element.
Try CSS media queries: </p>

```<code>@media screen and (max-width: 420px){
 .your-selector{
 width:100%;
  padding:0;
  }
}
</code>```

Body:
Your padding stays in place as the screen gets more narrow hence the extra space around your element.
Try CSS media queries:

@media screen and (max-width: 420px){
 .your-selector{
 width:100%;
  padding:0;
  }
}


问:
Should react-native CLI be a local module or global?
I have been flowing along with the initial steps for getting started with React Native over on FB's git page. https://facebook.github.io/react-native/docs/getting-started

During the process, using nxp or npm installed CLI, I get the flowing error.

```<code>[!] Invalid `Podfile` file: [!] /Users/allen/.nvm/versions/node/v12.14.1/bin/node -e console.log(require('@react-native-community/cli').bin);

internal/modules/cjs/loader.js:796
    throw err;
    ^

Error: Cannot find module '@react-native-community/cli'
Require stack:
- /Volumes/BLUE/workspace-blue/react_native-blue/test/ios/[eval]
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:793:17)
    at Function.Module._load (internal/modules/cjs/loader.js:686:27)
    at Module.require (internal/modules/cjs/loader.js:848:19)
    at require (internal/modules/cjs/helpers.js:74:18)
    at [eval]:1:13
    at Script.runInThisContext (vm.js:116:20)
    at Object.runInThisContext (vm.js:306:38)
    at Object.<anonymous> ([eval]-wrapper:9:26)
    at Module._compile (internal/modules/cjs/loader.js:955:30)
    at evalScript (internal/process/execution.js:80:25) {
  code: 'MODULE_NOT_FOUND',
  requireStack: [ '/Volumes/BLUE/workspace-blue/react_native-blue/test/ios/[eval]' ]
}
</code>```

This happens during the cocoapods installation. The docs say:

If you previously installed a global react-native-cli package, please remove it as it may cause unexpected issues.

But this happens no matter what's installed or what is used to create the starting files.

In the Podfile there are these lines:

```<code>platform :ios, '13.0' # <- this was 9.0 but I changed to 13.0
require_relative '../node_modules/@react-native-community/cli-platform-ios/native_modules'
</code>```

If I do an npm install @react-native-commuinty/cli locally within the project and then do the pod install everything works out correctly. Should I change the CLI path to that of my npm directory? If the docs say that it shouldn't have any problems when no react-native CLI is installed then why would I need to install it to make the pod install work?

Environment:

MacOS 10.15

node 12.14.1

ruby ruby 2.6.3p62 (2019-04-16 revision 67580) [universal.x86_64-darwin19] (tried with rbenv 2.5)

xcode-select version 2373.

答:
it needs to be local. As you enter

```<code>npx react-native init [project name]
</code>```

it will add it locally.

https://facebook.github.io/react-native/docs/getting-started

this official link advices:

If you previously installed a global react-native-cli package, please remove it as it may cause unexpected issues.

Body:
I have been flowing along with the initial steps for getting started with React Native over on FB's git page. https://facebook.github.io/react-native/docs/getting-started

During the process, using nxp or npm installed CLI, I get the flowing error.

[!] Invalid `Podfile` file: [!] /Users/allen/.nvm/versions/node/v12.14.1/bin/node -e console.log(require('@react-native-community/cli').bin);

internal/modules/cjs/loader.js:796
    throw err;
    ^

Error: Cannot find module '@react-native-community/cli'
Require stack:
- /Volumes/BLUE/workspace-blue/react_native-blue/test/ios/[eval]
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:793:17)
    at Function.Module._load (internal/modules/cjs/loader.js:686:27)
    at Module.require (internal/modules/cjs/loader.js:848:19)
    at require (internal/modules/cjs/helpers.js:74:18)
    at [eval]:1:13
    at Script.runInThisContext (vm.js:116:20)
    at Object.runInThisContext (vm.js:306:38)
    at Object.<anonymous> ([eval]-wrapper:9:26)
    at Module._compile (internal/modules/cjs/loader.js:955:30)
    at evalScript (internal/process/execution.js:80:25) {
  code: 'MODULE_NOT_FOUND',
  requireStack: [ '/Volumes/BLUE/workspace-blue/react_native-blue/test/ios/[eval]' ]
}

This happens during the cocoapods installation. The docs say:

If you previously installed a global react-native-cli package, please remove it as it may cause unexpected issues.

But this happens no matter what's installed or what is used to create the starting files.

In the Podfile there are these lines:

platform :ios, '13.0' # <- this was 9.0 but I changed to 13.0
require_relative '../node_modules/@react-native-community/cli-platform-ios/native_modules'

If I do an npm install @react-native-commuinty/cli locally within the project and then do the pod install everything works out correctly. Should I change the CLI path to that of my npm directory? If the docs say that it shouldn't have any problems when no react-native CLI is installed then why would I need to install it to make the pod install work?

Environment:

MacOS 10.15

node 12.14.1

ruby ruby 2.6.3p62 (2019-04-16 revision 67580) [universal.x86_64-darwin19] (tried with rbenv 2.5)

xcode-select version 2373.

Body:
it needs to be local. As you enter

npx react-native init [project name]

it will add it locally.

https://facebook.github.io/react-native/docs/getting-started

this official link advices:

If you previously installed a global react-native-cli package, please remove it as it may cause unexpected issues.


问:
Can't connect activities in activity diagram in EA
Hi I'm currently stuck with a problem with Activity diagram in EA. I'm trying to describe a code. When I add Start controll node and activity node I'm not able to connect them by control flow.

The same problem happens when I try to connect two activities together with control flow - I'm getting following error:

The requested connection is not UML compliant

Anybody can give some advice on this?

Thanks

答:
Edit: Please look down the other answers here. I just did not read correctly about what you were doing. This one is meant for the cases where EA did block users the wrong way. In your case it's blocking you for good reasons

Original answer

You can turn off "Strict connector syntax" in the Connector options. You find that in various places in EA's option jungle depending on the version. V14 has a couple of known bugs related to that. Not sure about V15 or any state of fixing that.

In V13.5 you find that option under Layout/Appearance/Theme & ...

(right bottom)


问:
C++ std::set metaprograming set of set of set ... nesting
I was trying to implement a n-tuple from scratch starting with the mathematical base ordered-pair
where n-tuple (a,b,c) = ordered_pair(a,ordered_pair(b,c)) and ordered pair is a set representation
ie. ordered_pair(a,b) = set{{a},{a,b}}

here is the code for ordered_pair

```<code>#include <iostream>
#include <set>
#include <boost/variant.hpp>
using namespace std;
template <typename T, typename U, typename Z>
class orderd_pair{

//typedef boost::variant<int,std::string,double> cell;
private:
set<set<Z>> opair;

set<T> first;
set<U> second;

public:

set<set<Z>> Orderd_pair(T first_element, U second_element){

first.insert(first_element);
second.insert(first_element);
second.insert(second_element);
opair.insert(first);
opair.insert(second);

return opair;

}
//TO DO void print_elements(std::set<std::set<cell>> opair);*/

};
</code>```

the problem is when trying to implement tuple set of each ordered_pair must be nested ie
for three element tuple set{{a},{a,{{b},{b,c}}}} and for more elements it will be nested even more making it hard to work with, how can I solve this??

also I have used boost::variant to support int,std::string and double data types.

答:
You will quickly find that you can't put a std::set<T> into the same container as a std::set if T is different to U. So you are likely to end up with

```<code>struct any_less {
    bool operator()(const std::any & lhs, const std::any & rhs) {
        return type_index(lhs.type()) < type_index(rhs.type());
    }
}

using ordered_pair = std::set<std::set<std::any, any_less>>;
</code>```

Codifying your recurrence relation.

```<code>template <typename A, typename B>
ordered_pair make_ordered_pair(A a, B b) {
    return { { a }, { a, b } };
}

template <typename A, typename B, typename C, typename... Rest>
ordered_pair make_ordered_pair(A a, B b, C c, Rest... rest) {
    return { { a }, { a, make_ordered_pair(b, c, rest...) } };
}
</code>```

But C++ has a much better type for ordered pairs: std::pair. It also has a much better type for tuples: std::tuple.

Body:
I was trying to implement a n-tuple from scratch starting with the mathematical base ordered-pair
where n-tuple (a,b,c) = ordered_pair(a,ordered_pair(b,c)) and ordered pair is a set representation
ie. ordered_pair(a,b) = set{{a},{a,b}}

here is the code for ordered_pair

#include <iostream>
#include <set>
#include <boost/variant.hpp>
using namespace std;
template <typename T, typename U, typename Z>
class orderd_pair{

//typedef boost::variant<int,std::string,double> cell;
private:
set<set<Z>> opair;

set<T> first;
set second;

public:

set<set<Z>> Orderd_pair(T first_element, U second_element){

first.insert(first_element);
second.insert(first_element);
second.insert(second_element);
opair.insert(first);
opair.insert(second);

return opair;

}
//TO DO void print_elements(std::set<std::set<cell>> opair);*/

};

the problem is when trying to implement tuple set of each ordered_pair must be nested ie
for three element tuple set{{a},{a,{{b},{b,c}}}} and for more elements it will be nested even more making it hard to work with, how can I solve this??

also I have used boost::variant to support int,std::string and double data types.

Body:
You will quickly find that you can't put a std::set<T> into the same container as a std::set<U> if T is different to U. So you are likely to end up with

struct any_less {
    bool operator()(const std::any & lhs, const std::any & rhs) {
        return type_index(lhs.type()) < type_index(rhs.type());
    }
}

using ordered_pair = std::set<std::set<std::any, any_less>>;

Codifying your recurrence relation.

template <typename A, typename B>
ordered_pair make_ordered_pair(A a, B b) {
    return { { a }, { a, b } };
}

template <typename A, typename B, typename C, typename... Rest>
ordered_pair make_ordered_pair(A a, B b, C c, Rest... rest) {
    return { { a }, { a, make_ordered_pair(b, c, rest...) } };
}

But C++ has a much better type for ordered pairs: std::pair. It also has a much better type for tuples: std::tuple.


问:
Too Many DOM Elements
I am building a one page webapp and it's starting to get pretty big. There are several components to the app, each one meticulously styled. On average the app has a DOM element count of 1200+. I have been warned by my YSlow scan that this is too many, and that I should have no more than 700 DOM elements.

I am usually quite strict and efficient with my markup and I doubt I would be able to trim much off. I tend to use a lot of DOM elements to get the styling exactly right and working cross browser.

How can I dramatically cut the number of DOM elements?
Will I have to load more of the content on demand (ajax) instead on all on page load?
Does a large amount of DOM elements have a big impact on performance?

I would love to hear people's experience with this and any solutions you may have...

答:
The number of dom elements would only enter into the picture if you're doing a lot of DOM and/or CSS manipulation on the page via Javascript. Scanning for an ID in a page with 50,000 elements is always going to be slower than a page with only 500. Changing a CSS style which is inherited by most of the page will most likely lead to more redrawing/reflowing than it would on a simpler page, etc...

The only way to cut element count is to simplify the page.

Title: Too Many DOM Elements


问:
Equal space after li of unordered list
I've removed dot(.) after the
 of
 and gave '|' after the number.

I've achieved it by using below code:

```<code>ol {
    counter-reset: item;
}
ol li::before {
    content: counter(item) " ";
    counter-increment: item;
    padding-right: 15px;
    border-right: 2.5px solid rgba(37, 194, 240, 0.8);
    margin-right: 15px;
}
</code>```

But the space after the numbers are not equal.

I need uniform spacing after the numbers.
Please help me to resolve this issue.

ol{counter-reset: item;columns: 2;}
ol li{display:block;margin-bottom:10px;}
ol li::before {
 content: counter(item) " ";
 counter-increment: item;
 padding-right: 15px;
 border-right: 2.5px solid rgba(37, 194, 240, 0.8);
 margin-right: 15px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ol>
<li>My abc</li>
<li>LiveColor</li>
<li>LiveFood</li>
<li>Ola</li>
<li>Uber</li>
<li>Good Chat</li>
<li>Food Panda</li>
<li>Domino'd</li>
<li>Clickfood</li>
<li>Smartyo</li>
<li>Tide</li>
<li>Webseries</li>
<li>GoPro</li>
<li>Liveshow</li>
</ol></code>```

In addition to it, the font-family is such a way that all the numbers have different spaces.

答:
Try these css codes..</p>

```<code>ol{counter-reset: item;columns: 2;}
ol li{display:block;margin-bottom:10px;position: relative;padding-left: 40px;}
ol li::before {
    content: counter(item) " ";
    counter-increment: item;
    position: absolute;
    left: 0px;
}
ol li::after {
    content: " ";
    position: absolute;
    background-color: rgba(37, 194, 240, 0.8);
    height: 100%;
    width: 2px;
    top: 0px;
    left: 25px;
}
</code>```

Title: Equal space after li of unordered list

Body:
I've removed dot(.) after the
 of
 and gave '|' after the number.

I've achieved it by using below code:

ol {
    counter-reset: item;
}
ol li::before {
    content: counter(item) " ";
    counter-increment: item;
    padding-right: 15px;
    border-right: 2.5px solid rgba(37, 194, 240, 0.8);
    margin-right: 15px;
}

But the space after the numbers are not equal.

I need uniform spacing after the numbers.
Please help me to resolve this issue.

ol{counter-reset: item;columns: 2;}
ol li{display:block;margin-bottom:10px;}
ol li::before {
 content: counter(item) " ";
 counter-increment: item;
 padding-right: 15px;
 border-right: 2.5px solid rgba(37, 194, 240, 0.8);
 margin-right: 15px;
}

My abc

LiveColor

LiveFood

Ola

Uber

Good Chat

Food Panda

Domino'd

Clickfood

Smartyo

Tide

Webseries

GoPro

Liveshow

In addition to it, the font-family is such a way that all the numbers have different spaces.

Body:
Try these css codes..

ol{counter-reset: item;columns: 2;}
ol li{display:block;margin-bottom:10px;position: relative;padding-left: 40px;}
ol li::before {
    content: counter(item) " ";
    counter-increment: item;
    position: absolute;
    left: 0px;
}
ol li::after {
    content: " ";
    position: absolute;
    background-color: rgba(37, 194, 240, 0.8);
    height: 100%;
    width: 2px;
    top: 0px;
    left: 25px;
}


问:
Getting NullPointerException in getDrawable method on Glide
I have an imageview and I'll like to get the Bitmap of it...

Here is my code:

Setting the imageview:

```<code>ImageView imageView;
imageView =  findViewById(R.id.image_wallpaper);
Glide.with(this).load(current_image.getImageURL()).into(imageView);
</code>```

Getting the bitmap:

```<code>setButton.setOnClickListener(new View.OnClickListener() {
    public void onClick(View arg0) {
        DisplayMetrics metrics = new DisplayMetrics();

        imageView.invalidate();  // I get the crash with or without that line
        Bitmap mBitmap = ((BitmapDrawable) imageView.getDrawable()).getBitmap();  // CRASH HERE

        // more things using the mBitmap

    }
});
</code>```

The crash log:

```<code>Fatal Exception: java.lang.NullPointerException
Attempt to invoke virtual method 'android.graphics.Bitmap android.graphics.drawable.BitmapDrawable.getBitmap()' on a null object reference
com.XXXX.XXXXXXX.ImageActivity$4.onClick (ImageActivity.java:170)
android.view.View.performClick (View.java:5246)
android.view.View$PerformClick.run (View.java:21200)
android.os.Handler.handleCallback (Handler.java:739)
android.os.Handler.dispatchMessage (Handler.java:95)
android.os.Looper.loop (Looper.java:145)
android.app.ActivityThread.main (ActivityThread.java:6946)
java.lang.reflect.Method.invoke (Method.java)
java.lang.reflect.Method.invoke (Method.java:372)
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run (ZygoteInit.java:1404)
com.android.internal.os.ZygoteInit.main (ZygoteInit.java:1199)
</code>```

I'm using last version of Glide:

```<code>implementation 'com.github.bumptech.glide:glide:4.9.0'                   // glide
</code>```

This crash log comes from Firebase Crashlytics, a lot of users get that error, but I'm unable to reproduce it on my devices.

What's the problem? How can I fix it?

Thanks

答:
There is a method in the Glide Library in which you can get bitmap, you can use that method to get bitmap and set into Imageview.

You can also use resource drawable in place of the "imagepath".

```<code>Glide.with(context)
        .asBitmap()
        .placeholder(placeholder)
        .error(placeholder)
        .load(
            "imagepath"
        )
        .into(object : CustomTarget<Bitmap>() {
            override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
                // here you will get Bitmap file and you can use it to set on image view.
                image.setImageBitmap(resource)
            }

            override fun onLoadCleared(placeholder: Drawable?) {
                // this is called when imageView is cleared on lifecycle call or for some other reason.
                // if you are referencing the bitmap somewhere else too other than this imageView clear it here as you can no longer have the bitmap.
            }
        })
</code>```

Body:
I have an imageview and I'll like to get the Bitmap of it...

Here is my code:

Setting the imageview:

ImageView imageView;
imageView =  findViewById(R.id.image_wallpaper);
Glide.with(this).load(current_image.getImageURL()).into(imageView);

Getting the bitmap:

setButton.setOnClickListener(new View.OnClickListener() {
    public void onClick(View arg0) {
        DisplayMetrics metrics = new DisplayMetrics();

        imageView.invalidate();  // I get the crash with or without that line
        Bitmap mBitmap = ((BitmapDrawable) imageView.getDrawable()).getBitmap();  // CRASH HERE

        // more things using the mBitmap

    }
});

The crash log:

Fatal Exception: java.lang.NullPointerException
Attempt to invoke virtual method 'android.graphics.Bitmap android.graphics.drawable.BitmapDrawable.getBitmap()' on a null object reference
com.XXXX.XXXXXXX.ImageActivity$4.onClick (ImageActivity.java:170)
android.view.View.performClick (View.java:5246)
android.view.View$PerformClick.run (View.java:21200)
android.os.Handler.handleCallback (Handler.java:739)
android.os.Handler.dispatchMessage (Handler.java:95)
android.os.Looper.loop (Looper.java:145)
android.app.ActivityThread.main (ActivityThread.java:6946)
java.lang.reflect.Method.invoke (Method.java)
java.lang.reflect.Method.invoke (Method.java:372)
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run (ZygoteInit.java:1404)
com.android.internal.os.ZygoteInit.main (ZygoteInit.java:1199)

I'm using last version of Glide:

implementation 'com.github.bumptech.glide:glide:4.9.0'                   // glide

This crash log comes from Firebase Crashlytics, a lot of users get that error, but I'm unable to reproduce it on my devices.

What's the problem? How can I fix it?

Thanks

Body:
There is a method in the Glide Library in which you can get bitmap, you can use that method to get bitmap and set into Imageview.

You can also use resource drawable in place of the "imagepath".

Glide.with(context)
        .asBitmap()
        .placeholder(placeholder)
        .error(placeholder)
        .load(
            "imagepath"
        )
        .into(object : CustomTarget<Bitmap>() {
            override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
                // here you will get Bitmap file and you can use it to set on image view.
                image.setImageBitmap(resource)
            }

            override fun onLoadCleared(placeholder: Drawable?) {
                // this is called when imageView is cleared on lifecycle call or for some other reason.
                // if you are referencing the bitmap somewhere else too other than this imageView clear it here as you can no longer have the bitmap.
            }
        })