问:
Smsgateway.me with visual foxpro, is PHP
I'm trying to use the SMS gateway from smsgateway.me in a software that works in VFP.

Anyone can help me to implement the PHP code in VFP?

The code is in: https://smsgateway.me/sms-api-documentation/messag...

PHP Code:

```<code>require 'vendor/autoload.php';

use SMSGatewayMe\Client\ApiClient;
use SMSGatewayMe\Client\Configuration;
use SMSGatewayMe\Client\Api\MessageApi;
use SMSGatewayMe\Client\Model\SendMessageRequest;

// Configure client
$config = Configuration::getDefaultConfiguration();
$config->setApiKey('Authorization', 'your-token-here');
$apiClient = new ApiClient($config);
$messageClient = new MessageApi($apiClient);

// Sending a SMS Message
$sendMessageRequest1 = new SendMessageRequest([
'phoneNumber' => '07791064781',
'message' => 'test1',
'deviceId' => 1
]);
$sendMessageRequest2 = new SendMessageRequest([
'phoneNumber' => '07791064781',
'message' => 'test2',
'deviceId' => 2
]);
$sendMessages = $messageClient->sendMessages([
$sendMessageRequest1,
$sendMessageRequest2
]);
print_r($sendMessages);
</code>```

答:
Thanks for help.
I find another way, and use a Android APK to create a SMS gateway direct in the phone.
I gona post another asking for help</p>

Body:
I'm trying to use the SMS gateway from smsgateway.me in a software that works in VFP.

Anyone can help me to implement the PHP code in VFP?

The code is in: https://smsgateway.me/sms-api-documentation/messag...

PHP Code:

require 'vendor/autoload.php';

use SMSGatewayMe\Client\ApiClient;
use SMSGatewayMe\Client\Configuration;
use SMSGatewayMe\Client\Api\MessageApi;
use SMSGatewayMe\Client\Model\SendMessageRequest;

// Configure client
$config = Configuration::getDefaultConfiguration();
$config->setApiKey('Authorization', 'your-token-here');
$apiClient = new ApiClient($config);
$messageClient = new MessageApi($apiClient);

// Sending a SMS Message
$sendMessageRequest1 = new SendMessageRequest([
'phoneNumber' => '07791064781',
'message' => 'test1',
'deviceId' => 1
]);
$sendMessageRequest2 = new SendMessageRequest([
'phoneNumber' => '07791064781',
'message' => 'test2',
'deviceId' => 2
]);
$sendMessages = $messageClient->sendMessages([
$sendMessageRequest1,
$sendMessageRequest2
]);
print_r($sendMessages);


来源: stackexchange

问:
How to put in array the children of the children
```<code>private static JSONArray getListOfChildPagesAsJSON(Page page) {
    JSONArray pagesArray = new JSONArray();
    try {
        Iterator<Page> childPages = page.listChildren();
        while (childPages.hasNext()) {
            Page childPage = childPages.next();
            JSONObject pageObject = new JSONObject();
            pageObject.put(childPage.getTitle(), childPage.getPath());
            pagesArray.put(pageObject);
        }
    } catch (JSONException e) {
        LOG.error(e.getMessage(), e);
    }
    return pagesArray;
}
</code>```

So that not only the children of the transferred page put into array, but also the children of the children.

答:
This is a classical case for recursion, like reading directoy tree on filesystem. My suggestion is as follows:

First step: Change the scope of variable JSONArray pagesArray = new JSONArray(); from function to class scope.

```<code>public MyClass {
  private JSONArray pagesArray = new JSONArray();
  ...
}
</code>```

Step two: Change return value to void and the modifier of your function by removing static.

```<code>private void getListOfChildPagesAsJSON(Page page) { }
</code>```

Step three add the missing recusion to your its body.

```<code>//JSONArray pagesArray = new JSONArray();
try {
    Iterator<Page> childPages = page.listChildren();
    while (childPages.hasNext()) {
        Page childPage = childPages.next();
        JSONObject pageObject = new JSONObject();
        pageObject.put(childPage.getTitle(), childPage.getPath());

        //Add the created object to your array which is class variable
        this.pagesArray.put(pageObject);

        //--Check for each single page for child pages again
        Iterator<Page> childPagesOfChildpage = childPage.listChildren();
        while (childPagesOfChildpage.hasNext()) {
            getListOfChildPagesAsJSON(childPagesOfChildpage.next());
        }
        //--
    }
} catch (JSONException e) {
    LOG.error(e.getMessage(), e);
}
</code>```

Note: The check childPage.hasChild() does not work here, because the node jcr:content is a valid child of passed page.

ContentLicense: CC BY-SA 4.0

Body:
private static JSONArray getListOfChildPagesAsJSON(Page page) {
    JSONArray pagesArray = new JSONArray();
    try {
        Iterator<Page> childPages = page.listChildren();
        while (childPages.hasNext()) {
            Page childPage = childPages.next();
            JSONObject pageObject = new JSONObject();
            pageObject.put(childPage.getTitle(), childPage.getPath());
            pagesArray.put(pageObject);
        }
    } catch (JSONException e) {
        LOG.error(e.getMessage(), e);
    }
    return pagesArray;
}

So that not only the children of the transferred page put into array, but also the children of the children.

Body:
This is a classical case for recursion, like reading directoy tree on filesystem. My suggestion is as follows:

First step: Change the scope of variable JSONArray pagesArray = new JSONArray(); from function to class scope.

public MyClass {
  private JSONArray pagesArray = new JSONArray();
  ...
}

Step two: Change return value to void and the modifier of your function by removing static.

private void getListOfChildPagesAsJSON(Page page) { }

Step three add the missing recusion to your its body.

//JSONArray pagesArray = new JSONArray();
try {
    Iterator<Page> childPages = page.listChildren();
    while (childPages.hasNext()) {
        Page childPage = childPages.next();
        JSONObject pageObject = new JSONObject();
        pageObject.put(childPage.getTitle(), childPage.getPath());

        //Add the created object to your array which is class variable
        this.pagesArray.put(pageObject);

        //--Check for each single page for child pages again
        Iterator<Page> childPagesOfChildpage = childPage.listChildren();
        while (childPagesOfChildpage.hasNext()) {
            getListOfChildPagesAsJSON(childPagesOfChildpage.next());
        }
        //--
    }
} catch (JSONException e) {
    LOG.error(e.getMessage(), e);
}

Note: The check childPage.hasChild() does not work here, because the node jcr:content is a valid child of passed page.


问:
Incompatible shape in R-keras
I'm trying to do audio classification using R-Keras but I have a problem with an incompatible shape error of my network.
I've created these 2 functions in order to read all the wave files and transform them in a matrix using mel features

```<code>  audio = readWave(paste(outDir, '/', labels$filename[i], sep = ('') ))
  audio = normalize(audio)
  audio = crop(audio) #in order to have all signals of same size
  return(melfcc(audio, sr = audio@samp.rate))
}

load_data = function(){
  features = lapply(1:nrow(labels), function(i) mfcc_extractor(i))
  data_array = array(data = unlist(features), dim = c(206, 12, 1440) )
  set.seed(0)
  train_idx = sample(1:nrow(labels), size = round(nrow(labels)*.8), replace = F)
  test_idx = c(1:nrow(labels))[-train_idx]

  X_train = data_array[1:206, 1:12, train_idx]
  X_test = data_array[1:206, 1:12, test_idx]
  y_train = labels[train_idx, ]
  y_test = labels[test_idx]
  return(list(X_train = X_train, X_test = X_test, y_train = y_train, y_test = y_test))
}
</code>```

Then I reshape train and test arrays in order to feed them into neural network

```<code>
library(keras)

train_images = array_reshape(X.train_X.test$X_train, c(1152, 12, 206, 1))
test_images = array_reshape(X.train_X.test$X_test, c(288, 12, 206, 1))

train_labels = to_categorical(X.train_X.test$y_train$Actor.id)
test_labels = to_categorical(X.train_X.test$y_test$Actor.id)
</code>```

And after building the network, when I fit it, R give me back this message:

```<code>  layer_conv_2d(filters = 32, kernel_size = c(5, 5), activation = "relu",
                input_shape = c(206, 12, 1)) %>%
  layer_max_pooling_2d(pool_size = c(2, 2))

model <- model %>%
  keras_model_sequential()
  layer_flatten() %>%
  layer_dense(units = 64, activation = "relu") %>%
  layer_dense(units = 8, activation = "softmax")

model

model %>% compile(
  optimizer = "rmsprop",
  loss = "categorical_crossentropy",
  metrics = c("accuracy")
)

model %>% fit(
  train_images, train_labels
)```

WARNING:tensorflow:Model was constructed with shape (None, 206, 12, 1) for input Tensor("sequential_4_input:0", shape=(None, 206, 12, 1), dtype=float32), but it was called on an input with incompatible shape (32, 12, 206, 1).
WARNING:tensorflow:Model was constructed with shape (None, 206, 12, 1) for input Tensor("conv2d_1_input:0", shape=(None, 206, 12, 1), dtype=float32), but it was called on an input with incompatible shape (32, 12, 206, 1).
Error in py_call_impl(callable, dots$args, dots$keywords) :
  ValueError: in user code:

    /usr/local/lib/python3.8/dist-packages/tensorflow/python/keras/engine/training.py:571 train_function  *
        outputs = self.distribute_strategy.run(
    /usr/local/lib/python3.8/dist-packages/tensorflow/python/distribute/distribute_lib.py:951 run  **
        return self._extended.call_for_each_replica(fn, args=args, kwargs=kwargs)
    /usr/local/lib/python3.8/dist-packages/tensorflow/python/distribute/distribute_lib.py:2290 call_for_each_replica
        return self._call_for_each_replica(fn, args, kwargs)
    /usr/local/lib/python3.8/dist-packages/tensorflow/python/distribute/distribute_lib.py:2649 _call_for_each_replica
        return fn(*args, **kwargs)
    /usr/local/lib/python3.8/dist-packages/tensorflow/python/keras/engine/training.py:532 train_step  **
        loss = self.compiled_loss(
    /usr/local/lib/python3.8/dist-packages/tensorflow/python/keras/engine/compile_utils.py:205 __call__
        loss_value = loss_obj(y_t, y_p, sample_we
```

答:
The error is telling you that there is a shape incompatibility issue between the shape indicated as input to the model and the actual shape of the data. For example, your training data has shape (None, 12, 206, 1), while the shape being indicated as input in the model is (None, 206, 12, 1). Thus, you need to: 1) either change the input_shape of the model to (None, 12, 206, 1) by doing

```<code>layer_conv_2d(filters = 32, kernel_size = c(5, 5), activation = "relu",
                input_shape = c(12, 206, 1))
</code>```

or 2) reshape your training and test data into (None, 206, 12, 1) using

```<code>train_images = array_reshape(X.train_X.test$X_train, c(1152, 206, 12, 1))
test_images = array_reshape(X.train_X.test$X_test, c(288, 206, 12, 1)
</code>```

Title: Incompatible shape in R-keras

Body:
I'm trying to do audio classification using R-Keras but I have a problem with an incompatible shape error of my network.
I've created these 2 functions in order to read all the wave files and transform them in a matrix using mel features

  audio = readWave(paste(outDir, '/', labels$filename[i], sep = ('') ))
  audio = normalize(audio)
  audio = crop(audio) #in order to have all signals of same size
  return(melfcc(audio, sr = audio@samp.rate))
}

load_data = function(){
  features = lapply(1:nrow(labels), function(i) mfcc_extractor(i))
  data_array = array(data = unlist(features), dim = c(206, 12, 1440) )
  set.seed(0)
  train_idx = sample(1:nrow(labels), size = round(nrow(labels)*.8), replace = F)
  test_idx = c(1:nrow(labels))[-train_idx]

  X_train = data_array[1:206, 1:12, train_idx]
  X_test = data_array[1:206, 1:12, test_idx]
  y_train = labels[train_idx, ]
  y_test = labels[test_idx]
  return(list(X_train = X_train, X_test = X_test, y_train = y_train, y_test = y_test))
}

Then I reshape train and test arrays in order to feed them into neural network

library(keras)

train_images = array_reshape(X.train_X.test$X_train, c(1152, 12, 206, 1))
test_images = array_reshape(X.train_X.test$X_test, c(288, 12, 206, 1))

train_labels = to_categorical(X.train_X.test$y_train$Actor.id)
test_labels = to_categorical(X.train_X.test$y_test$Actor.id)

And after building the network, when I fit it, R give me back this message:

  layer_conv_2d(filters = 32, kernel_size = c(5, 5), activation = "relu",
                input_shape = c(206, 12, 1)) %>%
  layer_max_pooling_2d(pool_size = c(2, 2))

model <- model %>%
  keras_model_sequential()
  layer_flatten() %>%
  layer_dense(units = 64, activation = "relu") %>%
  layer_dense(units = 8, activation = "softmax")

model

model %>% compile(
  optimizer = "rmsprop",
  loss = "categorical_crossentropy",
  metrics = c("accuracy")
)

model %>% fit(
  train_images, train_labels
)```

WARNING:tensorflow:Model was constructed with shape (None, 206, 12, 1) for input Tensor("sequential_4_input:0", shape=(None, 206, 12, 1), dtype=float32), but it was called on an input with incompatible shape (32, 12, 206, 1).
WARNING:tensorflow:Model was constructed with shape (None, 206, 12, 1) for input Tensor("conv2d_1_input:0", shape=(None, 206, 12, 1), dtype=float32), but it was called on an input with incompatible shape (32, 12, 206, 1).
Error in py_call_impl(callable, dots$args, dots$keywords) :
  ValueError: in user code:

    /usr/local/lib/python3.8/dist-packages/tensorflow/python/keras/engine/training.py:571 train_function  *
        outputs = self.distribute_strategy.run(
    /usr/local/lib/python3.8/dist-packages/tensorflow/python/distribute/distribute_lib.py:951 run  **
        return self._extended.call_for_each_replica(fn, args=args, kwargs=kwargs)
    /usr/local/lib/python3.8/dist-packages/tensorflow/python/distribute/distribute_lib.py:2290 call_for_each_replica
        return self._call_for_each_replica(fn, args, kwargs)
    /usr/local/lib/python3.8/dist-packages/tensorflow/python/distribute/distribute_lib.py:2649 _call_for_each_replica
        return fn(*args, **kwargs)
    /usr/local/lib/python3.8/dist-packages/tensorflow/python/keras/engine/training.py:532 train_step  **
        loss = self.compiled_loss(
    /usr/local/lib/python3.8/dist-packages/tensorflow/python/keras/engine/compile_utils.py:205 __call__
        loss_value = loss_obj(y_t, y_p, sample_we

Body:
The error is telling you that there is a shape incompatibility issue between the shape indicated as input to the model and the actual shape of the data. For example, your training data has shape (None, 12, 206, 1), while the shape being indicated as input in the model is (None, 206, 12, 1). Thus, you need to: 1) either change the input_shape of the model to (None, 12, 206, 1) by doing

layer_conv_2d(filters = 32, kernel_size = c(5, 5), activation = "relu",
                input_shape = c(12, 206, 1))

or 2) reshape your training and test data into (None, 206, 12, 1) using

train_images = array_reshape(X.train_X.test$X_train, c(1152, 206, 12, 1))
test_images = array_reshape(X.train_X.test$X_test, c(288, 206, 12, 1)


问:
IE6 and IE7 float issue on navigation list items
Like many people, I am having trouble with floating elements in IE7 (and 6, but I don't care about that!)

http://www.storybox.co.nz/wordpress/

Looks fine in every other browser, but in IE7 the navigation links sit under each other:

HTML (inline styles are from js dropdown script):

```<code><div id="primary-menu">
  <div class="menu">
    <ul>
      <li><a href="#" class="sf-with-ul">Work.</a>
        <ul class="sub-menu" style="float: none; width: 1em; visibility: hidden; display: none;">
          <li style="white-space: normal; float: left; width: 100%;"><a href="#" style="float: none; width: auto;">Spatial /</a></li>
          <li style="white-space: normal; float: left; width: 100%;"><a href="#" style="float: none; width: auto;">Web /</a></li>
          <li style="white-space: normal; float: left; width: 100%;"><a href="#" style="float: none; width: auto;">Graphic</a></li>
        </ul>
      </li>
      <li><a href="#">Lab.</a></li>
      <li><a href="#">About.</a></li>
    </ul>
  </div>
</div>
</code>```

CSS:

```<code>#primary-menu {
    margin:-30px auto 30px;
}
#primary-menu ul {
    float:right;
}
#primary-menu li {
        float: left;
        list-style: none;
        margin-left: 10px;
            display:inline;
}
#primary-menu ul li a {
        float: right;
}
</code>```

I have tried display:inline on the li items as well as on the a items, but that doesn't work.

Any other tips? Thanks!

答:
I tested on IE 7 and below is the updated CSS.

```<code>#primary-menu {
   /* margin:-30px auto 30px;*/ /*Avoid negative margins*/
}
#primary-menu ul {
  float:right;
}
#primary-menu li {
    float: left;
    list-style: none;
    margin-left: 10px;
        display:inline;
}
#primary-menu ul li a {
   /* float: right;*/ /*This caused the issue*/
   }
</code>```

Hope this helps

ContentLicense: CC BY-SA 3.0

Body:
Like many people, I am having trouble with floating elements in IE7 (and 6, but I don't care about that!)

http://www.storybox.co.nz/wordpress/

Looks fine in every other browser, but in IE7 the navigation links sit under each other:

HTML (inline styles are from js dropdown script):

Work.

Spatial /

Web /

Graphic

Lab.

About.

CSS:

#primary-menu {
    margin:-30px auto 30px;
}
#primary-menu ul {
    float:right;
}
#primary-menu li {
        float: left;
        list-style: none;
        margin-left: 10px;
            display:inline;
}
#primary-menu ul li a {
        float: right;
}

I have tried display:inline on the li items as well as on the a items, but that doesn't work.

Any other tips? Thanks!

Body:
I tested on IE 7 and below is the updated CSS.

#primary-menu {
   /* margin:-30px auto 30px;*/ /*Avoid negative margins*/
}
#primary-menu ul {
  float:right;
}
#primary-menu li {
    float: left;
    list-style: none;
    margin-left: 10px;
        display:inline;
}
#primary-menu ul li a {
   /* float: right;*/ /*This caused the issue*/
   }

Hope this helps


问:
Unable to add interpreter in pycharm , getting error exit status 101
I am unable to add an interpretor in pycharm . I have searched many forums but unable to solve .

Error:Command

```<code>'['C:\\Users\\USER NAME \\PycharmProjects\\pythonProject\\venv\\Scripts\\python.exe', '-Im', 'ensurepip', '--upgrade', '--default-pip']' returned non-zero exit status 101.
</code>```

I have python Python 3.7.8 in Windows 10 installed.

答:
Do you have a space in the path to your original python.exe? Most likely hidden as "USER NAME"? If so, look in "C:\Users" directory for a text file "USER" (being the first part of your account, without any extension). Delete this file and it'll likely to work again.

The same error happens with venv in Windows. See This Q&A for more details.

Body:
I am unable to add an interpretor in pycharm . I have searched many forums but unable to solve .

Error:Command

'['C:\\Users\\USER NAME \\PycharmProjects\\pythonProject\\venv\\Scripts\\python.exe', '-Im', 'ensurepip', '--upgrade', '--default-pip']' returned non-zero exit status 101.

I have python Python 3.7.8 in Windows 10 installed.


问:
Hekaton and Durability
Tech paper by Microsoft (Hekaton: SQL Server’s Memory-Optimized OLTP Engine) says

Generating a log record only at transaction commit time is possible
because Hekaton does not use write-ahead logging (WAL) to force log
changes to durable storage before dirty data. Dirty data is never
written to durable storage. Furthermore, Hekaton tries to group
multiple log records into one large I/O; this is the basis for group
commit and also a significant source of efficiency for Hekaton commit
processing.

No doubts, avoiding WAL and grouping multiple log records into one large I/O can improve performance but I'm struggling to understand how Durability can be guaranteed with such "improvements".

Can someone explain how (if) Hekaton handles the situation when crash happens after commit and before changes are persistent in the log?

According to SQL Server team blog

Hekaton’s main memory structures do away with the overhead and
indirection of the storage optimized view while still providing the
full ACID properties expected of a database system. For example,
durability in Hekaton is achieved by streamlined logging and
checkpointing that uses only efficient sequential IO.

答:
Can someone explain how (if) Hekaton handles the situation when crash happens after commit and before changes are persistent in the log?

Commit happens only after the log records are written, just like in traditional Write-Ahead Logging.  But in Write-Ahead Logging the database changes are also written to disk after the log records, which requires that the in-memory data structures for the database and the on-disk data structures are mostly the same.  Memory Optimized tables are not written to disk; instead they can be reconstructed from the logging and checkpointing during a crash recovery.

Using a data structure that can be efficiently written to and read from disk creates overhead since you can't simply refer to a row through native memory pointers.  Instead you have to find data by FileId:PageId:SlotId, or by an index key value that you traverse a BTree to locate.  If you allow the in-memory format to be different from the on-disk format, you can refer to rows using pointers, and describe the row structures as C Structs, and generate data access programs that run as native-compiled C operating on pointers and structs.

Title: Hekaton and Durability


问:
react-pdf utf8 font not working when on-fly-rendering, but works fine when render
My problem is i'm trying to save pdf file with 'on-fly-rendering' and utf8 font not working. But when displaying same pdf in render works fine.

Create pdf:

```<code>Font.register({
  family: "Roboto",
  src:
    "https://cdnjs.cloudflare.com/ajax/libs/ink/3.1.10/fonts/Roboto/roboto-light-webfont.ttf"
});

const styles = StyleSheet.create({
  page: {
    flexDirection: 'row',
    backgroundColor: '#E4E4E4',
    fontFamily: "Roboto",

  },
  section: {
    margin: 10,
    padding: 10,
    flexGrow: 1
  }
});
</code>```

Showing and saving pdf:

```<code>              <PDFViewer>
                <MyDocument data={data} />
              </PDFViewer>
              <PDFDownloadLink document={<MyDocument data={data}/>} fileName="lista_składników.pdf">
            {({ blob, url, loading, error }) => (loading ? 'Loading document...' : 'zapisz pdf')}
          </PDFDownloadLink>
</code>```

Output with PDFViewer:

Output with PDFDownloadLink:

答:
I had the same problem when only the first PDFDownloadLink has registered fonts. In the second one the fonts don't work.

I ended up using a better approach - generate a PDF on a button click as opposed to when a component loads.

https://github.com/diegomura/react-pdf/issues/736

```<code>import { saveAs } from 'file-saver';
import { pdf, Page, Text, View, Document } from '@react-pdf/renderer';

const generatePdfDocument = async (fileName, pdfDocumentComponent) => {
    const blob = await pdf(pdfDocumentComponent).toBlob();
    saveAs(blob, fileName);
};

const MyDocument = () => (
    <Document>
        <Page size="A4">
            <View>
                <Text>Section #1</Text>
            </View>
        </Page>
    </Document>
);

const DownloadButton = () => (
    <button
        type="button"
        onClick={() => {
            generatePdfDocument('MyDocument.pdf', <MyDocument />);
        }}
    >
        Download PDF
    </button>
);

export default DownloadButton;
</code>```

Body:
My problem is i'm trying to save pdf file with 'on-fly-rendering' and utf8 font not working. But when displaying same pdf in render works fine.

Create pdf:

Font.register({
  family: "Roboto",
  src:
    "https://cdnjs.cloudflare.com/ajax/libs/ink/3.1.10/fonts/Roboto/roboto-light-webfont.ttf"
});

const styles = StyleSheet.create({
  page: {
    flexDirection: 'row',
    backgroundColor: '#E4E4E4',
    fontFamily: "Roboto",

  },
  section: {
    margin: 10,
    padding: 10,
    flexGrow: 1
  }
});

Showing and saving pdf:

              <PDFViewer>
                <MyDocument data={data} />
              </PDFViewer>
              <PDFDownloadLink document={<MyDocument data={data}/>} fileName="lista_składników.pdf">
            {({ blob, url, loading, error }) => (loading ? 'Loading document...' : 'zapisz pdf')}
          </PDFDownloadLink>

Output with PDFViewer:

Output with PDFDownloadLink:

Body:
I had the same problem when only the first PDFDownloadLink has registered fonts. In the second one the fonts don't work.

I ended up using a better approach - generate a PDF on a button click as opposed to when a component loads.

https://github.com/diegomura/react-pdf/issues/736

import { saveAs } from 'file-saver';
import { pdf, Page, Text, View, Document } from '@react-pdf/renderer';

const generatePdfDocument = async (fileName, pdfDocumentComponent) => {
    const blob = await pdf(pdfDocumentComponent).toBlob();
    saveAs(blob, fileName);
};

const MyDocument = () => (
    <Document>
        <Page size="A4">
            <View>
                <Text>Section #1</Text>
            </View>
        </Page>
    </Document>
);

const DownloadButton = () => (
    <button
        type="button"
        onClick={() => {
            generatePdfDocument('MyDocument.pdf', <MyDocument />);
        }}
    >
        Download PDF
    </button>
);

export default DownloadButton;


问:
Unwanted early wrapping with "word-break: break-all" (and "break-word")
I have a long string, without whitespace, and a I want to place it in a div, such that

It fills the div as much as possible, without overflowing.

It uses the same amount of characters on each line (except the last, which line may be less).

The div is a responsive div, with width 90vw and height 84vh.

The HTML is:

```<code><div class = "content"><p><code>Some-very-large-string-without-white-space"</code></p></div>
</code>```

Scaling the font so it just fits is easy with a bit of JavaScript:

```<code>function font_fiddle (selection) {
    let element  = document . querySelector (selection)

    let fontSize = element . clientHeight

    if (!element . innerHTML . length) {
        return;
    }

    element . style . fontSize = fontSize + 'px';
    while (element . scrollHeight > element . clientHeight && fontSize > 0) {
        element . style . fontSize  = -- fontSize + 'px';
    }
}
</code>```

font_fiddle (".content") is called when the document loads, and when the window resizes. This parts works well.

The CSS for the code element is:

```<code>code {
    word-break: break-all;
    color: lightgreen;
    background: black;
    font-style: initial;
    font-family: 'Source Code Pro', monospace;
    font-size: 95%;
}
</code>```

Due to the monospace font, and the word-break: break-all, I would expect all lines (with the exception of the last) to have the same number of characters, and to have a straight right "edge". And this would be the case if the string contains just letters and digits. But my string doesn't, and this leads to some lines being a one or a few characters shorter than possible:

Changing the CSS to word-break: break-word; has some effect, but we're still left with a jagged right edge:

Is there a way to get every line contain the same amount of characters, regardless of what those characters are?

This all is with Firefox on MacOS.

答:
with using

```<code>  text-align: justify;
  text-justify: inter-character;
  word-break: break-all;
</code>```

I think it will solve your problem .

div {
  width: 50vw;
  height: 50vh;
  border: 1px solid;
  margin: auto;

  text-align: justify;
  text-justify: inter-character;
  word-break: break-all;

  background: #000;
  color: green;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
 Inmyyo/unger5andmorevu5l*nerableyearsmyfathe*rgave45me/5someadvicethatI'vebeentur45ningo/ver/i5n24ymindeversince.5'W4heneve*ryou-/55feel-55lik8ec5*rit4icizi5ng45anyo4ne5'h*etol4/545dme,'j4u/s5trememberthatallthepeoplei5n45th4sworld5haven't/hadt5h4eadvanta5gesthatyou'vehad.'
</div></code>```

Body:
I have a long string, without whitespace, and a I want to place it in a div, such that

It fills the div as much as possible, without overflowing.

It uses the same amount of characters on each line (except the last, which line may be less).

The div is a responsive div, with width 90vw and height 84vh.

The HTML is:

Some-very-large-string-without-white-space"

Scaling the font so it just fits is easy with a bit of JavaScript:

function font_fiddle (selection) {
    let element  = document . querySelector (selection)

    let fontSize = element . clientHeight

    if (!element . innerHTML . length) {
        return;
    }

    element . style . fontSize = fontSize + 'px';
    while (element . scrollHeight > element . clientHeight && fontSize > 0) {
        element . style . fontSize  = -- fontSize + 'px';
    }
}

font_fiddle (".content") is called when the document loads, and when the window resizes. This parts works well.

The CSS for the code element is:

code {
    word-break: break-all;
    color: lightgreen;
    background: black;
    font-style: initial;
    font-family: 'Source Code Pro', monospace;
    font-size: 95%;
}

Due to the monospace font, and the word-break: break-all, I would expect all lines (with the exception of the last) to have the same number of characters, and to have a straight right "edge". And this would be the case if the string contains just letters and digits. But my string doesn't, and this leads to some lines being a one or a few characters shorter than possible:

Changing the CSS to word-break: break-word; has some effect, but we're still left with a jagged right edge:

Is there a way to get every line contain the same amount of characters, regardless of what those characters are?

This all is with Firefox on MacOS.

Body:
with using

  text-align: justify;
  text-justify: inter-character;
  word-break: break-all;

I think it will solve your problem .

div {
  width: 50vw;
  height: 50vh;
  border: 1px solid;
  margin: auto;

  text-align: justify;
  text-justify: inter-character;
  word-break: break-all;

  background: #000;
  color: green;
}

<div class="container">
 Inmyyo/unger5andmorevu5l*nerableyearsmyfathe*rgave45me/5someadvicethatI'vebeentur45ningo/ver/i5n24ymindeversince.5'W4heneve*ryou-/55feel-55lik8ec5*rit4icizi5ng45anyo4ne5'h*etol4/545dme,'j4u/s5trememberthatallthepeoplei5n45th4sworld5haven't/hadt5h4eadvanta5gesthatyou'vehad.'
</div>


问:
Terraform Snowpipe on Azure error on integration
I'm trying to set up snowpipe with terraform on azure using https://registry.terraform.io/providers/chanzuckerberg/snowflake/latest/docs/resources/pipe#optional

my resource looks like this:

```<code>resource "snowflake_pipe" "pipe" {
  provider = snowflake.sys_admin
  integration = "myintegration"
  database = "mydb"
  schema   = "PUBLIC"
  name     = "mypipe"

  comment = "A pipe."

  copy_statement = "copy into \"db\".\"schema\".\"table\" from (select $1,$2,$3,$4,$5, $6, $7, $8, $9, $10, metadata$filename, metadata$file_row_number, current_timestamp  from   @db.PUBLIC.stage (file_format => TEST.PUBLIC.CSV))"
  auto_ingest    = true

}
</code>```

when I run terraform apply I get:

An argument named "integration" is not expected here.

If I remove integration = "myintegration" from above I get:

Pipe Notifications bind failure "Integration cannot be null for Azure."

Has anyone managed to go around this?

答: The integration argument was added to the resource schema in this commit on June 4, 2021. The provider is lacking a full CHANGELOG, so we have to use the general timeline estimates for versions from the provider registry. In that case, it would appear that you would need to upgrade your provider version to at least 0.25.0 to support this functionality.

Body:
I'm trying to set up snowpipe with terraform on azure using https://registry.terraform.io/providers/chanzuckerberg/snowflake/latest/docs/resources/pipe#optional

my resource looks like this:

resource "snowflake_pipe" "pipe" {
  provider = snowflake.sys_admin
  integration = "myintegration"
  database = "mydb"
  schema   = "PUBLIC"
  name     = "mypipe"

  comment = "A pipe."

  copy_statement = "copy into \"db\".\"schema\".\"table\" from (select $1,$2,$3,$4,$5, $6, $7, $8, $9, $10, metadata$filename, metadata$file_row_number, current_timestamp  from   @db.PUBLIC.stage (file_format => TEST.PUBLIC.CSV))"
  auto_ingest    = true

}

when I run terraform apply I get:

An argument named "integration" is not expected here.

If I remove integration = "myintegration" from above I get:

Pipe Notifications bind failure "Integration cannot be null for Azure."

Has anyone managed to go around this?


问:
One httpClient for many method in one class
I would like to use one httpclient to many method in class.
Below is the simplified code:

public class test{

private readonly HttpClient _httpClient;

```<code>public Test(){
_httpClient = new HttpClient();
}

public void method1(){
using (_httpClient){
//...
}
}

public void method2(){
using (_httpClient){
//...
}
}

public void method3(){
using (_httpClient){
//...
}
}
}
</code>```

Then it calls the method data:

```<code>public async static void TestHttpClient()
        {
            Test test1 = new Test();
            test1.Method1();
            test1.Method2();
            test1.Method3();
        }
</code>```

Method 1 is working. When calling the second one I get the message: "You cannot access a deleted object."

Thanks for helps.

Regards

答:
One way to do it is to create a private variable and a get accessor

    private HttpClient _httpClient;

    private HttpClient MyClient
    {
        get {
            if (_httpClient == null)
            {
                _httpClient = new HttpClient
                {
                    BaseAddress = new Uri($"https://your.url/")
                };
                //Other client logic goes here
            }
            return _httpClient;
        }
    }
```
<p>Then from your method, you just reference the accessor</p>
<pre class="lang-cs prettyprint-override"><code>public async Task method1()
{
    await MyClient.Post() //post logic here
   //...
}
</code>```

You don't need to dispose HttpClient, MS recommends leaving the object in place, unless you know you need to forcibly close the connection.

Body:
I would like to use one httpclient to many method in class.
Below is the simplified code:

public class test{

private readonly HttpClient _httpClient;

public Test(){
_httpClient = new HttpClient();
}

public void method1(){
using (_httpClient){
//...
}
}

public void method2(){
using (_httpClient){
//...
}
}

public void method3(){
using (_httpClient){
//...
}
}
}

Then it calls the method data:

public async static void TestHttpClient()
        {
            Test test1 = new Test();
            test1.Method1();
            test1.Method2();
            test1.Method3();
        }

Method 1 is working. When calling the second one I get the message: "You cannot access a deleted object."

Thanks for helps.

Regards

Body:
One way to do it is to create a private variable and a get accessor

    private HttpClient _httpClient;

    private HttpClient MyClient
    {
        get {
            if (_httpClient == null)
            {
                _httpClient = new HttpClient
                {
                    BaseAddress = new Uri($"https://your.url/")
                };
                //Other client logic goes here
            }
            return _httpClient;
        }
    }

Then from your method, you just reference the accessor

public async Task method1()
{
    await MyClient.Post() //post logic here
   //...
}

You don't need to dispose HttpClient, MS recommends leaving the object in place, unless you know you need to forcibly close the connection.


问:
How to add CSS code for multiple color in one click on web page
How to add a CSS which we can change. like if we change in one place, the color of the whole website should get changed.

Screenshot : screenshot for Sample

Sample website : https://themezhub.net/rikada-demo-05/rikada/index.html#

as you can see in above website, they have a slider in left side and which contain a list of color, if you choose any color the whole website color will change.

How to make like this?.

Example :

I define the color code in one place of CSS or website and then the whole website should get changed according to it.

答:
You have to add the class with the body tag on click left side colors. Then add CSS of color for each element that you'd like to update.

how the change color works on reference site


问:
How to search for a string with one double quote with git grep in Windows cmd
The problem is that strings with two qoutes are searched well. But! I want to look for a string "Agent (one double quote!) inside my repo on cmd in Windows. So I having this:

git grep "\"Agent\"" > 1.txt (it works! all strings with "Agent" was found)

git grep "\"Agent" > 1.txt (error! fatal: ambiguous argument '>': unknown revision...)

Any ideas how to properly escape?

答:
In Git CMD or Windows cmd console, you can use ^ to escape the " inside the terminal:

git grep ""^""Agent" > 1.txt
```
<p>In Git Bash, you can simply use</p>
<pre class="lang-none prettyprint-override"><code>git grep '"Agent' > 1.txt
</code>```

See this text I made on my data with "Regex pattern:

Body:
In Git CMD or Windows cmd console, you can use ^ to escape the " inside the terminal:

git grep ""^""Agent" > 1.txt

In Git Bash, you can simply use

git grep '"Agent' > 1.txt

See this text I made on my data with "Regex pattern:


问:
Using appsettings.json values in Automapper configuration
Is there a way to get a value from appsettings.json when mapping two objects in Automapper?

```<code>public class MapperProfile : Profile
{
     public MapperProfile()
     {
          CreateMap<Employee, EmployeeDto>()
             .ForMember(employeeDto => employeeDto.Picture, employee => employee.MapFrom(employee => $"{someValueFromAppSettings}{employee.Picture}"
     }
}
</code>```

I need to append a path before the picture's name on mapping but I can't seem to figure it out how and whether it is even possible with Automapper.

答:
From the AutoMapper documentation:

You can’t inject dependencies into Profile classes.

But there are (at least) 2 ways you can achieve what you want:

Using IValueResolver<in TSource, in TDestination, TDestMember> interface.

```<code>public class EmployeeDtoPathResolver: IValueResolver<Employee, EmployeeDto, string>
    {
        private readonly IConfiguration _configuration
        public CarBrandResolver(IConfiguration configuration)
        {
            _configuration= configuration;
        }

        public string Resolve(Employee source, EmployeeDto destination, int destMember, ResolutionContext context)
        {
            var path = // get the required path from _configuration;
            return $"{path}{source.Picture}"
        }
    }
</code>```
```<code>public class MapperProfile : Profile
{
     public MapperProfile()
     {
          CreateMap<Employee, EmployeeDto>()
             .ForMember(employeeDto => employeeDto.Picture, opt => opt.MapFrom<EmployeeDtoPathResolver>()); // Edited this
     }
}
</code>```

Using IMappingAction<in TSource, in TDestination> implementations.

It is basically an encapsulation of Before and After Map Actions into small reusable classes.

```<code>public class EmployeeDtoAction : IMappingAction<Employee, EmployeeDto>
{
    private readonly IConfiguration _configuration;

    public EmployeeAction (IConfiguration configuration)
    {
        _configuration = configuration ?? throw new ArgumentNullException(nameof(configuration));
    }

    public void Process(Employee source, EmployeeDto destination, ResolutionContext context)
    {
        var path =  // get the required path from _configuration;
        destination.Picture = $"{path}{destination.Picture}"
    }
}
</code>```
```<code>public class MapperProfile : Profile
{
     public MapperProfile()
     {
          CreateMap<Employee, EmployeeDto>()
             .AfterMap<EmployeeDtoAction>(); // Added this
     }
}
</code>```

Body:
Is there a way to get a value from appsettings.json when mapping two objects in Automapper?

public class MapperProfile : Profile
{
     public MapperProfile()
     {
          CreateMap<Employee, EmployeeDto>()
             .ForMember(employeeDto => employeeDto.Picture, employee => employee.MapFrom(employee => $"{someValueFromAppSettings}{employee.Picture}"
     }
}

I need to append a path before the picture's name on mapping but I can't seem to figure it out how and whether it is even possible with Automapper.

Body:
From the AutoMapper documentation:

You can’t inject dependencies into Profile classes.

But there are (at least) 2 ways you can achieve what you want:

Using IValueResolver<in TSource, in TDestination, TDestMember> interface.

public class EmployeeDtoPathResolver: IValueResolver<Employee, EmployeeDto, string>
    {
        private readonly IConfiguration _configuration
        public CarBrandResolver(IConfiguration configuration)
        {
            _configuration= configuration;
        }

        public string Resolve(Employee source, EmployeeDto destination, int destMember, ResolutionContext context)
        {
            var path = // get the required path from _configuration;
            return $"{path}{source.Picture}"
        }
    }

public class MapperProfile : Profile
{
     public MapperProfile()
     {
          CreateMap<Employee, EmployeeDto>()
             .ForMember(employeeDto => employeeDto.Picture, opt => opt.MapFrom<EmployeeDtoPathResolver>()); // Edited this
     }
}

Using IMappingAction<in TSource, in TDestination> implementations.

It is basically an encapsulation of Before and After Map Actions into small reusable classes.

public class EmployeeDtoAction : IMappingAction<Employee, EmployeeDto>
{
    private readonly IConfiguration _configuration;

    public EmployeeAction (IConfiguration configuration)
    {
        _configuration = configuration ?? throw new ArgumentNullException(nameof(configuration));
    }

    public void Process(Employee source, EmployeeDto destination, ResolutionContext context)
    {
        var path =  // get the required path from _configuration;
        destination.Picture = $"{path}{destination.Picture}"
    }
}

public class MapperProfile : Profile
{
     public MapperProfile()
     {
          CreateMap<Employee, EmployeeDto>()
             .AfterMap<EmployeeDtoAction>(); // Added this
     }
}


问:
Directive to upper case input fields
I want to use a directive to transform all input data to uppercase. To achieve that, I create this custom directive :

```<code>@Directive({
  selector: '[appToUpperCase]'
})
export class ToUpperCaseDirective {

  constructor() {}

  @HostListener('input', ['$event']) onKeyUp(event) {
    event.target['value'] = event.target['value'].toUpperCase();
  }

}
</code>```

And I use it like that :

```<code><form [formGroup]="formGroup" appToUpperCase>
</code>```

It works almost good exept that when I enter text in my field, the upper case transform is permormed but the focus is set at the end of the field...So when I edit a pre filled input, if I want to modify the begining of the data, I have to set the focus at the right place after each Keyup event...

How can I fix that ?

答:
Upgrading @Leasye answer due to the deprecation of initEvent as mentioned by @robert
I have used Event class to create the event.
I've also used setProperty() method of Renderer2 to assign value to input element, rather than assigning it to the DOM object directly.

import { Directive, ElementRef, HostListener, Renderer2 } from '@angular/core';

@Directive({
  selector: '[appTextUppercase]'
})
export class TextUppercaseDirective {
  preValue: string = "";

  constructor(private elmRef: ElementRef, private renderer: Renderer2) { }

  @HostListener('input', ['$event']) onInput(event: any) {
    const text_upper = event.target.value.toUpperCase();
    if (!this.preValue || (this.preValue && text_upper && this.preValue !== text_upper)) {
      this.preValue = text_upper;
      this.renderer.setProperty(this.elmRef.nativeElement, 'value', text_upper);
      const htmlEvent = new Event('input', { "bubbles": false, "cancelable": true
    });
        document.dispatchEvent(htmlEvent);
        }
    };
}```

However, would like to point to an issue in the above directive, that it does not bind the last edited character in case of editing the field value by moving the cursor back. In which case solution by @Andy works fine.

Title: Directive to upper case input fields

Body:
I want to use a directive to transform all input data to uppercase. To achieve that, I create this custom directive :

@Directive({
  selector: '[appToUpperCase]'
})
export class ToUpperCaseDirective {

  constructor() {}

  @HostListener('input', ['$event']) onKeyUp(event) {
    event.target['value'] = event.target['value'].toUpperCase();
  }

}

And I use it like that :

<form [formGroup]="formGroup" appToUpperCase>

It works almost good exept that when I enter text in my field, the upper case transform is permormed but the focus is set at the end of the field...So when I edit a pre filled input, if I want to modify the begining of the data, I have to set the focus at the right place after each Keyup event...

How can I fix that ?

Body:
Upgrading @Leasye answer due to the deprecation of initEvent as mentioned by @robert
I have used Event class to create the event.
I've also used setProperty() method of Renderer2 to assign value to input element, rather than assigning it to the DOM object directly.

import { Directive, ElementRef, HostListener, Renderer2 } from '@angular/core';

@Directive({
  selector: '[appTextUppercase]'
})
export class TextUppercaseDirective {
  preValue: string = "";

  constructor(private elmRef: ElementRef, private renderer: Renderer2) { }

  @HostListener('input', ['$event']) onInput(event: any) {
    const text_upper = event.target.value.toUpperCase();
    if (!this.preValue || (this.preValue && text_upper && this.preValue !== text_upper)) {
      this.preValue = text_upper;
      this.renderer.setProperty(this.elmRef.nativeElement, 'value', text_upper);
      const htmlEvent = new Event('input', { "bubbles": false, "cancelable": true
    });
        document.dispatchEvent(htmlEvent);
        }
    };
}

However, would like to point to an issue in the above directive, that it does not bind the last edited character in case of editing the field value by moving the cursor back. In which case solution by @Andy works fine.


问:
Something Easier than jq UI Dialog?
Is it just me, or is Jquery UI Dialog really difficult to grasp.  I am not a javascript developer, and I don't feel like learning the language (not right now anyway... this project is on a deadline!).  Isn't there anything simpler that uses the latest jquery and is relatively simple to use?  Like you know, set an id or a class (id preferably) for the form and call a simple jquery function?  Why does it have to be so hard?  And no simpleDialog.  Some of those scripts conflict with my other scripts and make my other jquery function crap out (I spent 13 hours yesterday trying to figure that one out)...</p>

答:
I've never used the UI Dialog, but you can try a modal popup: http://www.queness.com/post/77/simple-jquery-modal-window-tutorial

You can style it however you like, and use simple jquery show/hide functions to display it. =)

Title: Something Easier than jq UI Dialog?


问:
Does an Android Studio Linux arm64 version exist?
Does an Android Studio Linux arm64 version exist?.

I think now is a good time to support it since the new mac m1 machine is arm64 and some work is being done to run Linux on top of it.

Also I am developing with Flutter which (as far as I understand) already supports Linux arm64.

But I can't find any GitHub repo for Android Studio to request support, if you know any please post it in the comments.

More people that asked on other forums:

On Reddit.

And another one on Reddit.

Chromebook is based on Linux so adding a link for installation for that on Reddit too.

答:
Yes the Stable version is released for the Chromebooks

https://www.reddit.com/r/AndroidStudio/comments/e8r9or/how_to_install_android_studio_stable_release_on/


问:
How do I create a pandas column using a different function depending on what month it is in?
I have been given a JSON file that has information about flight delays from seven different airports. I have saved this to a pandas data frame called flights. The data doesn't accurately display how many flights were delayed by weather so I have been assigned to recalculate that information. If the month is between April and August it is calculated differently than the rest of the months. I initially tried lambda with an if flights["month"] in delay_40. Second I tried an np.where without using an in statement, then np.select using dot notation instead of bracket notation. Each different implementation has given me the same error message. ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

Just a heads up, the indentation here is to improve readability. I understand that you can't have indentation in a lambda statement, and I don't know if it affects np.select or np.where.

```<code>delay_40 = ["April", "May", "June", "July", "August"]

weather_delay_total = flights

weather_delay_total = flights.assign(
    improved_delays_weather = lambda row:
    (round(row["num_of_delays_weather"] + (.3 * row["num_of_delays_late_aircraft"]) + (.4 * row["num_of_delays_nas"]))) if (row["month"] in delay_40)
    else (round(row["num_of_delays_weather"] + (.3 * row["num_of_delays_late_aircraft"]) + (.65 * row["num_of_delays_nas"])))
)

weather_delay_total["improved_delays_weather"] = np.where(
    flights.month == "April" or flights.month == "May" or flights.month == "June" or flights.month == "July" or flights.month == "August",
    round(flights["num_of_delays_weather"] + (.3 * flights["num_of_delays_late_aircraft"]) + (.4 * flights["num_of_delays_nas"])),
    round(flights["num_of_delays_weather"] + (.3 * flights["num_of_delays_late_aircraft"]) + (.65 * flights["num_of_delays_nas"])))

weather_delay_total = flights.assign(
    improved_delays_weather = np.select(
        flights.month == "April" or flights.month == "May" or flights.month == "June" or flights.month == "July" or flights.month == "August",
        round(flights.num_of_delays_weather + (.3 * flights.num_of_delays_late_aircraft) + (.4 * flights.num_of_delays_nas)),
        round(flights.num_of_delays_weather + (.3 * flights.num_of_delays_late_aircraft) + (.65 * flights.num_of_delays_nas)
    )
)
</code>```

答: This question was answered by Parfait and mozway in the comments. I used np.where = flights["month"].isin(delay_40) and it worked perfectly. Thank you Parfait and mozway!

Body:
I have been given a JSON file that has information about flight delays from seven different airports. I have saved this to a pandas data frame called flights. The data doesn't accurately display how many flights were delayed by weather so I have been assigned to recalculate that information. If the month is between April and August it is calculated differently than the rest of the months. I initially tried lambda with an if flights["month"] in delay_40. Second I tried an np.where without using an in statement, then np.select using dot notation instead of bracket notation. Each different implementation has given me the same error message. ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

Just a heads up, the indentation here is to improve readability. I understand that you can't have indentation in a lambda statement, and I don't know if it affects np.select or np.where.

delay_40 = ["April", "May", "June", "July", "August"]

weather_delay_total = flights

weather_delay_total = flights.assign(
    improved_delays_weather = lambda row:
    (round(row["num_of_delays_weather"] + (.3 * row["num_of_delays_late_aircraft"]) + (.4 * row["num_of_delays_nas"]))) if (row["month"] in delay_40)
    else (round(row["num_of_delays_weather"] + (.3 * row["num_of_delays_late_aircraft"]) + (.65 * row["num_of_delays_nas"])))
)

weather_delay_total["improved_delays_weather"] = np.where(
    flights.month == "April" or flights.month == "May" or flights.month == "June" or flights.month == "July" or flights.month == "August",
    round(flights["num_of_delays_weather"] + (.3 * flights["num_of_delays_late_aircraft"]) + (.4 * flights["num_of_delays_nas"])),
    round(flights["num_of_delays_weather"] + (.3 * flights["num_of_delays_late_aircraft"]) + (.65 * flights["num_of_delays_nas"])))

weather_delay_total = flights.assign(
    improved_delays_weather = np.select(
        flights.month == "April" or flights.month == "May" or flights.month == "June" or flights.month == "July" or flights.month == "August",
        round(flights.num_of_delays_weather + (.3 * flights.num_of_delays_late_aircraft) + (.4 * flights.num_of_delays_nas)),
        round(flights.num_of_delays_weather + (.3 * flights.num_of_delays_late_aircraft) + (.65 * flights.num_of_delays_nas)
    )
)


问:
how use optional parameters in cucumber
I want the same Gherkin sentence (with paramaters and without paramaters):

Gherkin with paramaters:

```<code>When a 'notify' message is sent to the green box with the properties.
 |type|message|
 |error|The error message|
</code>```

Gherkin without paramaters:

```<code>When a 'notify' message is sent to the green box with the properties.
</code>```

Java (cucumber):

```<code>@When("^a '(.*)' message is sent to the green box with the properties.$")
public void hello(String name, List<GherkinCondition> conditions) {
    ...
}
</code>```

I have a error because java method is is declared with 2 parameters and in the case "without paramaters" I have only one.

stack trace:

```<code>cucumber.runtime.CucumberException: Arity mismatch: Step Definition 'steps.CommonSteps.hello(String,GherkinCondition>) in file:/C:/workspace/xxxxx/java/target/classes/' with pattern [^a '(.*)' message is sent to the green box with the properties.$] is declared with 2 parameters. However, the gherkin step has 1 arguments [notify].
</code>```

答:
Till now, there is no solution for this;

Alternative text only works when there is no whitespace between the
alternative parts.

Hence your way of using () -> optional is the best we have now.

Title: how use optional parameters in cucumber

Body:
I want the same Gherkin sentence (with paramaters and without paramaters):

Gherkin with paramaters:

When a 'notify' message is sent to the green box with the properties.
 |type|message|
 |error|The error message|

Gherkin without paramaters:

When a 'notify' message is sent to the green box with the properties.

Java (cucumber):

@When("^a '(.*)' message is sent to the green box with the properties.$")
public void hello(String name, List<GherkinCondition> conditions) {
    ...
}

I have a error because java method is is declared with 2 parameters and in the case "without paramaters" I have only one.

stack trace:

cucumber.runtime.CucumberException: Arity mismatch: Step Definition 'steps.CommonSteps.hello(String,GherkinCondition>) in file:/C:/workspace/xxxxx/java/target/classes/' with pattern [^a '(.*)' message is sent to the green box with the properties.$] is declared with 2 parameters. However, the gherkin step has 1 arguments [notify].


问:
Avoid dynamic SQL generation when calling stored procedure on SQL server from R/DBI/ODBC
Using the profiler on SQL Server to monitor a stored procedure call via DBI/odbc, shows that dynamic SQL / prepared statement is generated :

```<code>con <- DBI::dbConnect(odbc::odbc(),...)
dbGetQuery(con, "EXEC sp_helptext 'sys.sp_addlogin';")
</code>```

Results on SQL Server in:

declare @p1 int
set @p1=2
exec sp_prepexec @p1 output,NULL,N'EXEC sp_helptext ''sys.sp_addlogin'';'
select @p1
```
<p>For database safety & performance we disabled dynamic SQL calls, so that I would like a direct call:</p>
```EXEC sp_helptext 'sys.sp_addlogin';
```

Not sure if the dynamic SQL overlay is generated by DBI or by the odbc driver.

Is there a way to avoid it?

答:
I found what I was looking for in odbc package documentation : direct execution.

The odbc package uses Prepared Statements to compile the query once and reuse it, allowing large or repeated queries to be more efficient. However, prepared statements can actually perform worse in some cases, such as many different small queries that are all only executed once.
Because of this the odbc package now also supports direct queries by specifying immediate = TRUE.

This will use a prepared statement:

```<code>dbGetQuery(con, "EXEC sp_helptext 'sys.sp_addlogin';")
</code>```

declare @p1 int

set @p1=2

exec sp_prepexec @p1 output,NULL,N'EXEC sp_helptext ''sys.sp_addlogin'';'

select @p1

This will execute the stored procedure directly:

```<code>dbGetQuery(con, "EXEC sp_helptext 'sys.sp_addlogin';",immediate = TRUE)
</code>```

EXEC sp_helptext 'sys.sp_addlogin';

Body:
Using the profiler on SQL Server to monitor a stored procedure call via DBI/odbc, shows that dynamic SQL / prepared statement is generated :

con <- DBI::dbConnect(odbc::odbc(),...)
dbGetQuery(con, "EXEC sp_helptext 'sys.sp_addlogin';")

Results on SQL Server in:

declare @p1 int
set @p1=2
exec sp_prepexec @p1 output,NULL,N'EXEC sp_helptext ''sys.sp_addlogin'';'
select @p1

For database safety & performance we disabled dynamic SQL calls, so that I would like a direct call:

EXEC sp_helptext 'sys.sp_addlogin';

Not sure if the dynamic SQL overlay is generated by DBI or by the odbc driver.

Is there a way to avoid it?

Body:
I found what I was looking for in odbc package documentation : direct execution.

The odbc package uses Prepared Statements to compile the query once and reuse it, allowing large or repeated queries to be more efficient. However, prepared statements can actually perform worse in some cases, such as many different small queries that are all only executed once.
Because of this the odbc package now also supports direct queries by specifying immediate = TRUE.

This will use a prepared statement:

dbGetQuery(con, "EXEC sp_helptext 'sys.sp_addlogin';")

declare @p1 int

set @p1=2

exec sp_prepexec @p1 output,NULL,N'EXEC sp_helptext ''sys.sp_addlogin'';'

select @p1

This will execute the stored procedure directly:

dbGetQuery(con, "EXEC sp_helptext 'sys.sp_addlogin';",immediate = TRUE)

EXEC sp_helptext 'sys.sp_addlogin';


问:
Need code to add just one product to wishlist rather than adding product multiple times
I've made a wishlist which works like it should do by adding the product to the wishlist when I press the heart button. However, I have a minor issue! When I add a product to the wishlist and then click on the heart button again, it adds the same product multiple times which is something I do not want. Can anyone help me find some code that only adds the product once so that if that product is already in the wishlist, it won't add it again. Your help would be greatly appreciated! Thanks.

var wishlistkey = "wishlist";
// try and fetch an existing wishlist from the localStorage.
var wish_list = []; // localStorage.getItem(wishlistkey)

if ($.isEmptyObject(wish_list)) { //nothing was saved previously
  wish_list = new Array()
} else {
  wish_list = JSON.parse(wish_list);
  count_items_in_wishlist_update();
  $('#wish_list_item').html(wish_list);
}

$(document).ready(function() {
  $(".wishlist").on("click", function() {
    $data = "";
    $office_id = $(this).attr("office_id");
    $office_name = $(this).attr("office_name");
    $office_str = "
" + $office_name + "	x
";
    //check if the element is in the array
    if ($.inArray($office_id, wish_list) == -1) {

      $("#wish_list_item").append($office_str);

      wish_list.push($office_str);
      //  localStorage.setItem(wishlistkey, JSON.stringify(wish_list))
      show_message($office_name + " Office Added");
    }
    count_items_in_wishlist_update();
  });

  //adding toggle functionality to the wishlist pannel
  $(".wish_list_heading").on("click", function() {
    if (!$(this).hasClass("up")) {
      $("#wish_list").css("height", "390px");
      $(this).addClass("up");
      $("#wish_list").css("overflow", "auto");
    } else {
      $("#wish_list").css("height", "35px");
      $(this).removeClass("up");
      $("#wish_list").css("overflow", "hidden");
    }

  });
  // Remove function
  $("#wish_list_item").on("click", ".w-premove", function() {
    $office_id = $(this).attr("wpid");
    $("#list_id_" + $office_id).remove();
    wish_list = [];

    $("tr.wishlist-item").each(function(index, el) {
      wish_list.push(el.outerHTML);
    });
    //localStorage.setItem(wishlistkey, JSON.stringify(wish_list));

    show_message("Office removed");
    count_items_in_wishlist_update();

  });
});
//Animation
function show_message($msg) {
  $("#msg").html($msg);
  $top = Math.max(0, (($(window).height() - $("#msg").outerHeight()) / 2) + $(window).scrollTop()) + "px";
  $left = Math.max(0, (($(window).width() - $("#msg").outerWidth()) / 2) + $(window).scrollLeft()) + "px";
  $("#msg").css("left", $left);
  $("#msg").animate({
    opacity: 0.6,
    top: $top
  }, 400, function() {
    $(this).css({
      'opacity': 1
    });
  }).show();
  setTimeout(function() {
    $("#msg").animate({
      opacity: 0.6,
      top: "0px"
    }, 400, function() {
      $(this).hide();
    });
  }, 2000);
}

//Validation against the amount of product being added
function count_items_in_wishlist_update() {
  $("#listitem").html(wish_list.length);
  if (wish_list.length > 1) {
    $("#p_label").html("Shortlist (");
  } else {
    $("#p_label").html("Shortlist (");
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>button a {
  color: #fff !important;
}

button {
  font-family: 'open sans', sans-serif;
  font-size: 15px;
}

button {
  text-align: center;
  padding: 1px 7px;
  margin: 0 5px 0;
  border: 4px solid #000;
  background-color: #000;
  vertical-align: middle;
  cursor: pointer;
  white-space: nowrap;
  font-size: 35px;
  color: #fff;
}

#wish_list {
  position: fixed;
  bottom: 0px;
  right: 0px;
  height: 35px;
  width: 400px;
  background: #fff;
  border: 3px solid #22a7c5;
  z-index: 3;
}

#wish_list .wish_list_heading {
  margin: 0px 0px;
  text-align: center;
  color: #fff;
  height: 27px;
  background-color: #22a7c5;
  padding: 6px 3px;
  font-weight: bold;
  cursor: pointer;
  font-size: 18px;
}

#wish_list_item {
  width: 100%;
  text-align: center;
  border-spacing: 0px 4px;
  border-collapse: separate;
}

#msg {
  position: fixed;
  display: none;
  padding: 10px 25px;
  background: #22a7c5;
  border: 1px solid #22a7c5;
  font-size: 18px;
  width: 50%;
  text-align: center;
  font-weight: 700;
  color: #fff;
  z-index: 4;
}

.wishlist-item {
  padding: 10px 5px;
  background: #f1f1f1;
  color: #323470;
}

.w-premove {
  font-size: 20px;
  cursor: pointer;
  width: 7%;
  padding-bottom: 4px;
}

.w-pname {
  font-size: 16px;
  width: 93%;
  text-align: left;
  padding-left: 12px;
}</code>```

    Shortlist (
    0
    )

  <button class='wishlist' title="Add To Shortlist" office_name='Hampton Street' office_id='hamptonstreet'>
        ❤
      </button>

```

答:
I have modified your code a little here is what you need to update:
(it checks for include method which returns in true or false based on wether the item is already in the array or not, if its not, it will add item, otherwise)

```<code>var wishlistkey = "wishlist";
// try and fetch an existing wishlist from the localStorage.
var wish_list = []; // localStorage.getItem(wishlistkey)

if ($.isEmptyObject(wish_list)) { //nothing was saved previously
  wish_list = new Array()
} else {
  wish_list = JSON.parse(wish_list);
  count_items_in_wishlist_update();
  $('#wish_list_item').html(wish_list);
}

$(document).ready(function() {
  $(".wishlist").on("click", function() {
    $data = "";
    $office_id = $(this).attr("office_id");
    $office_name = $(this).attr("office_name");
    $office_str = "<tr class='wishlist-item' id='list_id_" + $office_id + "'><td class='w-pname'>" + $office_name + "</td><td class='w-premove' wpid='" + $office_id + "'>x</td></tr>";
    //check if the element is in the array
    if ($.inArray($office_id, wish_list) == -1) {

  if(!wish_list.includes($office_str))
  {
        $("#wish_list_item").append($office_str);
        wish_list.push($office_str);
        //  localStorage.setItem(wishlistkey, JSON.stringify(wish_list))
       show_message($office_name + " Office Added");
  }
  else
  {
       var myIndex = wish_list.indexOf($office_str);
       if (myIndex!==-1)
       wish_list.splice(myIndex, 1);
       $("#wish_list_item").remove();
       show_message("Office removed");
       count_items_in_wishlist_update();
  }

}
    count_items_in_wishlist_update();
  });

  //adding toggle functionality to the wishlist pannel
  $(".wish_list_heading").on("click", function() {
    if (!$(this).hasClass("up")) {
      $("#wish_list").css("height", "390px");
      $(this).addClass("up");
      $("#wish_list").css("overflow", "auto");
    } else {
      $("#wish_list").css("height", "35px");
      $(this).removeClass("up");
      $("#wish_list").css("overflow", "hidden");
    }

  });
// Remove function
  $("#wish_list_item").on("click", ".w-premove", function() {
    $office_id = $(this).attr("wpid");
    $("#list_id_" + $office_id).remove();
    wish_list = [];

    $("tr.wishlist-item").each(function(index, el) {
      wish_list.push(el.outerHTML);
    });
    //localStorage.setItem(wishlistkey, JSON.stringify(wish_list));

    show_message("Office removed");
    count_items_in_wishlist_update();

  });
});
//Animation
function show_message($msg) {
  $("#msg").html($msg);
  $top = Math.max(0, (($(window).height() - $("#msg").outerHeight()) / 2) + $(window).scrollTop()) + "px";
  $left = Math.max(0, (($(window).width() - $("#msg").outerWidth()) / 2) + $(window).scrollLeft()) + "px";
  $("#msg").css("left", $left);
  $("#msg").animate({
    opacity: 0.6,
    top: $top
  }, 400, function() {
    $(this).css({
      'opacity': 1
    });
  }).show();
  setTimeout(function() {
    $("#msg").animate({
      opacity: 0.6,
      top: "0px"
    }, 400, function() {
      $(this).hide();
    });
  }, 2000);
}

//Validation against the amount of product being added
function count_items_in_wishlist_update() {
  $("#listitem").html(wish_list.length);
  if (wish_list.length > 1) {
    $("#p_label").html("Shortlist (");
  } else {
    $("#p_label").html("Shortlist (");
  }
}
</code>```

Body:
I've made a wishlist which works like it should do by adding the product to the wishlist when I press the heart button. However, I have a minor issue! When I add a product to the wishlist and then click on the heart button again, it adds the same product multiple times which is something I do not want. Can anyone help me find some code that only adds the product once so that if that product is already in the wishlist, it won't add it again. Your help would be greatly appreciated! Thanks.

var wishlistkey = "wishlist";
// try and fetch an existing wishlist from the localStorage.
var wish_list = []; // localStorage.getItem(wishlistkey)

if ($.isEmptyObject(wish_list)) { //nothing was saved previously
  wish_list = new Array()
} else {
  wish_list = JSON.parse(wish_list);
  count_items_in_wishlist_update();
  $('#wish_list_item').html(wish_list);
}

$(document).ready(function() {
  $(".wishlist").on("click", function() {
    $data = "";
    $office_id = $(this).attr("office_id");
    $office_name = $(this).attr("office_name");
    $office_str = "
" + $office_name + "	x
";
    //check if the element is in the array
    if ($.inArray($office_id, wish_list) == -1) {

      $("#wish_list_item").append($office_str);

      wish_list.push($office_str);
      //  localStorage.setItem(wishlistkey, JSON.stringify(wish_list))
      show_message($office_name + " Office Added");
    }
    count_items_in_wishlist_update();
  });

  //adding toggle functionality to the wishlist pannel
  $(".wish_list_heading").on("click", function() {
    if (!$(this).hasClass("up")) {
      $("#wish_list").css("height", "390px");
      $(this).addClass("up");
      $("#wish_list").css("overflow", "auto");
    } else {
      $("#wish_list").css("height", "35px");
      $(this).removeClass("up");
      $("#wish_list").css("overflow", "hidden");
    }

  });
  // Remove function
  $("#wish_list_item").on("click", ".w-premove", function() {
    $office_id = $(this).attr("wpid");
    $("#list_id_" + $office_id).remove();
    wish_list = [];

    $("tr.wishlist-item").each(function(index, el) {
      wish_list.push(el.outerHTML);
    });
    //localStorage.setItem(wishlistkey, JSON.stringify(wish_list));

    show_message("Office removed");
    count_items_in_wishlist_update();

  });
});
//Animation
function show_message($msg) {
  $("#msg").html($msg);
  $top = Math.max(0, (($(window).height() - $("#msg").outerHeight()) / 2) + $(window).scrollTop()) + "px";
  $left = Math.max(0, (($(window).width() - $("#msg").outerWidth()) / 2) + $(window).scrollLeft()) + "px";
  $("#msg").css("left", $left);
  $("#msg").animate({
    opacity: 0.6,
    top: $top
  }, 400, function() {
    $(this).css({
      'opacity': 1
    });
  }).show();
  setTimeout(function() {
    $("#msg").animate({
      opacity: 0.6,
      top: "0px"
    }, 400, function() {
      $(this).hide();
    });
  }, 2000);
}

//Validation against the amount of product being added
function count_items_in_wishlist_update() {
  $("#listitem").html(wish_list.length);
  if (wish_list.length > 1) {
    $("#p_label").html("Shortlist (");
  } else {
    $("#p_label").html("Shortlist (");
  }
}

button a {
  color: #fff !important;
}

button {
  font-family: 'open sans', sans-serif;
  font-size: 15px;
}

button {
  text-align: center;
  padding: 1px 7px;
  margin: 0 5px 0;
  border: 4px solid #000;
  background-color: #000;
  vertical-align: middle;
  cursor: pointer;
  white-space: nowrap;
  font-size: 35px;
  color: #fff;
}

#wish_list {
  position: fixed;
  bottom: 0px;
  right: 0px;
  height: 35px;
  width: 400px;
  background: #fff;
  border: 3px solid #22a7c5;
  z-index: 3;
}

#wish_list .wish_list_heading {
  margin: 0px 0px;
  text-align: center;
  color: #fff;
  height: 27px;
  background-color: #22a7c5;
  padding: 6px 3px;
  font-weight: bold;
  cursor: pointer;
  font-size: 18px;
}

#wish_list_item {
  width: 100%;
  text-align: center;
  border-spacing: 0px 4px;
  border-collapse: separate;
}

#msg {
  position: fixed;
  display: none;
  padding: 10px 25px;
  background: #22a7c5;
  border: 1px solid #22a7c5;
  font-size: 18px;
  width: 50%;
  text-align: center;
  font-weight: 700;
  color: #fff;
  z-index: 4;
}

.wishlist-item {
  padding: 10px 5px;
  background: #f1f1f1;
  color: #323470;
}

.w-premove {
  font-size: 20px;
  cursor: pointer;
  width: 7%;
  padding-bottom: 4px;
}

.w-pname {
  font-size: 16px;
  width: 93%;
  text-align: left;
  padding-left: 12px;
}

    Shortlist (
    0
    )

  <button class='wishlist' title="Add To Shortlist" office_name='Hampton Street' office_id='hamptonstreet'>
        ❤
      </button>

Body:
I have modified your code a little here is what you need to update:
(it checks for include method which returns in true or false based on wether the item is already in the array or not, if its not, it will add item, otherwise)

var wishlistkey = "wishlist";
// try and fetch an existing wishlist from the localStorage.
var wish_list = []; // localStorage.getItem(wishlistkey)

if ($.isEmptyObject(wish_list)) { //nothing was saved previously
  wish_list = new Array()
} else {
  wish_list = JSON.parse(wish_list);
  count_items_in_wishlist_update();
  $('#wish_list_item').html(wish_list);
}

$(document).ready(function() {
  $(".wishlist").on("click", function() {
    $data = "";
    $office_id = $(this).attr("office_id");
    $office_name = $(this).attr("office_name");
    $office_str = "<tr class='wishlist-item' id='list_id_" + $office_id + "'><td class='w-pname'>" + $office_name + "</td><td class='w-premove' wpid='" + $office_id + "'>x</td></tr>";
    //check if the element is in the array
    if ($.inArray($office_id, wish_list) == -1) {

  if(!wish_list.includes($office_str))
  {
        $("#wish_list_item").append($office_str);
        wish_list.push($office_str);
        //  localStorage.setItem(wishlistkey, JSON.stringify(wish_list))
       show_message($office_name + " Office Added");
  }
  else
  {
       var myIndex = wish_list.indexOf($office_str);
       if (myIndex!==-1)
       wish_list.splice(myIndex, 1);
       $("#wish_list_item").remove();
       show_message("Office removed");
       count_items_in_wishlist_update();
  }

}
    count_items_in_wishlist_update();
  });

  //adding toggle functionality to the wishlist pannel
  $(".wish_list_heading").on("click", function() {
    if (!$(this).hasClass("up")) {
      $("#wish_list").css("height", "390px");
      $(this).addClass("up");
      $("#wish_list").css("overflow", "auto");
    } else {
      $("#wish_list").css("height", "35px");
      $(this).removeClass("up");
      $("#wish_list").css("overflow", "hidden");
    }

  });
// Remove function
  $("#wish_list_item").on("click", ".w-premove", function() {
    $office_id = $(this).attr("wpid");
    $("#list_id_" + $office_id).remove();
    wish_list = [];

    $("tr.wishlist-item").each(function(index, el) {
      wish_list.push(el.outerHTML);
    });
    //localStorage.setItem(wishlistkey, JSON.stringify(wish_list));

    show_message("Office removed");
    count_items_in_wishlist_update();

  });
});
//Animation
function show_message($msg) {
  $("#msg").html($msg);
  $top = Math.max(0, (($(window).height() - $("#msg").outerHeight()) / 2) + $(window).scrollTop()) + "px";
  $left = Math.max(0, (($(window).width() - $("#msg").outerWidth()) / 2) + $(window).scrollLeft()) + "px";
  $("#msg").css("left", $left);
  $("#msg").animate({
    opacity: 0.6,
    top: $top
  }, 400, function() {
    $(this).css({
      'opacity': 1
    });
  }).show();
  setTimeout(function() {
    $("#msg").animate({
      opacity: 0.6,
      top: "0px"
    }, 400, function() {
      $(this).hide();
    });
  }, 2000);
}

//Validation against the amount of product being added
function count_items_in_wishlist_update() {
  $("#listitem").html(wish_list.length);
  if (wish_list.length > 1) {
    $("#p_label").html("Shortlist (");
  } else {
    $("#p_label").html("Shortlist (");
  }
}


问:
Angular Object Array Sorting
Trying to sort the array of object, the property of the object contains alphanumeric values,
Tried methods which didn't worked

test.sort((a,b)=> a.Code.localeCompare(b.Code));
test.sort((a,b)=> +a.Code- +b.Code);

let test = [{Code: '16', Color: "Red"},
      {Code: '54', Color: "Yellow"},
      {Code: '24', Color: "Yellow"},
      {Code: '1600', Color: "Blue"},
      {Code: '16a', Color: "Green"},
      {Code: '22', Color: "Yellow"},
      {Code: '23', Color: "Yellow"}];

 test.sort((a,b) =>  a.Code.localeCompare(b.Code));
 console.log(test);```
</div>
</div>
</p>
<p>getting output as</p>
```[{"Code": "16", "Color": "Red" },
{"Code": "1600","Color": "Blue"},
{"Code": "16a","Color": "Green"},
{"Code": "22","Color": "Yellow"},
{"Code": "23","Color": "Yellow"},
{"Code": "24","Color": "Yellow"},
{"Code": "54","Color": "Yellow"}]
```
<p>How I can get the Expected output as</p>
```[{"Code": "16", "Color": "Red" },
{"Code": "22","Color": "Yellow"},
{"Code": "23","Color": "Yellow"},
{"Code": "24","Color": "Yellow"},
{"Code": "54","Color": "Yellow"},
{"Code": "1600","Color": "Blue"},
{"Code": "16a","Color": "Green"}]
```

答:
Thanks Nina a slight modification done to the solution as typescript was restricting typecasting

let test = [{ Code: '16', Color: "Red" }, { Code: '54', Color: "Yellow" }, { Code: '24', Color: "Yellow" }, { Code: '1600', Color: "Blue" }, { Code: '16a', Color: "Green" }, { Code: '22', Color: "Yellow" }, { Code: '23', Color: "Yellow" }];

test.sort(({ Code: a }, { Code: b }) =>
    +isFinite(+b) - +isFinite(+a) ||
    +a - +b ||
    a.localeCompare(b)
);

console.log(test);```

Title: Angular Object Array Sorting

Body:
Trying to sort the array of object, the property of the object contains alphanumeric values,
Tried methods which didn't worked

test.sort((a,b)=> a.Code.localeCompare(b.Code));
test.sort((a,b)=> +a.Code- +b.Code);

let test = [{Code: '16', Color: "Red"},
      {Code: '54', Color: "Yellow"},
      {Code: '24', Color: "Yellow"},
      {Code: '1600', Color: "Blue"},
      {Code: '16a', Color: "Green"},
      {Code: '22', Color: "Yellow"},
      {Code: '23', Color: "Yellow"}];

 test.sort((a,b) =>  a.Code.localeCompare(b.Code));
 console.log(test);

getting output as

[{"Code": "16", "Color": "Red" },
{"Code": "1600","Color": "Blue"},
{"Code": "16a","Color": "Green"},
{"Code": "22","Color": "Yellow"},
{"Code": "23","Color": "Yellow"},
{"Code": "24","Color": "Yellow"},
{"Code": "54","Color": "Yellow"}]

How I can get the Expected output as

[{"Code": "16", "Color": "Red" },
{"Code": "22","Color": "Yellow"},
{"Code": "23","Color": "Yellow"},
{"Code": "24","Color": "Yellow"},
{"Code": "54","Color": "Yellow"},
{"Code": "1600","Color": "Blue"},
{"Code": "16a","Color": "Green"}]


问:
Error creating docker image: "/bin/sh: 1: -E: not found"
I try to build image from Dockerfile, but I receive this error:

```<code>/bin/sh: 1: -E: not found
The command '/bin/sh -c curl -sL https://deb.nodesource.com/setup_$NODE_VERSION.x | -E bash -' returned a non-zero code: 127.
</code>```

I get it because of the following line in the Dockerfile:

```<code>RUN  install curl -sL https://deb.nodesource.com/setup_$NODE_VERSION.x | -E bash -
</code>```

答:
I try to build image from Dockerfile, but I receive this error:

```<code>/bin/sh: 1: -E: not found
The command '/bin/sh -c curl -sL https://deb.nodesource.com/setup_$NODE_VERSION.x | -E bash -' returned a non-zero code: 127.
</code>```

As you can see in Dockerfile RUN as well as in above error

```<code>RUN  install curl -sL https://deb.nodesource.com/setup_$NODE_VERSION.x | -E bash -
</code>```

-E bash - has no meaning without sudo

Please correct to

```<code>RUN  curl -sL https://deb.nodesource.com/setup_$NODE_VERSION.x | bash -
</code>```

Since nowhere USER <user> is specified in your Dockerfile, during build default user will be root as your parent image is ubuntu.

Please note the default user in a Dockerfile is the user of the parent image, in your case its ubuntu:latest ( FROM ubuntu:latest AS deploy). There can be images which are non-root by default.

If you're installing on non-docker environment you can use curl -sL .... | sudo -E bash -

```<code>$ man sudo
   .....
-E, --preserve-env
    Indicates to the security policy that the user wishes to preserve their existing
    environment variables. The security policy may return
    an error if the user does not have permission to preserve the environment.
</code>```

Body:
I try to build image from Dockerfile, but I receive this error:

/bin/sh: 1: -E: not found
The command '/bin/sh -c curl -sL https://deb.nodesource.com/setup_$NODE_VERSION.x | -E bash -' returned a non-zero code: 127.

I get it because of the following line in the Dockerfile:

RUN  install curl -sL https://deb.nodesource.com/setup_$NODE_VERSION.x | -E bash -

Body:
I try to build image from Dockerfile, but I receive this error:

/bin/sh: 1: -E: not found
The command '/bin/sh -c curl -sL https://deb.nodesource.com/setup_$NODE_VERSION.x | -E bash -' returned a non-zero code: 127.

As you can see in Dockerfile RUN as well as in above error

RUN  install curl -sL https://deb.nodesource.com/setup_$NODE_VERSION.x | -E bash -

-E bash - has no meaning without sudo

Please correct to

RUN  curl -sL https://deb.nodesource.com/setup_$NODE_VERSION.x | bash -

Since nowhere USER <user> is specified in your Dockerfile, during build default user will be root as your parent image is ubuntu.

Please note the default user in a Dockerfile is the user of the parent image, in your case its ubuntu:latest ( FROM ubuntu:latest AS deploy). There can be images which are non-root by default.

If you're installing on non-docker environment you can use curl -sL .... | sudo -E bash -

$ man sudo
   .....
-E, --preserve-env
    Indicates to the security policy that the user wishes to preserve their existing
    environment variables. The security policy may return
    an error if the user does not have permission to preserve the environment.


问:
Visitor IP information - WP Google Maps Plugin
We understand that the WP Google Maps plugin does not directly share any information with Google, however, the plugin does make use of the Google Maps API and in doing so, for certain features such as Geolocation as an example, the Google Maps API requires a users IP information in order to make use of the Geolocation features.

Can someone let us know if Google shares the visitor information (particularly Visitor IP information)?

Here is our flow -

We are using market cluster in map

Map has been linked into custom post type “Case studies”

All the Post’s locations categorized under marker categories

We are using search by keywords and search filter by categories

Info window has been customized to display a few custom fields in the window

答:
From the terms of service.

4.4 Data Use, Protection, and Privacy.

4.4.1 Data Use and Retention. To provide the Services through the Customer Application(s), Google collects and receives data from Customer and End Users (and End Users’ End Users, if any), including search terms, IP addresses, and latitude/longitude coordinates. Customer acknowledges and agrees that Google and its Affiliates may use and retain this data to provide and improve Google products and services, subject to the Google Privacy Policy at https://www.google.com/policies/privacy/.

4.4.2 European Data Protection Terms. Google and Customer agree to the Google Maps Controller-Controller Data Protection Terms at https://cloud.google.com/maps-platform/terms/maps-controller-terms.
4.4.3 End User Requirements.

(a) End User Privacy.  Customer’s use of the Services in the Customer Application will comply with applicable privacy laws, including laws regarding Services that store and access Cookies on End Users’ devices.   Customer will comply with the then-current Consent Policy at https://www.google.com/about/company/user-consent-policy.html, if applicable.
(b) End User Personal Data. Through the normal functioning of the Google Maps Core Services, End Users provide personally identifiable information and Personal Data directly to Google, subject to the then-current Google Privacy Policy at https://www.google.com/policies/privacy/. (a) However, Customer will not provide to Google (i) any End User’s personally identifiable information; or (ii) any European End User’s Personal Data (where “European” means “European Economic Area, Switzerland, or the UK”).
(c) End User Location Privacy Requirements. To safeguard End Users’ location privacy, Customer will ensure that the Customer Application(s): (i) notify End Users in advance of (1) the type(s) of data that Customer intends to collect from the End Users or the End Users’ devices, and (2) the combination and use of End User's location with any other data provider's data; and (ii) will not obtain or cache any End User's location except with the End User's express, prior, revocable consent.


问:
Multinomial density function working with non-integer data?
Does anyone know why dmultinom function in R works with non-integers and what does it return in that case? See below:

```<code>> dmultinom(c(0.7,0.1,0.1,0.1) ,prob = c(0.25,0.25,0.25,0.25))
[1] 0.25

> dmultinom(c(0.25,0.25,0.25,0.25) ,prob = c(0.25,0.25,0.25,0.25))
[1] 1
</code>```

答:
This is the source code of dmultinom

function (x, size = NULL, prob, log = FALSE)
{
    K <- length(prob)
    if (length(x) != K)
        stop("x[] and prob[] must be equal length vectors.")
    if (any(!is.finite(prob)) || any(prob < 0) || (s <- sum(prob)) ==
        0)
        stop("probabilities must be finite, non-negative and not all 0")
    prob <- prob/s
    x <- as.integer(x + 0.5)
    if (any(x < 0))
        stop("'x' must be non-negative")
    N <- sum(x)
    if (is.null(size))
        size <- N
    else if (size != N)
        stop("size != sum(x), i.e. one is wrong")
    i0 <- prob == 0
    if (any(i0)) {
        if (any(x[i0] != 0))
            return(if (log) -Inf else 0)
        if (all(i0))
            return(if (log) 0 else 1)
        x <- x[!i0]
        prob <- prob[!i0]
    }
    r <- lgamma(size + 1) + sum(x * log(prob) - lgamma(x + 1))
    if (log)
        r
    else exp(r)
}
```
<p>As you can see, it rounds the <code>x</code> to the closest integer in <code>x <- as.integer(x + 0.5)</code>.
Therefore, in your case it is equivalent to:</p>
<pre class="lang-r prettyprint-override"><code>dmultinom(c(0,0,0,0) ,prob = c(0.25,0.25,0.25,0.25))

[1] 1
</code>```

Body:
Does anyone know why dmultinom function in R works with non-integers and what does it return in that case? See below:

> dmultinom(c(0.7,0.1,0.1,0.1) ,prob = c(0.25,0.25,0.25,0.25))
[1] 0.25

> dmultinom(c(0.25,0.25,0.25,0.25) ,prob = c(0.25,0.25,0.25,0.25))
[1] 1

Body:
This is the source code of dmultinom

function (x, size = NULL, prob, log = FALSE)
{
    K <- length(prob)
    if (length(x) != K)
        stop("x[] and prob[] must be equal length vectors.")
    if (any(!is.finite(prob)) || any(prob < 0) || (s <- sum(prob)) ==
        0)
        stop("probabilities must be finite, non-negative and not all 0")
    prob <- prob/s
    x <- as.integer(x + 0.5)
    if (any(x < 0))
        stop("'x' must be non-negative")
    N <- sum(x)
    if (is.null(size))
        size <- N
    else if (size != N)
        stop("size != sum(x), i.e. one is wrong")
    i0 <- prob == 0
    if (any(i0)) {
        if (any(x[i0] != 0))
            return(if (log) -Inf else 0)
        if (all(i0))
            return(if (log) 0 else 1)
        x <- x[!i0]
        prob <- prob[!i0]
    }
    r <- lgamma(size + 1) + sum(x * log(prob) - lgamma(x + 1))
    if (log)
        r
    else exp(r)
}

As you can see, it rounds the x to the closest integer in x <- as.integer(x + 0.5).
Therefore, in your case it is equivalent to:

dmultinom(c(0,0,0,0) ,prob = c(0.25,0.25,0.25,0.25))

[1] 1


问:
java 8 grouping a map of same key and value and make a key value pair
I have a method fetchConfigsCount() which returns List<Map<String, Object>>.

The result looks like:

{
    "web_id": "abc",
    "count": 1
},
{
    "web_id": "xyz",
    "count": 1
},
{
    "web_id": "pqr",
    "count": 1
}
```
<p>We have another method <code>fetchWebsitesCount()</code> which also returns a response in same format.</p>
<p><code>web_id</code> is the key and its value is owner name.
<code>count</code> is another key and its value is of type <code>int</code>.</p>
<pre class="lang-json prettyprint-override"><code>{
    "web_id": "abc",
    "count": 2
},
{
    "web_id": "xyz",
    "count": 3
},
{
    "web_id": "pqr",
    "count": 4
}
</code>```

We have a list of owners which is of type ArrayList<String>:

List<String> listOfOwners = ["abc","xyz","pqr"];
```
<p>I want to collect all these things and want to create a result like below:</p>
<pre class="lang-json prettyprint-override"><code>result:[
    {"owner": "abc",
    "ownerPresence":{
    "configCount":1,
    "websiteCount":2
    },
    {"owner": "xyz",
    "ownerPresence":{
    "configCount":1,
    "websiteCount":3
    },
    {"owner": "pqr",
    "ownerPresence":{
    "configCount":1,
    "websiteCount":4
    }]
</code>```

I am not sure how I can do this in Java 8.

答:
Remap the initial lists of maps into Map<String, Integer>:

static Map<String, Integer> convert(List<Map<String, Object>> list) {
    return list
        .stream()
        .collect(Collectors.toMap(
            m -> (String) m.get("web_id"),
            m -> (Integer) m.get("count")
        ));
}

List<Map<String, Object>> configs  = fetchConfigsCount();
List<Map<String, Object>> websites = fetchWebsitesCount();

Map<String, Integer> configMap  = convert(configs);
Map<String, Integer> websiteMap = convert(websites);
```
<ol start="2">
<li>Create a POJO to represent a list entry:</li>
</ol>
<pre class="lang-java prettyprint-override"><code>class Pojo {
    String owner;
    Map<String, Integer> ownerPresence;
    // boilerplate: constructor(s), getters/setters
}
</code>```

Stream the list of owners, and build a map:

List<String> listOfOwners = Arrays.asList("abc","xyz","pqr");

List<Pojo> result = listOfOwners
    .stream()
    .map(owner -> new Pojo(
        owner,
        Map.of(
            "configCount",  configMap.get(owner),
            "websiteCount", websiteMap.get(owner)
        )
    ))
    .collect(Collectors.toList());
```
<hr />
<p><strong>Update</strong></p>
<p>If there are other inputs, a wrapper map may be created to hold the converted maps by appropriate keys <code>"configCount", "websiteCount", "sourceCount"</code>, etc.:</p>
<pre class="lang-java prettyprint-override"><code>Map<String, Map<String, Integer>> bigMap = Map.of(
    "configCount",  convert(fetchConfigsCount()),
    "websiteCount", convert(fetchWebsitesCount()),
    "sourceCount",  convert(fetchSourcesCount())
);
</code>```

Then the map for Pojo may be created like this:

List<Pojo> result = listOfOwners
    .stream()
    .map(owner -> new Pojo(
        owner,
        bigMap.keySet()
            .stream() // Stream<String>
            .collect(Collectors.toMap(
                k -> k,
                k -> bigMap.get(k).get(owner)
            )) // Map<String, Integer>
    ))
    .collect(Collectors.toList());
```

Body:
I have a method fetchConfigsCount() which returns List<Map<String, Object>>.

The result looks like:

{
    "web_id": "abc",
    "count": 1
},
{
    "web_id": "xyz",
    "count": 1
},
{
    "web_id": "pqr",
    "count": 1
}

We have another method fetchWebsitesCount() which also returns a response in same format.

web_id is the key and its value is owner name.
count is another key and its value is of type int.

{
    "web_id": "abc",
    "count": 2
},
{
    "web_id": "xyz",
    "count": 3
},
{
    "web_id": "pqr",
    "count": 4
}

We have a list of owners which is of type ArrayList<String>:

List<String> listOfOwners = ["abc","xyz","pqr"];

I want to collect all these things and want to create a result like below:

result:[
    {"owner": "abc",
    "ownerPresence":{
    "configCount":1,
    "websiteCount":2
    },
    {"owner": "xyz",
    "ownerPresence":{
    "configCount":1,
    "websiteCount":3
    },
    {"owner": "pqr",
    "ownerPresence":{
    "configCount":1,
    "websiteCount":4
    }]

I am not sure how I can do this in Java 8.

Body:
Remap the initial lists of maps into Map<String, Integer>:

static Map<String, Integer> convert(List<Map<String, Object>> list) {
    return list
        .stream()
        .collect(Collectors.toMap(
            m -> (String) m.get("web_id"),
            m -> (Integer) m.get("count")
        ));
}

List<Map<String, Object>> configs  = fetchConfigsCount();
List<Map<String, Object>> websites = fetchWebsitesCount();

Map<String, Integer> configMap  = convert(configs);
Map<String, Integer> websiteMap = convert(websites);

Create a POJO to represent a list entry:

class Pojo {
    String owner;
    Map<String, Integer> ownerPresence;
    // boilerplate: constructor(s), getters/setters
}

Stream the list of owners, and build a map:

List<String> listOfOwners = Arrays.asList("abc","xyz","pqr");

List<Pojo> result = listOfOwners
    .stream()
    .map(owner -> new Pojo(
        owner,
        Map.of(
            "configCount",  configMap.get(owner),
            "websiteCount", websiteMap.get(owner)
        )
    ))
    .collect(Collectors.toList());

Update

If there are other inputs, a wrapper map may be created to hold the converted maps by appropriate keys "configCount", "websiteCount", "sourceCount", etc.:

Map<String, Map<String, Integer>> bigMap = Map.of(
    "configCount",  convert(fetchConfigsCount()),
    "websiteCount", convert(fetchWebsitesCount()),
    "sourceCount",  convert(fetchSourcesCount())
);

Then the map for Pojo may be created like this:

List<Pojo> result = listOfOwners
    .stream()
    .map(owner -> new Pojo(
        owner,
        bigMap.keySet()
            .stream() // Stream<String>
            .collect(Collectors.toMap(
                k -> k,
                k -> bigMap.get(k).get(owner)
            )) // Map<String, Integer>
    ))
    .collect(Collectors.toList());


问:
How to test Controller Actions for simple mistakes
When scaffolding controllers it will create tests for that model, do the test have the ability to check for runtime errors for the whole page including rendering the .erb

If so can tests scan for common typos in the .erb for example checkbox instead of check_box

Because silly typos take a stupid amounts of time to figure out because the code looks right.

It would be good if there was a plugin that would use a service to check if it's a common typo or gotcha.

答:
In general I test the controller in the controller tests and the views in the view tests.

In more detail, I will test that given the right input to the controller, it produces the right output. I usually mock out the model(s) involved and concentrate on what work matters inside the controller. In my view tests I simply validate that the things on the page look like what I want them to look. I also use Jasmine to test javascript when I have more complex interactions in that body of code.

I put a lot of stock in this separation of tests.

I use rspec for my model, view, controller, routing and request tests and I write failing tests and then implement the feature/method to make those tests go green. And also I run rake spec before checking in. This gives me good coverage on the type of things you're concerned about.

There is also a gem called autotest that will run a test each time you save them (or perhaps some other granularity). If your test is green it will run the entire suite. I don't use it because I don't like how aggressively it does this but I have friends that swear by it.


问:
converting long to wide with columns starting at zero
I have the following data

```<code>county<-c(a,a,a,b,b,c)
id<-c(1,2,3,4,5,6)
data<-data.frame(county,id)
</code>```

I need to convert from long to wide and get the following output

```<code>county<-c(a,b,c)
id__0<-c(1,4,6)
id__1<-c(2,5,##NA##)
id__2<-3,##NA##,##NA##)
data2<-data.frame(county,id__0,id__1,id__2)
</code>```

My main problem is not in converting from long to wide, but how to make the columns start with id__0.

答:
You could add an intermediate variable by grouping according to county and using mutate to build a sequence from 0 upwards for each county, then pivot_wider on that:

library(tidyr)
library(dplyr)

data %>%
  group_by(county) %>%
  mutate(id_count = seq(n()) - 1) %>%
  pivot_wider(county, names_from =id_count, values_from = id, names_prefix = "id_")
#> # A tibble: 3 x 4
#> # Groups:   county [3]
#>   county  id_0  id_1  id_2
#>   <chr>  <dbl> <dbl> <dbl>
#> 1 a          1     2     3
#> 2 b          4     5    NA
#> 3 c          6    NA    NA
```

Created on 2022-02-10 by the reprex package (v2.0.1)

Body:
I have the following data

county<-c(a,a,a,b,b,c)
id<-c(1,2,3,4,5,6)
data<-data.frame(county,id)

I need to convert from long to wide and get the following output

county<-c(a,b,c)
id__0<-c(1,4,6)
id__1<-c(2,5,##NA##)
id__2<-3,##NA##,##NA##)
data2<-data.frame(county,id__0,id__1,id__2)

My main problem is not in converting from long to wide, but how to make the columns start with id__0.

Body:
You could add an intermediate variable by grouping according to county and using mutate to build a sequence from 0 upwards for each county, then pivot_wider on that:

library(tidyr)
library(dplyr)

data %>%
  group_by(county) %>%
  mutate(id_count = seq(n()) - 1) %>%
  pivot_wider(county, names_from =id_count, values_from = id, names_prefix = "id_")
#> # A tibble: 3 x 4
#> # Groups:   county [3]
#>   county  id_0  id_1  id_2
#>   <chr>  <dbl> <dbl> <dbl>
#> 1 a          1     2     3
#> 2 b          4     5    NA
#> 3 c          6    NA    NA

Created on 2022-02-10 by the reprex package (v2.0.1)


问:
LinkedIn Lead Gen webhook into Pardot with Google Analytics parameters
I have a webhook from my Lead Gen forms in LinkedIn to Pardot via Zapier but I can't get the Google Analytics UTM parameters to feed into my Pardot prospect information. Has anyone had success?</p>

答:
Instead of using webhooks try using a Pardot Form Handler.  Using Pardot Forms or Form Handlers you can capture UTM parameters.

Zapier doesn't always play nice with dynamic variables, so if you're deadset on using webhooks, make sure the data is actually posting to Zapier.