问:
Private repository passing through kubernetes yaml file
We have tried to setup hivemq manifest file. We have hivemq docker image in our private repository

Step1: I have logged into the private repository like

```<code> docker login "private repo name"
</code>```

It was success

After that I have tried to create manifest file for that like below

apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: hivemq
spec:
  replicas: 1
  template:
    metadata:
      labels:
        name: hivemq1
    spec:
      containers:
      - env:
        xxxxx some envronment values I have passed
        name: hivemq
        image: privatereponame:portnumber/directoryname/hivemq:
        ports:
        - containerPort: 1883

Its successfully creating, but I am getting the below issues. Could you please help any one to solve this issue.

hivemq-4236597916-mkxr4                    0/1       ImagePullBackOff   0          1h

Logs:

Error from server (BadRequest): container "hivemq16" in pod "hivemq16-1341290525-qtkhb" is waiting to start: InvalidImageName

Some times I am getting that kind of issues

Error from server (BadRequest): container "hivemq" in pod "hivemq-4236597916-mkxr4" is waiting to start: trying and failing to pull image

答:
In order to use a private docker registry with Kubernetes it's not enough to docker login.

You need to add a Kubernetes docker-registry Secret with your credentials as described here: https://kubernetes.io/docs/tasks/configure-pod-container/pull-image-private-registry/. Also in that article is imagePullSecrets setting you have to add to your yaml deployment file, referencing that secret.

Body:
We have tried to setup hivemq manifest file. We have hivemq docker image in our private repository

Step1: I have logged into the private repository like

 docker login "private repo name"

It was success

After that I have tried to create manifest file for that like below

apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: hivemq
spec:
  replicas: 1
  template:
    metadata:
      labels:
        name: hivemq1
    spec:
      containers:
      - env:
        xxxxx some envronment values I have passed
        name: hivemq
        image: privatereponame:portnumber/directoryname/hivemq:
        ports:
        - containerPort: 1883

Its successfully creating, but I am getting the below issues. Could you please help any one to solve this issue.

hivemq-4236597916-mkxr4                    0/1       ImagePullBackOff   0          1h

Logs:

Error from server (BadRequest): container "hivemq16" in pod "hivemq16-1341290525-qtkhb" is waiting to start: InvalidImageName

Some times I am getting that kind of issues

Error from server (BadRequest): container "hivemq" in pod "hivemq-4236597916-mkxr4" is waiting to start: trying and failing to pull image


来源: stackexchange

问:
Organize list of object in java
I have a class

```<code>public class ProductStock {

   private Long id;
   private Integer quantity;

}
</code>```

and a list like

```<code>List<ProductStock> productStocks =
{
  ProductStock(1, 1),
  ProductStock(2, 1),
  ProductStock(3, 1),
  ProductStock(1, 1),
  ProductStock(4, 1),
  ProductStock(5, 1),
  ProductStock(2, 1)
}
</code>```

I want to group productStocks by id.
What is the best way to convert this list like bellow

```<code>productStocks =
{
  ProductStock(1, 2),
  ProductStock(2, 2),
  ProductStock(3, 1),
  ProductStock(4, 1),
  ProductStock(5, 1)
}
</code>```

答:
You can use a Map for aggregating all the ProductStock in one place. Then you can use the contents of this Map to create the new List of ProductStock that will have the aggregated data.

```<code>Map<Long, Long> productStockMap = productStocks.stream().collect(Collectors.groupingBy(ProductStock::getId, Collectors.counting()));
productStocks = new ArrayList<>();
for(Map.Entry<Long, Long> entry: productStockMap.entrySet()) {
    productStocks.add(new ProductStock(entry.getKey(), entry.getValue().intValue()));
}
</code>```

Result:

```<code>============Before============

ProductStock{id=1, quantity=1}
ProductStock{id=2, quantity=1}
ProductStock{id=3, quantity=1}
ProductStock{id=1, quantity=1}
ProductStock{id=4, quantity=1}
ProductStock{id=5, quantity=1}
ProductStock{id=2, quantity=1}

=============After============

ProductStock{id=1, quantity=2}
ProductStock{id=2, quantity=2}
ProductStock{id=3, quantity=1}
ProductStock{id=4, quantity=1}
ProductStock{id=5, quantity=1}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Organize list of object in java

Body:
I have a class

public class ProductStock {

   private Long id;
   private Integer quantity;

}

and a list like

List<ProductStock> productStocks =
{
  ProductStock(1, 1),
  ProductStock(2, 1),
  ProductStock(3, 1),
  ProductStock(1, 1),
  ProductStock(4, 1),
  ProductStock(5, 1),
  ProductStock(2, 1)
}

I want to group productStocks by id.
What is the best way to convert this list like bellow

productStocks =
{
  ProductStock(1, 2),
  ProductStock(2, 2),
  ProductStock(3, 1),
  ProductStock(4, 1),
  ProductStock(5, 1)
}

Body:
You can use a Map for aggregating all the ProductStock in one place. Then you can use the contents of this Map to create the new List of ProductStock that will have the aggregated data.

Map<Long, Long> productStockMap = productStocks.stream().collect(Collectors.groupingBy(ProductStock::getId, Collectors.counting()));
productStocks = new ArrayList<>();
for(Map.Entry<Long, Long> entry: productStockMap.entrySet()) {
    productStocks.add(new ProductStock(entry.getKey(), entry.getValue().intValue()));
}

Result:

============Before============

ProductStock{id=1, quantity=1}
ProductStock{id=2, quantity=1}
ProductStock{id=3, quantity=1}
ProductStock{id=1, quantity=1}
ProductStock{id=4, quantity=1}
ProductStock{id=5, quantity=1}
ProductStock{id=2, quantity=1}

=============After============

ProductStock{id=1, quantity=2}
ProductStock{id=2, quantity=2}
ProductStock{id=3, quantity=1}
ProductStock{id=4, quantity=1}
ProductStock{id=5, quantity=1}


问:
R: mix() in mixdist package returning error
I have installed the mixdist package in R to combine distributions. Specifically, I'm using the mix() function. See documentation.
Basically, I'm getting

    Error in nlm(mixlike, lmixdat = mixdat, lmixpar = fitpar, ldist = dist,  :
    missing value in parameter

I googled the error message, but no useful results popped up.

My first argument to mix() is a data frame called data.df. It is formatted exactly like the built-in data set pike65. I also did data.df <- as.mixdata(data.df).

My second argument has two rows. It is a data frame called datapar, formatted exactly like pikepar. My pi values are 0.5 and 0.5. My mu values are 250 and 463 (based on my data set). My sigma values are 0.5 and 1.

My call to mix() looks like:

fitdata <- mix(data.df, datapar, "norm", constr = mixconstr(consigma="CCV"), emsteps = 3, print.level = 2)

The printing shows that my pi values go from 0.5 to NaN after the first iteration, and that my gradient is becoming 0.

I would appreciate any help in sorting out this error.

Thanks,

n.i.

答:
In addition, you can get this message if you have missing data in your dataset.

From example set

```<code>data(pike65)
data(pikepar)
pike65$freq[10] <- NA
fitpike1 <- mix(pike65, pikepar, "lnorm", constr = mixconstr(consigma = "CCV"), emsteps = 3)
</code>```

Error in nlm(mixlike, lmixdat = mixdat, lmixpar = fitpar, ldist =
  dist,  :    missing value in parameter

Body:
In addition, you can get this message if you have missing data in your dataset.

From example set

data(pike65)
data(pikepar)
pike65$freq[10] <- NA
fitpike1 <- mix(pike65, pikepar, "lnorm", constr = mixconstr(consigma = "CCV"), emsteps = 3)

Error in nlm(mixlike, lmixdat = mixdat, lmixpar = fitpar, ldist =
  dist,  :    missing value in parameter


问:
How to get the highest key from dictionary (python)?
I'm new to Python and I am having a small problem I want to solve

```<code>a={"1" : 3, "2" : 3, "6":3}
</code>```

I have this dic and I would like to get the maximum key out of him
for example in the dictionary above I would like to get the key 6 as a value

答:
There are many ways, one way of doing it is:

```<code>greatest = max(int(k) for k in a)
</code>```

Or a human readable format, so you can understand the logic:

```<code>greatest = None
for k in a:
    k = int(k)
    if greatest == None:
        greatest = k
    if k > greatest:
        greatest = k
</code>```

Body:
I'm new to Python and I am having a small problem I want to solve

a={"1" : 3, "2" : 3, "6":3}

I have this dic and I would like to get the maximum key out of him
for example in the dictionary above I would like to get the key 6 as a value

Body:
There are many ways, one way of doing it is:

greatest = max(int(k) for k in a)

Or a human readable format, so you can understand the logic:

greatest = None
for k in a:
    k = int(k)
    if greatest == None:
        greatest = k
    if k > greatest:
        greatest = k


问:
Keras: batches not completed
This is code of Keras, python. When the code below is ran on Linux mint, all batches aren't completed. It is always stopped at 32nd batch like

```<code>1/100  .............. ETA 30:00 Loss ..
2/100 =........... ETA 29:59 Loss ..
3/100 ==......... ETA 29:58 Loss ..
.
.
.
32/100 ==....... ETA 25:00 Loss ..
</code>```

(Training stops for unknown reason)

But when this code is ran on Windows, this works as expected until 100th batch. What is causing this behavior?

from __future__ import print_function

import numpy as np
import keras
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D
from keras.layers import Activation, Dropout, Flatten, Dense
from keras.layers.noise import AlphaDropout
from keras.preprocessing.image import ImageDataGenerator
from keras.models import model_from_json
from keras.layers import Dense, Dropout, Activation
from keras.preprocessing.text import Tokenizer
import keras.backend.tensorflow_backend as KTF
import tensorflow as tf
import os.path

f_log = './log'
f_model = './model/dogvscat'
model_yaml = 'dogvscat_model.yaml'
model_filename = 'dogvscat_model.json'
weights_filename = 'dogvscat_model_weights.hdf5'

batch_size = 64
epochs = 15
nb_validation_samples = 100

print('Building model...')

if os.path.isfile(os.path.join(f_model,model_filename)):
    print('Saved parameters found. I will use this file...')
    json_string = open(os.path.join(f_model, model_filename)).read()
    model = model_from_json(json_string)
    model.summary()
    model.compile(loss='categorical_crossentropy',
                optimizer='adam',
                metrics=['accuracy'])
    model.load_weights(os.path.join(f_model,weights_filename))
else:
    print('Saved parameters Not found. Creating new model...')
    model = Sequential()
    model.add(Conv2D(32, (3, 3), input_shape=(128, 128, 3)))
    model.add(Activation('selu'))
    model.add(MaxPooling2D(pool_size=(2, 2)))

    model.add(Conv2D(64, (3, 3)))
    model.add(Activation('selu'))
    model.add(MaxPooling2D(pool_size=(2, 2)))

    model.add(Flatten())
    model.add(Dense(64, kernel_initializer='lecun_normal'))
    model.add(Activation('selu'))
    model.add(AlphaDropout(0.1))
    model.add(Dense(2))
    model.add(Activation('softmax'))

    model.summary()

    model.compile(loss='categorical_crossentropy',
                optimizer='adam',
                metrics=['accuracy'])

train_datagen = ImageDataGenerator(
    rescale=1.0 / 255,
    shear_range=0.2,
    zoom_range=0.2,
    horizontal_flip=True)

test_datagen = ImageDataGenerator(rescale=1.0 / 255)

train_generator = train_datagen.flow_from_directory(
    'data/train',
    target_size=(128, 128),
    batch_size=batch_size,
    class_mode='categorical',
    shuffle=True)

validation_generator = test_datagen.flow_from_directory(
    'data/validation',
    target_size=(128, 128),
    batch_size=batch_size,
    class_mode='categorical',
    shuffle=True)

tb_cb = keras.callbacks.TensorBoard(log_dir=f_log, histogram_freq=0)
cp_cb = keras.callbacks.ModelCheckpoint(filepath = os.path.join(f_model,weights_filename), monitor='val_loss', verbose=1, save_best_only=True, mode='auto')
cbks = [tb_cb, cp_cb]

history = model.fit_generator(
    train_generator,
    steps_per_epoch=nb_validation_samples,
    epochs=epochs,
    validation_data=validation_generator,
    validation_steps=nb_validation_samples,
    callbacks=cbks
    )

score = model.evaluate_generator(validation_generator, nb_validation_samples)

print('')
print('Test score:', score[0])
print('Test accuracy:', score[1])

json_string = model.to_json()
open(os.path.join(f_model,model_filename), 'w').write(json_string)
yaml_string = model.to_yaml()
open(os.path.join(f_model,model_yaml), 'w').write(yaml_string)
print('save weights')
model.save_weights(os.path.join(f_model,weights_filename))
```

答:
You have an error in your code, you should change your steps_per_epoch, validation_steps just like below.

history = model.fit_generator(
train_generator,
steps_per_epoch=np.ceil(nb_training_samples/batch_size),
epochs=epochs,
validation_data=validation_generator,
validation_steps=np.ceil(nb_validation_samples/batch_size),
callbacks=cbks
)
```

On every step your batch_size of samples is used so you need np.ceil(nb_training_samples/batch_size) steps for an epoch

Title: Keras: batches not completed

Body:
This is code of Keras, python. When the code below is ran on Linux mint, all batches aren't completed. It is always stopped at 32nd batch like

1/100  .............. ETA 30:00 Loss ..
2/100 =........... ETA 29:59 Loss ..
3/100 ==......... ETA 29:58 Loss ..
.
.
.
32/100 ==....... ETA 25:00 Loss ..

(Training stops for unknown reason)

But when this code is ran on Windows, this works as expected until 100th batch. What is causing this behavior?

from __future__ import print_function

import numpy as np
import keras
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D
from keras.layers import Activation, Dropout, Flatten, Dense
from keras.layers.noise import AlphaDropout
from keras.preprocessing.image import ImageDataGenerator
from keras.models import model_from_json
from keras.layers import Dense, Dropout, Activation
from keras.preprocessing.text import Tokenizer
import keras.backend.tensorflow_backend as KTF
import tensorflow as tf
import os.path

f_log = './log'
f_model = './model/dogvscat'
model_yaml = 'dogvscat_model.yaml'
model_filename = 'dogvscat_model.json'
weights_filename = 'dogvscat_model_weights.hdf5'

batch_size = 64
epochs = 15
nb_validation_samples = 100

print('Building model...')

if os.path.isfile(os.path.join(f_model,model_filename)):
    print('Saved parameters found. I will use this file...')
    json_string = open(os.path.join(f_model, model_filename)).read()
    model = model_from_json(json_string)
    model.summary()
    model.compile(loss='categorical_crossentropy',
                optimizer='adam',
                metrics=['accuracy'])
    model.load_weights(os.path.join(f_model,weights_filename))
else:
    print('Saved parameters Not found. Creating new model...')
    model = Sequential()
    model.add(Conv2D(32, (3, 3), input_shape=(128, 128, 3)))
    model.add(Activation('selu'))
    model.add(MaxPooling2D(pool_size=(2, 2)))

    model.add(Conv2D(64, (3, 3)))
    model.add(Activation('selu'))
    model.add(MaxPooling2D(pool_size=(2, 2)))

    model.add(Flatten())
    model.add(Dense(64, kernel_initializer='lecun_normal'))
    model.add(Activation('selu'))
    model.add(AlphaDropout(0.1))
    model.add(Dense(2))
    model.add(Activation('softmax'))

    model.summary()

    model.compile(loss='categorical_crossentropy',
                optimizer='adam',
                metrics=['accuracy'])

train_datagen = ImageDataGenerator(
    rescale=1.0 / 255,
    shear_range=0.2,
    zoom_range=0.2,
    horizontal_flip=True)

test_datagen = ImageDataGenerator(rescale=1.0 / 255)

train_generator = train_datagen.flow_from_directory(
    'data/train',
    target_size=(128, 128),
    batch_size=batch_size,
    class_mode='categorical',
    shuffle=True)

validation_generator = test_datagen.flow_from_directory(
    'data/validation',
    target_size=(128, 128),
    batch_size=batch_size,
    class_mode='categorical',
    shuffle=True)

tb_cb = keras.callbacks.TensorBoard(log_dir=f_log, histogram_freq=0)
cp_cb = keras.callbacks.ModelCheckpoint(filepath = os.path.join(f_model,weights_filename), monitor='val_loss', verbose=1, save_best_only=True, mode='auto')
cbks = [tb_cb, cp_cb]

history = model.fit_generator(
    train_generator,
    steps_per_epoch=nb_validation_samples,
    epochs=epochs,
    validation_data=validation_generator,
    validation_steps=nb_validation_samples,
    callbacks=cbks
    )

score = model.evaluate_generator(validation_generator, nb_validation_samples)

print('')
print('Test score:', score[0])
print('Test accuracy:', score[1])

json_string = model.to_json()
open(os.path.join(f_model,model_filename), 'w').write(json_string)
yaml_string = model.to_yaml()
open(os.path.join(f_model,model_yaml), 'w').write(yaml_string)
print('save weights')
model.save_weights(os.path.join(f_model,weights_filename))

Body:
You have an error in your code, you should change your steps_per_epoch, validation_steps just like below.

history = model.fit_generator(
train_generator,
steps_per_epoch=np.ceil(nb_training_samples/batch_size),
epochs=epochs,
validation_data=validation_generator,
validation_steps=np.ceil(nb_validation_samples/batch_size),
callbacks=cbks
)

On every step your batch_size of samples is used so you need np.ceil(nb_training_samples/batch_size) steps for an epoch


问:
I want the variable to be accessed from anywhere
Here i want to access the variable "finalPrice " in another function, how can i achive this?</p>

```<code>  function available(id){
    $.ajax({
        method:"GET",
    }).done(function(data){

     for(j=0; j<available_location.length; j++) {

            var finalPrice =available_location[j].price_details.final_price;
   };
});

function razorpay() {
    $.ajax({
        url : 'http://test4238.wickedride.com//api/cancelledEnquiries/add',
        type : 'GET',
        data : {

         },
        success: function(data){
              alert(finalPrice );
           }
    });
}
</code>```

答:
Just define it outside the function and remove var from before final price in available();. Now it can be accessed by both functions.

```<code> var finalPrice = 0;

 function available(id){
    $.ajax({
        method:"GET",
    }).done(function(data){

     for(j=0; j<available_location.length; j++) {

       finalPrice =available_location[j].price_details.final_price;
   };
});

function razorpay() {
    $.ajax({
        url : 'http://test4238.wickedride.com//api/cancelledEnquiries/add',
        type : 'GET',
        data : {

         },
        success: function(data){
              alert(finalPrice );
           }
    });
}
</code>```

Body:
Here i want to access the variable "finalPrice " in another function, how can i achive this?

  function available(id){
    $.ajax({
        method:"GET",
    }).done(function(data){

     for(j=0; j<available_location.length; j++) {

            var finalPrice =available_location[j].price_details.final_price;
   };
});

function razorpay() {
    $.ajax({
        url : 'http://test4238.wickedride.com//api/cancelledEnquiries/add',
        type : 'GET',
        data : {

         },
        success: function(data){
              alert(finalPrice );
           }
    });
}

Body:
Just define it outside the function and remove var from before final price in available();. Now it can be accessed by both functions.

 var finalPrice = 0;

 function available(id){
    $.ajax({
        method:"GET",
    }).done(function(data){

     for(j=0; j<available_location.length; j++) {

       finalPrice =available_location[j].price_details.final_price;
   };
});

function razorpay() {
    $.ajax({
        url : 'http://test4238.wickedride.com//api/cancelledEnquiries/add',
        type : 'GET',
        data : {

         },
        success: function(data){
              alert(finalPrice );
           }
    });
}


问:
Symfony Automatism in URL reWrite
The name of my web site is "vg"
The dev url is : "http://localhost/vg/web/app_dev.php/"
The prefix definition set in the vg\app\config\routig.yml is : "/gallery"

So the question is : how to add automatically the prefix (gallery) to the url given by a user or process if the url is just "http://localhost/vg/web/app_dev.php/"

(.../gallery/ is the equivalent of traditional index page.)

Thanks

答:
Ok I found. And I want sincerely to thak you.

In the vg\app\config\routing.yml file

```
    vg_paint:
        resource: '@VGpaintBundle/Resources/config/routing.yml'
        prefix:   /gallery

    root:
        path: /
        defaults:
            _controller: FrameworkBundle:Redirect:urlRedirect
            path: /gallery
            permanent: true
```

In the # src/VG/paintBundle/Resources/config/routing.yml file

```
    vg_paint_home:
        path: /
        defaults:
            _controller: VGpaintBundle:Paints:index
            page: 0
            requirements:
                page: \d*

    vg_paint_index:
        path: /{page}
        defaults:
            _controller: VGpaintBundle:Paints:index
            page: 0
            requirements:
                page: \d*

    vg_paint_view:
        path: /paints/{id}
        defaults:
            _controller: VGpaintBundle:Paints:view
            id: 0
            requirements:
                id: \d+
```

And now if I call http://localhost/vg/web/app_dev.php (with or without / at the end) the "gallery" word comes at the end of this URL
@+

Title: Symfony Automatism in URL reWrite

Body:
Ok I found. And I want sincerely to thak you.

In the vg\app\config\routing.yml file

    vg_paint:
        resource: '@VGpaintBundle/Resources/config/routing.yml'
        prefix:   /gallery

    root:
        path: /
        defaults:
            _controller: FrameworkBundle:Redirect:urlRedirect
            path: /gallery
            permanent: true

In the # src/VG/paintBundle/Resources/config/routing.yml file

    vg_paint_home:
        path: /
        defaults:
            _controller: VGpaintBundle:Paints:index
            page: 0
            requirements:
                page: \d*

    vg_paint_index:
        path: /{page}
        defaults:
            _controller: VGpaintBundle:Paints:index
            page: 0
            requirements:
                page: \d*

    vg_paint_view:
        path: /paints/{id}
        defaults:
            _controller: VGpaintBundle:Paints:view
            id: 0
            requirements:
                id: \d+

And now if I call http://localhost/vg/web/app_dev.php (with or without / at the end) the "gallery" word comes at the end of this URL
@+

ContentLicense: CC BY-SA 4.0


问:
Why is the email is not send in this code? Magento
I am trying to send a email for a user when he fill a form and click the submit.I have created a controller in Magento and included the following code

```<code>public function sendMailAction(){
    $html="put your html content hereblah blah";
    $mail = Mage::getModel('core/email');
    $mail->setToName('Your Name');
    $mail->setToEmail('sadeeenadeee@gmail.com');
    $mail->setBody('Mail Text / Mail Content');
    $mail->setSubject('Mail Subject');
    $mail->setFromEmail('Sender Mail Id');
    $mail->setFromName("Msg to Show on Subject");
    $mail->setType('html');// YOu can use Html or text as Mail format

    try {
        $mail->send();
        Mage::getSingleton('core/session')->addSuccess('Your request has been sent');
        $this->_redirect('');
    }
    catch (Exception $e) {
        Mage::getSingleton('core/session')->addError('Unable to send.');
        $this->_redirect('');
    }
    }
</code>```

This is the function I am planning to use to send the email.Above controller function is called for the click of the submit button.
Then I configured the outgoing SMTP email in Magento admin panel.

System > Configuration-> Mail Sending Settings

I followed the above path and added the HOST and PORT in the Mail Sending Settings and saved the config.HOST and PORT are obtained from the email service provider.But when a user fills the form and click the submit,rather than sending a email browser tries to launch a app saying that,

THIS LINK NEEDS TO BE OPEN WITH AN APPLICATION

Can someone help me please?
I AM WORKING ON A HOSTED SITE

答:
```<code>$emailTemplateVariables = array();
$EmailSenderName="Email Sender Name";
$EmailId="semder Email";
            $emailTemplateVariables['key1'] = "data1";
            $emailTemplateVariables['key2'] = "data2";

            /* sent mail to //recepient  */
            $recipientEmail="abcd@xyz.com";

            $sender = Array('name' => $EmailSenderName,
            'email' => $EmailId);
            $emailName = 'Email Name';
            $translate = Mage::getSingleton('core/translate');
            $emailTemplate  = Mage::getModel('core/email_template')
                        ->loadDefault('Any_email_template');

                $emailTemplate->setSenderName($EmailSenderName)
                ->setSenderEmail($EmailId)
                ->setTemplateSubject($emailName);
                $emailstatus=$emailTemplate->send($recipientEmail, $emailName, $emailTemplateVariables);

            $translate->setTranslateInline(true);
            if($emailstatus) {
//email send successfully

            }
            else {

            //something went wrong
            }
</code>```

Please confirm that any mails in que for that enter the terminal command
mailq

```<code> $emailTemplate  = Mage::getModel('core/email_template')->load(1);   //1 is Transactional Emails id
</code>```

if you want to try default the above

Body:
I am trying to send a email for a user when he fill a form and click the submit.I have created a controller in Magento and included the following code

public function sendMailAction(){
    $html="put your html content hereblah blah";
    $mail = Mage::getModel('core/email');
    $mail->setToName('Your Name');
    $mail->setToEmail('sadeeenadeee@gmail.com');
    $mail->setBody('Mail Text / Mail Content');
    $mail->setSubject('Mail Subject');
    $mail->setFromEmail('Sender Mail Id');
    $mail->setFromName("Msg to Show on Subject");
    $mail->setType('html');// YOu can use Html or text as Mail format

    try {
        $mail->send();
        Mage::getSingleton('core/session')->addSuccess('Your request has been sent');
        $this->_redirect('');
    }
    catch (Exception $e) {
        Mage::getSingleton('core/session')->addError('Unable to send.');
        $this->_redirect('');
    }
    }

This is the function I am planning to use to send the email.Above controller function is called for the click of the submit button.
Then I configured the outgoing SMTP email in Magento admin panel.

System > Configuration-> Mail Sending Settings

I followed the above path and added the HOST and PORT in the Mail Sending Settings and saved the config.HOST and PORT are obtained from the email service provider.But when a user fills the form and click the submit,rather than sending a email browser tries to launch a app saying that,

THIS LINK NEEDS TO BE OPEN WITH AN APPLICATION

Can someone help me please?
I AM WORKING ON A HOSTED SITE

Body:
$emailTemplateVariables = array();
$EmailSenderName="Email Sender Name";
$EmailId="semder Email";
            $emailTemplateVariables['key1'] = "data1";
            $emailTemplateVariables['key2'] = "data2";

            /* sent mail to //recepient  */
            $recipientEmail="abcd@xyz.com";

            $sender = Array('name' => $EmailSenderName,
            'email' => $EmailId);
            $emailName = 'Email Name';
            $translate = Mage::getSingleton('core/translate');
            $emailTemplate  = Mage::getModel('core/email_template')
                        ->loadDefault('Any_email_template');

                $emailTemplate->setSenderName($EmailSenderName)
                ->setSenderEmail($EmailId)
                ->setTemplateSubject($emailName);
                $emailstatus=$emailTemplate->send($recipientEmail, $emailName, $emailTemplateVariables);

            $translate->setTranslateInline(true);
            if($emailstatus) {
//email send successfully

            }
            else {

            //something went wrong
            }

Please confirm that any mails in que for that enter the terminal command
mailq

 $emailTemplate  = Mage::getModel('core/email_template')->load(1);   //1 is Transactional Emails id

if you want to try default the above


问:
AngularJs - work with service
I am very new to Angular. I have watched some tutorials and read some of the documentation and I start coding.

this is my code:

```<code>angular.module('CourseStoryApp').service("CourseStoryService", ['$http', '$routeParams', function ($http, $routeParams) {
    return $http({
        url: "CourseStoryWebService.asmx/Course",
        method: "GET",
        params: { eID: $routeParams.eid }
    }).then(function (response) {
        return response.data;
    });
}]);

angular.module('CourseStoryApp').controller('HeaderController', ['$scope', 'CourseStoryService', function ($scope, CourseStoryService) {
   CourseStoryService.then(function (data) {
     $scope.courseStory = data;
   });
}]);
</code>```

is this the correct way to create a service and call it on controller?

答:
If you're using the .then() method, you have to implement something called promise in your service.

If you're new to angular, I really suggest you to learn about Angular 2 or more. The first version encountered some problems

Title: AngularJs - work with service

Body:
I am very new to Angular. I have watched some tutorials and read some of the documentation and I start coding.

this is my code:

angular.module('CourseStoryApp').service("CourseStoryService", ['$http', '$routeParams', function ($http, $routeParams) {
    return $http({
        url: "CourseStoryWebService.asmx/Course",
        method: "GET",
        params: { eID: $routeParams.eid }
    }).then(function (response) {
        return response.data;
    });
}]);

angular.module('CourseStoryApp').controller('HeaderController', ['$scope', 'CourseStoryService', function ($scope, CourseStoryService) {
   CourseStoryService.then(function (data) {
     $scope.courseStory = data;
   });
}]);

is this the correct way to create a service and call it on controller?


答:
Your finalPrice is scoped only to the available function since that's where it's declared (var finalPrice). In Javascript, if you want a variable to be accessable from all script scopes, move it outside the function, to the beginning of the script:

```<code>var finalPrice;

function available(id) {
    $.ajax({
          method:"GET",
    }).done(function(data) {
       for(j = 0; j < available_location.length; j++) {
           finalPrice = available_location[j].price_details.final_price;
       };
});

function razorpay() {
    $.ajax({
        url: 'http://test4238.wickedride.com//api/cancelledEnquiries/add',
        type: 'GET',
        data: {
        },
        success: function(data){
           alert(finalPrice );
        }
    });
}
</code>```

Title: I want the variable to be accessed from anywhere

Body:
Your finalPrice is scoped only to the available function since that's where it's declared (var finalPrice). In Javascript, if you want a variable to be accessable from all script scopes, move it outside the function, to the beginning of the script:

var finalPrice;

function available(id) {
    $.ajax({
          method:"GET",
    }).done(function(data) {
       for(j = 0; j < available_location.length; j++) {
           finalPrice = available_location[j].price_details.final_price;
       };
});

function razorpay() {
    $.ajax({
        url: 'http://test4238.wickedride.com//api/cancelledEnquiries/add',
        type: 'GET',
        data: {
        },
        success: function(data){
           alert(finalPrice );
        }
    });
}


问:
Changing urls in visual composer's raw html block
Visual Composer saves the raw HTML block as a base64 encoded (and url encoded) string in the database. My site needs to go from http to https, and I would need to change asset URL's used in these raw HTML blocks to be served with https. Clearly the Wordpress search/replace tool won't work here.

Does anybody know a solution for this?

答:
place the below code in your theme's functions.php

```<code>add_filter('the_content', 'chnage_http_to_https', 10);
function chnage_http_to_https($content){
    return str_replace('http://example.com','https://example.com', $content);
}
</code>```

it will help you on front end.
chnage example.com to your site name

Body:
place the below code in your theme's functions.php

add_filter('the_content', 'chnage_http_to_https', 10);
function chnage_http_to_https($content){
    return str_replace('http://example.com','https://example.com', $content);
}

it will help you on front end.
chnage example.com to your site name


问:
Python Input function not working in IDE 2.7
I have a basic query... The below mentioned program is not running in IDE Python 2.7 Version.
Also please help me to understand what is myName here. Is it a kind of variable? Once i enter the input value its not moving to next statement How are you. Can anyone help me to come out of this basic stuff?</p>

```<code>print('Hello world!')
print('What is your name?')
myName = input()
print('How are you, ' + myName)
</code>```

答:
For inputs in Python 2.7 use this:

```<code>myName = raw_input("Enter code here: ")
</code>```

In Python 3.0 use this:

```<code>myName = input("Enter code here: ")
</code>```

'myName' is a variable that will hold what the user enters as a string. If you type in "Steve" it will hold that inside 'myName', so when you do something like this:

```<code>print("My name is, " + myName)
</code>```

It will print out the following:

```<code>My name is, Steve
</code>```

Body:
I have a basic query... The below mentioned program is not running in IDE Python 2.7 Version.
Also please help me to understand what is myName here. Is it a kind of variable? Once i enter the input value its not moving to next statement How are you. Can anyone help me to come out of this basic stuff?

print('Hello world!')
print('What is your name?')
myName = input()
print('How are you, ' + myName)

Body:
For inputs in Python 2.7 use this:

myName = raw_input("Enter code here: ")

In Python 3.0 use this:

myName = input("Enter code here: ")

'myName' is a variable that will hold what the user enters as a string. If you type in "Steve" it will hold that inside 'myName', so when you do something like this:

print("My name is, " + myName)

It will print out the following:

My name is, Steve


问:
weird behavior from $.ajax
when i run this code:

```<code>function SolveRecaptchaV2(APIKey, googleKey, pageUrl, proxy, proxyType){
        var requestUrl = "https://2captcha.com/in.php?key=" + APIKey + "&method=userrecaptcha&googlekey=" + googleKey + "&pageurl=" + pageUrl + "&proxy=" + proxy + "&proxytype=";

        switch (proxyType) {
            case 'HTTP':
            requestUrl = requestUrl + "HTTP";
            break;

            case 'HTTPS':
            requestUrl = requestUrl + "HTTPS";
            break;

            case 'SOCKS4':
            requestUrl = requestUrl + "SOCKS4";
            break;

            case 'SOCKS5':
            requestUrl = requestUrl + "SOCKS5";
            break;
        }
        console.log('here'); //this gets shown in console
        $.ajax({url: requestUrl, success: function(result){
            if(result.length < 3){
                return false;
            }else{
                if(result.substring(0, 3) == "OK|"){
                    var captchaID = result.substring(3);

                    for(var i=0; i<24; i++){
                        var ansUrl = "https://2captcha.com/res.php?key=" + APIKey + "&action=get&id=" + captchaID;

                        var requests = $.ajax({url: ansUrl});
                        requests.done(function(ansresult){
                            console.log(ansresult); //This gets shown in console
                            if(ansresult.length < 3){
                                return ansresult;
                            }else{
                                if(ansresult.substring(0, 3) == "OK|"){
                                    return ansresult;
                                }else if (ansresult != "CAPCHA_NOT_READY"){
                                    return ansresult;
                                 }
                            }
                            //await sleep(1000);
                        });
                    }

                }else{

                    return 'not OK|';
                }
            }
        },
        fail: function(){
            return "fail";
            }
        });

    }
</code>```

When i run this code everything works fine and the code runs no problems, but when i make the callback function in $.ajax an async function, then $.ajax doesnt seem to run. Here is the code that doesnt run:

```<code>function SolveRecaptchaV2(APIKey, googleKey, pageUrl, proxy, proxyType){
        var requestUrl = "https://2captcha.com/in.php?key=" + APIKey + "&method=userrecaptcha&googlekey=" + googleKey + "&pageurl=" + pageUrl + "&proxy=" + proxy + "&proxytype=";

        switch (proxyType) {
            case 'HTTP':
            requestUrl = requestUrl + "HTTP";
            break;

            case 'HTTPS':
            requestUrl = requestUrl + "HTTPS";
            break;

            case 'SOCKS4':
            requestUrl = requestUrl + "SOCKS4";
            break;

            case 'SOCKS5':
            requestUrl = requestUrl + "SOCKS5";
            break;
        }
        console.log('here'); //This still shows in console.......
        $.ajax({url: requestUrl, success: function(result){
            if(result.length < 3){
                return false;
            }else{
                if(result.substring(0, 3) == "OK|"){
                    var captchaID = result.substring(3);

                    for(var i=0; i<24; i++){
                        var ansUrl = "https://2captcha.com/res.php?key=" + APIKey + "&action=get&id=" + captchaID;

                        var requests = $.ajax({url: ansUrl});
                        requests.done(async function(ansresult){
                            console.log(ansresult); //This does not show in console now.....
                            if(ansresult.length < 3){
                                return ansresult;
                            }else{
                                if(ansresult.substring(0, 3) == "OK|"){
                                    return ansresult;
                                }else if (ansresult != "CAPCHA_NOT_READY"){
                                    return ansresult;
                                 }
                            }
                            //await sleep(1000);
                        });
                    }

                }else{

                    return 'not OK|';
                }
            }
        },
        fail: function(){
            return "fail";
            }
        });

    }
</code>```

Notice the console.log before the first ajax call, and the console.log in the second ajax call. The console.log in the ajax call doesnt appear...

答:
Hooray, you've found a bug in jQuery. https://github.com/jquery/jquery/issues/3596

It ignores async functions passed as callbacks because it doesn't recognize them.

console.log(jQuery.isFunction(()=>{}))  // true
console.log(jQuery.isFunction(async ()=>{}))  // false

function deferred() {
  return $.ajax({url:"https://httpbin.org/ip"});  // returns a Deferred
}

async function native() {
  return $.ajax({url:"https://httpbin.org/ip"});  // returns a native promise
}

function demo() {
  deferred().then(async val=>console.log("doesn't work"));
  native().then(async val=>console.log('works'));
}
demo();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></code>```

Since you're writing a Chrome extension, you can definitely use all the JavaScript that it supports.

Write await $.ajax(…) (or use fetch) and don't worry about jQuery's callbacks.

As an example:

```<code>async function demo() {
  try {
    let result = await $.ajax({url:"https://httpbin.org/headers"});
    return result.headers['User-Agent'];
  } catch (err) {
    return 'fail';
  }
}
</code>```

Title: weird behavior from $.ajax

Body:
when i run this code:

function SolveRecaptchaV2(APIKey, googleKey, pageUrl, proxy, proxyType){
        var requestUrl = "https://2captcha.com/in.php?key=" + APIKey + "&method=userrecaptcha&googlekey=" + googleKey + "&pageurl=" + pageUrl + "&proxy=" + proxy + "&proxytype=";

        switch (proxyType) {
            case 'HTTP':
            requestUrl = requestUrl + "HTTP";
            break;

            case 'HTTPS':
            requestUrl = requestUrl + "HTTPS";
            break;

            case 'SOCKS4':
            requestUrl = requestUrl + "SOCKS4";
            break;

            case 'SOCKS5':
            requestUrl = requestUrl + "SOCKS5";
            break;
        }
        console.log('here'); //this gets shown in console
        $.ajax({url: requestUrl, success: function(result){
            if(result.length < 3){
                return false;
            }else{
                if(result.substring(0, 3) == "OK|"){
                    var captchaID = result.substring(3);

                    for(var i=0; i<24; i++){
                        var ansUrl = "https://2captcha.com/res.php?key=" + APIKey + "&action=get&id=" + captchaID;

                        var requests = $.ajax({url: ansUrl});
                        requests.done(function(ansresult){
                            console.log(ansresult); //This gets shown in console
                            if(ansresult.length < 3){
                                return ansresult;
                            }else{
                                if(ansresult.substring(0, 3) == "OK|"){
                                    return ansresult;
                                }else if (ansresult != "CAPCHA_NOT_READY"){
                                    return ansresult;
                                 }
                            }
                            //await sleep(1000);
                        });
                    }

                }else{

                    return 'not OK|';
                }
            }
        },
        fail: function(){
            return "fail";
            }
        });

    }

When i run this code everything works fine and the code runs no problems, but when i make the callback function in $.ajax an async function, then $.ajax doesnt seem to run. Here is the code that doesnt run:

function SolveRecaptchaV2(APIKey, googleKey, pageUrl, proxy, proxyType){
        var requestUrl = "https://2captcha.com/in.php?key=" + APIKey + "&method=userrecaptcha&googlekey=" + googleKey + "&pageurl=" + pageUrl + "&proxy=" + proxy + "&proxytype=";

        switch (proxyType) {
            case 'HTTP':
            requestUrl = requestUrl + "HTTP";
            break;

            case 'HTTPS':
            requestUrl = requestUrl + "HTTPS";
            break;

            case 'SOCKS4':
            requestUrl = requestUrl + "SOCKS4";
            break;

            case 'SOCKS5':
            requestUrl = requestUrl + "SOCKS5";
            break;
        }
        console.log('here'); //This still shows in console.......
        $.ajax({url: requestUrl, success: function(result){
            if(result.length < 3){
                return false;
            }else{
                if(result.substring(0, 3) == "OK|"){
                    var captchaID = result.substring(3);

                    for(var i=0; i<24; i++){
                        var ansUrl = "https://2captcha.com/res.php?key=" + APIKey + "&action=get&id=" + captchaID;

                        var requests = $.ajax({url: ansUrl});
                        requests.done(async function(ansresult){
                            console.log(ansresult); //This does not show in console now.....
                            if(ansresult.length < 3){
                                return ansresult;
                            }else{
                                if(ansresult.substring(0, 3) == "OK|"){
                                    return ansresult;
                                }else if (ansresult != "CAPCHA_NOT_READY"){
                                    return ansresult;
                                 }
                            }
                            //await sleep(1000);
                        });
                    }

                }else{

                    return 'not OK|';
                }
            }
        },
        fail: function(){
            return "fail";
            }
        });

    }

Notice the console.log before the first ajax call, and the console.log in the second ajax call. The console.log in the ajax call doesnt appear...

Body:
Hooray, you've found a bug in jQuery. https://github.com/jquery/jquery/issues/3596

It ignores async functions passed as callbacks because it doesn't recognize them.

console.log(jQuery.isFunction(()=>{}))  // true
console.log(jQuery.isFunction(async ()=>{}))  // false

function deferred() {
  return $.ajax({url:"https://httpbin.org/ip"});  // returns a Deferred
}

async function native() {
  return $.ajax({url:"https://httpbin.org/ip"});  // returns a native promise
}

function demo() {
  deferred().then(async val=>console.log("doesn't work"));
  native().then(async val=>console.log('works'));
}
demo();

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Since you're writing a Chrome extension, you can definitely use all the JavaScript that it supports.

Write await $.ajax(…) (or use fetch) and don't worry about jQuery's callbacks.

As an example:

async function demo() {
  try {
    let result = await $.ajax({url:"https://httpbin.org/headers"});
    return result.headers['User-Agent'];
  } catch (err) {
    return 'fail';
  }
}


问:
How to change EditText background color when I enter text?
My EditText has some color, but when I enter some text it should change. Say it's grey, I started to enter and it's yellow. This EditText is also focused, so when this activity starts -- I already can enter the text. How I tried:

```<code><style name="LoginEnterField">
    <item name="android:textColorHint">@color/black</item>
    <item name="android:textColor">@color/black</item>
    <item name="android:background">@drawable/selector_edittext</item>
    <item name="android:textSize">@dimen/general_text_size</item>
    <item name="android:paddingLeft">@dimen/activity_inner_horizontal_margin</item>
    <item name="android:paddingRight">@dimen/activity_inner_horizontal_margin</item>
</style>

<shape xmlns:android="http://schemas.android.com/apk/res/android"

    android:shape="rectangle">
    <solid android:color="@color/grey"/>
    <corners android:radius="5dp" />

</shape>

<shape xmlns:android="http://schemas.android.com/apk/res/android"

  android:shape="rectangle">
  <solid android:color="@color/yellow"/>
  <corners android:radius="5dp" />

</shape>

<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:state_focused="true" android:drawable="@drawable/roundbox_active_style"/>
  <item android:drawable="@drawable/roundbox_inactive_style" />
</selector>
</code>```

I think the point is in this selector. My EditText changes color, but it always yellow. How to make it became yellow only if I enter some text? I can't make any code changes! It's very important. I can't add or change only xml files.

EDIT: It's impossible to do from xml only, so make code changes.

答:
Use addTextChangedListener

```<code> public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (!editText.getText().toString().trim().isEmpty()) {
                    editText.setBackgroundColor(Your New Color);
                } else {
                    editText.setBackgroundColor(Your Old Color);
                }
            }
</code>```

Body:
My EditText has some color, but when I enter some text it should change. Say it's grey, I started to enter and it's yellow. This EditText is also focused, so when this activity starts -- I already can enter the text. How I tried:

<shape xmlns:android="http://schemas.android.com/apk/res/android"

    android:shape="rectangle">
    <solid android:color="@color/grey"/>
    <corners android:radius="5dp" />

</shape>

<shape xmlns:android="http://schemas.android.com/apk/res/android"

  android:shape="rectangle">
  <solid android:color="@color/yellow"/>
  <corners android:radius="5dp" />

</shape>

<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:state_focused="true" android:drawable="@drawable/roundbox_active_style"/>
  <item android:drawable="@drawable/roundbox_inactive_style" />
</selector>

I think the point is in this selector. My EditText changes color, but it always yellow. How to make it became yellow only if I enter some text? I can't make any code changes! It's very important. I can't add or change only xml files.

EDIT: It's impossible to do from xml only, so make code changes.

Body:
Use addTextChangedListener

 public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (!editText.getText().toString().trim().isEmpty()) {
                    editText.setBackgroundColor(Your New Color);
                } else {
                    editText.setBackgroundColor(Your Old Color);
                }
            }


问:
grep range of numbers
For the following text I need to count the lines that the number between parenthesis is in the range [10-20].

    This function's cyclomatic complexity is too high. (1)
    This function's cyclomatic complexity is too high. (2)
    This function's cyclomatic complexity is too high. (3)
    This function's cyclomatic complexity is too high. (4)
    This function's cyclomatic complexity is too high. (5)
    This function's cyclomatic complexity is too high. (6)
    This function's cyclomatic complexity is too high. (7)
    This function's cyclomatic complexity is too high. (8)
    This function's cyclomatic complexity is too high. (9)
    This function's cyclomatic complexity is too high. (10)
    This function's cyclomatic complexity is too high. (12)
    This function's cyclomatic complexity is too high. (13)
    This function's cyclomatic complexity is too high. (14)
    This function's cyclomatic complexity is too high. (15)
    This function's cyclomatic complexity is too high. (16)
    This function's cyclomatic complexity is too high. (17)
```

<p>Im trying the following commands:</p>

```cat log.txt | grep -c "This function's cyclomatic complexity is too high. ([10-20])"
cat log.txt | grep -c "This function's cyclomatic complexity is too high. ([10,11,12,13,14,15,16,17,18,20])"
```

But didnt work. Whats the correct way to do it?

答:
grep is the wrong tool.  You don't want to be using a regex to do numerical comparison.  Try:

```<code>awk "/This function's cyclomatic complexity is too high./"'$2 >= 10 && $2 <=20 {c++} END {print c}' FS='[()]' pruebascript.txt
</code>```

Note that you probably can simplify to:

```<code>awk '$2 >= 10 && $2 <=20 {c++} END {print c}' FS='[()]' pruebascript.txt
</code>```

depending on your actual data.

Title: grep range of numbers

Body:
For the following text I need to count the lines that the number between parenthesis is in the range [10-20].

    This function's cyclomatic complexity is too high. (1)
    This function's cyclomatic complexity is too high. (2)
    This function's cyclomatic complexity is too high. (3)
    This function's cyclomatic complexity is too high. (4)
    This function's cyclomatic complexity is too high. (5)
    This function's cyclomatic complexity is too high. (6)
    This function's cyclomatic complexity is too high. (7)
    This function's cyclomatic complexity is too high. (8)
    This function's cyclomatic complexity is too high. (9)
    This function's cyclomatic complexity is too high. (10)
    This function's cyclomatic complexity is too high. (12)
    This function's cyclomatic complexity is too high. (13)
    This function's cyclomatic complexity is too high. (14)
    This function's cyclomatic complexity is too high. (15)
    This function's cyclomatic complexity is too high. (16)
    This function's cyclomatic complexity is too high. (17)

Im trying the following commands:

cat log.txt | grep -c "This function's cyclomatic complexity is too high. ([10-20])"
cat log.txt | grep -c "This function's cyclomatic complexity is too high. ([10,11,12,13,14,15,16,17,18,20])"

But didnt work. Whats the correct way to do it?

Body:
grep is the wrong tool.  You don't want to be using a regex to do numerical comparison.  Try:

awk "/This function's cyclomatic complexity is too high./"'$2 >= 10 && $2 <=20 {c++} END {print c}' FS='[()]' pruebascript.txt

Note that you probably can simplify to:

awk '$2 >= 10 && $2 <=20 {c++} END {print c}' FS='[()]' pruebascript.txt

depending on your actual data.


问:
Error occurs when building .apk file with ionic
building the Android app produces the following error

Error: Source path does not exist:
  resources\android\icon\drawable-hdpi-icon.png

[ERROR] An error occurred while running cordova build android (exit
  code 1).

答:
What is your cordova and ionic-cli versions?

you can try

```<code>npm i -g ionic@latest
//or
ionic cordova resources -f //should recreate the necessary resources.
</code>```

```<code>and you are edit your config.xml files.
</code>```

so you can try ionic cordova platform add android

Again, what is your cordova and ionic-cli versions?

Body:
What is your cordova and ionic-cli versions?

you can try

npm i -g ionic@latest
//or
ionic cordova resources -f //should recreate the necessary resources.

and you are edit your config.xml files.

so you can try ionic cordova platform add android

Again, what is your cordova and ionic-cli versions?


问:
SQL group by with descending id order
I'm using Laravel for a radio website. Every song played is stored as a row in a table called last_played. We have a page called Top 20 which basically should display the Top 20 most played songs and when they were last played.

Table

```<code>+----+--------+-------------+
| id |  song  | time_played |
+----+--------+-------------+
|  1 | song_1 |  1510837544 |
|  2 | song_2 |  1510837545 |
|  3 | song_3 |  1510837546 |
|  4 | song_2 |  1510837547 |
|  5 | song_1 |  1510837548 |
|  6 | song_2 |  1510837549 |
+----+--------+-------------+
</code>```

Expected result like this

```<code>+--------+-------------+-------+
|  song  | time_played | count |
+--------+-------------+-------+
| song_2 |  1510837549 |     3 |
| song_1 |  1510837548 |     2 |
| song_3 |  1510837546 |     1 |
+--------+-------------+-------+
</code>```

And the query we use is as following:

```<code>$top20 = DB::select(DB::raw('SELECT *,
  COUNT(*) AS count FROM last_played
   GROUP BY song ORDER BY COUNT(*) DESC LIMIT 20'));
</code>```

Everything goes well until we display the songs. They are displayed correctly by the number of times they have been played, but each song returned are the ones with the lowest ID. We want to group everything and get the count of the songs played the most, and return the last id of that song too.

A link to the top20 page is here, and as you can see "Sist spillt / last played" is showing the first time the song where played, not the last.

Anyone know how to solve this?

答:
This should work:</p>

```<code>SELECT song, COUNT(song) AS count, MAX(time_played) FROM last_played GROUP BY song ORDER BY COUNT(song) DESC LIMIT 0,20
</code>```

Title: SQL group by with descending id order

Body:
I'm using Laravel for a radio website. Every song played is stored as a row in a table called last_played. We have a page called Top 20 which basically should display the Top 20 most played songs and when they were last played.

Table

+----+--------+-------------+
| id |  song  | time_played |
+----+--------+-------------+
|  1 | song_1 |  1510837544 |
|  2 | song_2 |  1510837545 |
|  3 | song_3 |  1510837546 |
|  4 | song_2 |  1510837547 |
|  5 | song_1 |  1510837548 |
|  6 | song_2 |  1510837549 |
+----+--------+-------------+

Expected result like this

+--------+-------------+-------+
|  song  | time_played | count |
+--------+-------------+-------+
| song_2 |  1510837549 |     3 |
| song_1 |  1510837548 |     2 |
| song_3 |  1510837546 |     1 |
+--------+-------------+-------+

And the query we use is as following:

$top20 = DB::select(DB::raw('SELECT *,
  COUNT(*) AS count FROM last_played
   GROUP BY song ORDER BY COUNT(*) DESC LIMIT 20'));

Everything goes well until we display the songs. They are displayed correctly by the number of times they have been played, but each song returned are the ones with the lowest ID. We want to group everything and get the count of the songs played the most, and return the last id of that song too.

A link to the top20 page is here, and as you can see "Sist spillt / last played" is showing the first time the song where played, not the last.

Anyone know how to solve this?

Body:
This should work:

SELECT song, COUNT(song) AS count, MAX(time_played) FROM last_played GROUP BY song ORDER BY COUNT(song) DESC LIMIT 0,20


问:
Conditional ftplugin settings in vim
I am trying to achieve different ts, sts, sw and (no)et settings depending on project.

My idea was to have an alias, kvim f.ex., looking like alias kvim="vim -u ~/.kvimrc" with ~/.kvimrc containing only:

```<code>let g:IsKernelCode="yes"
source ~/.vimrc
</code>```

And then in my ~/.vim/ftplugin/c/c.vim I could have sections like:

```<code>if exists("g:IsKernelCode")
     "kernel-code-settings
...
</code>```

This seams to work when I open a single file. But kvim -p a_bunch_of_files*.c will result in only the first file having my kernel-code-settings.

What am I missing?

答: What I ended up doing was alias kvim='vim --cmd '"'"'let g:IsKernelCode="yes"'"'", discarding my .kvimrc and keeping the .vim/ftplugin/c/c.vim as in my question.

Title: Conditional ftplugin settings in vim

Body:
I am trying to achieve different ts, sts, sw and (no)et settings depending on project.

My idea was to have an alias, kvim f.ex., looking like alias kvim="vim -u ~/.kvimrc" with ~/.kvimrc containing only:

let g:IsKernelCode="yes"
source ~/.vimrc

And then in my ~/.vim/ftplugin/c/c.vim I could have sections like:

if exists("g:IsKernelCode")
     "kernel-code-settings
...

This seams to work when I open a single file. But kvim -p a_bunch_of_files*.c will result in only the first file having my kernel-code-settings.

What am I missing?


问:
Is there a way to join the elements in an js array, but let the last separator be different?
What I want is something like Array.join(separator), but which takes a second argument Array.join(separator, beforeLastElement), so when I say [foo, bar, baz].join(", ", " or") I would get "foo, bar or baz". I guess I could write a function that used Array.slice to separate out the last element, but is there some well known method that I could use instead?

答:
there is a package join-array</p>

```<code>const join = require('join-array');
const names = ['Rachel','Taylor','Julia','Robert','Jasmine','Lily','Madison'];
const config = {
  array: names,
  separator: ', ',
  last: ' and ',
  max: 4,
  maxMessage:(missed)=>`(${missed} more...)`
};
const list = join(config); //Rachel, Taylor, Julia, (3 more...) and Madison
</code>```

Body:
there is a package join-array

const join = require('join-array');
const names = ['Rachel','Taylor','Julia','Robert','Jasmine','Lily','Madison'];
const config = {
  array: names,
  separator: ', ',
  last: ' and ',
  max: 4,
  maxMessage:(missed)=>`(${missed} more...)`
};
const list = join(config); //Rachel, Taylor, Julia, (3 more...) and Madison


问:
Expand Bootstrap datatable row and display subtable?
I want to expand my bootstrap datatable after click on icon. I can make it expandable and display another table there, but my button expands every row in table in the same time. I don't know how to send exactly this td which I clicked to my function.

This is how it looks:

Before expand: example

After click any of the '+' buttons it expands every row: example

Functions which expands and formats data for subtable:

```<code>function expandRow(list, td) {
    var tbl = $('#common_table').DataTable();
    var tr = $('.details-control').closest('tr');
    var row = tbl.row(tr);

    if (row.child.isShown()) {
        // This row is already open - close it
        row.child.hide();
        tr.removeClass('shown');
    } else {
        // Open this row
        row.child(format(list)).show();
        tr.addClass('shown');
    }
}

function format(operations) {
    var table = "<table id='common_table' class='table table-bordered'>";
    table+="<thead><tr class='table_nav tableHeads'><th class='tableHead'>OPERACJE</th><tr></thead>";
        // for(i=0; i<operations.length; i++){
             table +="<tbody><tr class='row_style'><td>sadasdasddsa</td></tr></tbody>";
             //   }

     table+="</table>";
    return table;
}
</code>```

And the way how I call this function:

```<code><table>...
<tbody>
    <tr class="row_style" th:each="qcOrder : ${qcOrdersList}">
        <td class="details-control" th:onclick="'javascript:expandRow(\''+ ${qcOperationsList} +'\', \'' + this + '\');'"></td>
...
</code>```

答:
Try this:

```<code><tr> <td id="XXXX" colspan=10 style='display:none'>
         <!-- SUB TABLE HERE -->
     </td>
</tr>
</code>```

and on JS call do simple:

findElementById("XXXX")  and change style for element from 'none' to ""

Body:
I want to expand my bootstrap datatable after click on icon. I can make it expandable and display another table there, but my button expands every row in table in the same time. I don't know how to send exactly this td which I clicked to my function.

This is how it looks:

Before expand: example

After click any of the '+' buttons it expands every row: example

Functions which expands and formats data for subtable:

function expandRow(list, td) {
    var tbl = $('#common_table').DataTable();
    var tr = $('.details-control').closest('tr');
    var row = tbl.row(tr);

    if (row.child.isShown()) {
        // This row is already open - close it
        row.child.hide();
        tr.removeClass('shown');
    } else {
        // Open this row
        row.child(format(list)).show();
        tr.addClass('shown');
    }
}

function format(operations) {
    var table = "
";
    table+="

OPERACJE

";
        // for(i=0; i<operations.length; i++){
             table +="

sadasdasddsa

";
             //   }

     table+="
";
    return table;
}

And the way how I call this function:

...

...

Body:
Try this:

<tr> <td id="XXXX" colspan=10 style='display:none'>
         <!-- SUB TABLE HERE -->
     </td>
</tr>

and on JS call do simple:

findElementById("XXXX")  and change style for element from 'none' to ""


问:
Why does "import PIL; PIL.Image" not work, but "from PIL import Image" does?
In a python interpreter:

```<code>>>> import PIL
>>> PIL.Image
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'Image'
>>> from PIL import Image
>>> PIL.Image
<module 'PIL.Image' from '/usr/lib/python2.7/site-packages/PIL/Image.pyc'>
</code>```

Why do I have to make the import as "from PIL import Image"? I'm interested in both "what is the underlying working in python imports that makes this behaviour possible?" and "Why was the PIL package designed to work like this?"

Also, I really like to keep a clean namespace when programming. If I want to use PIL.Image in my code, should I import like this:

```<code>>>> import PIL
>>> from PIL import Image
>>> del Image
</code>```

or is there a better way?

答:
PIL.Image is a submodule of PIL and so won't be automatically imported with,

```<code>import PIL
</code>```

since Python doesn't recursively import submodules.

5.4.2. Submodules in the Python Language Reference may help to understand the behaviour of importing submodules.

When a submodule is loaded using any mechanism, ... a binding is placed in the parent module’s namespace to the submodule object.

So although after importing and loading a submodule,

```<code>import PIL
from PIL import Image
</code>```

you are able to access it via PIL.Image, this does not mean PIL.Image is loaded when importing the PIL module.

Also, I couldn't find this explicitly stated anywhere but from what I've tested, it seems to be that when you import a submodule either like:

```<code>import package.submodule
</code>```

or:

```<code>from package import submodule
</code>```

The parent package is also loaded in the process.

Body:
In a python interpreter:

>>> import PIL
>>> PIL.Image
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'Image'
>>> from PIL import Image
>>> PIL.Image
<module 'PIL.Image' from '/usr/lib/python2.7/site-packages/PIL/Image.pyc'>

Why do I have to make the import as "from PIL import Image"? I'm interested in both "what is the underlying working in python imports that makes this behaviour possible?" and "Why was the PIL package designed to work like this?"

Also, I really like to keep a clean namespace when programming. If I want to use PIL.Image in my code, should I import like this:

>>> import PIL
>>> from PIL import Image
>>> del Image

or is there a better way?

Body:
PIL.Image is a submodule of PIL and so won't be automatically imported with,

import PIL

since Python doesn't recursively import submodules.

5.4.2. Submodules in the Python Language Reference may help to understand the behaviour of importing submodules.

When a submodule is loaded using any mechanism, ... a binding is placed in the parent module’s namespace to the submodule object.

So although after importing and loading a submodule,

import PIL
from PIL import Image

you are able to access it via PIL.Image, this does not mean PIL.Image is loaded when importing the PIL module.

Also, I couldn't find this explicitly stated anywhere but from what I've tested, it seems to be that when you import a submodule either like:

import package.submodule

or:

from package import submodule

The parent package is also loaded in the process.


问:
Using parameters throughout multiple subroutines python
I am currently trying to write a program where the user inputs what colour carpet they would like and then depending on what carpet and what area they have inputted it will give them a different price, However my current issue is using the parameters correctly since I am very new to both using python and to programming. The current program specification requires the use of subroutines. An example problem is with my last line main(exit1) where it says that exit1 isn't defined and if I try to edit the code to main() it says that exit1 is required. Any help will be greatly appreciated.</p>

```<code>def prices():
    PriceA = 40
    PriceB = 50
    PriceC = 60
def main(exit1):
    exit1 = False
    while exit1 == False:
        carpet = str(input("What carpet would you like blue, red or yellow "))
        carpet = carpet.upper()
        if carpet == "X":
            exit1 = True
        else:
            width = int(input("What is the width of the room in M^2 "))
            height = int(input("What is the height of the room in M^2 "))
            area = width * height

            if carpet == "BLUE":
                a(area)

            elif carpet == "RED":
                b(area)

            elif carpet == "YELLOW":
                c(area)

            else:
                print("Invalid carpet")
                cost = 0
                output(cost)

def output(cost, exit1):
print ("the price is £", cost)

def a(area, PriceA):
    cost = PriceA * area
    output(cost)

def b(area, PriceB):
    cost = PriceB * area
    output(cost)

def c(area, PriceC):
    cost = PriceC * area
    output(cost)

main(exit1)
</code>```

答:
You are trying to pass in a variable as an argument to the main function on the last line of your program, but you have not defined the exit1 variable before that line is executed (you define it within the scope of the main function). To achieve what you want to do you don't need to provide main with the exit1 argument, so you can just remove it from the function definition and the function call.

```<code>def main():
    ...

...

main()
</code>```

Body:
I am currently trying to write a program where the user inputs what colour carpet they would like and then depending on what carpet and what area they have inputted it will give them a different price, However my current issue is using the parameters correctly since I am very new to both using python and to programming. The current program specification requires the use of subroutines. An example problem is with my last line main(exit1) where it says that exit1 isn't defined and if I try to edit the code to main() it says that exit1 is required. Any help will be greatly appreciated.

def prices():
    PriceA = 40
    PriceB = 50
    PriceC = 60
def main(exit1):
    exit1 = False
    while exit1 == False:
        carpet = str(input("What carpet would you like blue, red or yellow "))
        carpet = carpet.upper()
        if carpet == "X":
            exit1 = True
        else:
            width = int(input("What is the width of the room in M^2 "))
            height = int(input("What is the height of the room in M^2 "))
            area = width * height

            if carpet == "BLUE":
                a(area)

            elif carpet == "RED":
                b(area)

            elif carpet == "YELLOW":
                c(area)

            else:
                print("Invalid carpet")
                cost = 0
                output(cost)

def output(cost, exit1):
print ("the price is £", cost)

def a(area, PriceA):
    cost = PriceA * area
    output(cost)

def b(area, PriceB):
    cost = PriceB * area
    output(cost)

def c(area, PriceC):
    cost = PriceC * area
    output(cost)

main(exit1)

Body:
You are trying to pass in a variable as an argument to the main function on the last line of your program, but you have not defined the exit1 variable before that line is executed (you define it within the scope of the main function). To achieve what you want to do you don't need to provide main with the exit1 argument, so you can just remove it from the function definition and the function call.

def main():
    ...

...

main()


问:
Chrome Extension: chrome.tabs.executeScript not working
I'm writing a chrome extension, and want to execute a content script from my background script. The background script executes, but the content doesn't. Here are the relevant chunks of code:

manifest.json:

```<code>"background": {
    "scripts": ["js/app/background.js"],
    "persistent": true
},

"permissions": [
    "identity",
    "tabs",
    "activeTab",
    "*://*/*"
]
</code>```

background.js:

```<code>console.log('background')
chrome.tabs.executeScript(null, {file: "content.js"})
</code>```

content.js:

```<code>console.log('content')
</code>```

When I inspect element, the console has background logged on it, but not content. The regular console also has nothing logged on it. What am I doing wrong?

答:
It must be as mentioned below:

```<code>chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
chrome.tabs.executeScript({
        code:"alert('Any Javascript code comes here !');"
    });
</code>```

});

Note: can execute in background script, Don't forgot to allow necessary permissions in manifest.json

Body:
I'm writing a chrome extension, and want to execute a content script from my background script. The background script executes, but the content doesn't. Here are the relevant chunks of code:

manifest.json:

"background": {
    "scripts": ["js/app/background.js"],
    "persistent": true
},

"permissions": [
    "identity",
    "tabs",
    "activeTab",
    "*://*/*"
]

background.js:

console.log('background')
chrome.tabs.executeScript(null, {file: "content.js"})

content.js:

console.log('content')

When I inspect element, the console has background logged on it, but not content. The regular console also has nothing logged on it. What am I doing wrong?

Body:
It must be as mentioned below:

chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
chrome.tabs.executeScript({
        code:"alert('Any Javascript code comes here !');"
    });

});

Note: can execute in background script, Don't forgot to allow necessary permissions in manifest.json


问:
problem signed char c++
This is the code:

```<code>int main()
{

 char c = 0x00;
 //c |= 0x0A;
 c |= 0xA0;

 while(c != 0x00)
 {
  cout << (c & 1) << endl;
  c = (c >> 1);
 }
}
</code>```

Why does this code work when I do or with 0X0A and not with 0xA0, as a number 0xA0 is to big to fit a signed char but why am I not allowed to set the bits for 0xA0?

When I print the loop it never breaks and it only print ones? How come?

答:
It is because of the sign extension of when performing a right shift.

```<code>0xA0 <=>        10100000 binary (and is a negative number because the MSB is set to 1)
(0xA0 >> 1) <=> 11010000
</code>```

replace char c by unsigned char c
or mask the MSB after the shift.

```<code>int main()
{

 char c = 0x00;
 //c |= 0x0A;
 c |= 0xA0;

 while(c != 0x00)
 {
  cout << (c & 1) << endl;
  c = (c >> 1) & 0x7f;
 }
}
</code>```

Note that char is usually a signed (range -128..127) but some c/C++ compiler define char as unsigned (AIX xlC compiler is known case).

ContentLicense: CC BY-SA 2.5

Title: problem signed char c++

Body:
This is the code:

int main()
{

 char c = 0x00;
 //c |= 0x0A;
 c |= 0xA0;

 while(c != 0x00)
 {
  cout << (c & 1) << endl;
  c = (c >> 1);
 }
}

Why does this code work when I do or with 0X0A and not with 0xA0, as a number 0xA0 is to big to fit a signed char but why am I not allowed to set the bits for 0xA0?

When I print the loop it never breaks and it only print ones? How come?

Body:
It is because of the sign extension of when performing a right shift.

0xA0 <=>        10100000 binary (and is a negative number because the MSB is set to 1)
(0xA0 >> 1) <=> 11010000

replace char c by unsigned char c
or mask the MSB after the shift.

int main()
{

 char c = 0x00;
 //c |= 0x0A;
 c |= 0xA0;

 while(c != 0x00)
 {
  cout << (c & 1) << endl;
  c = (c >> 1) & 0x7f;
 }
}

Note that char is usually a signed (range -128..127) but some c/C++ compiler define char as unsigned (AIX xlC compiler is known case).


问:
How to return string array?

Design a copy machine template: CopyMachine.java with

Public static variable int totalNoOfCopy, which records the total number of copies made from all the copy machines

method with signature:
public String[] copy(String strText, int intNos), which will update totalNoOfCopy value and return a String array with all its element value being strText and array size being intNos.

Design a program UseCopyMachine.java:

Create object canon and fujistu from CopyMachine.javab

Copy 6  "Flying!" on canon machine and  copy 8 "High!" on fujitsu machine

Show all the copies’ content from the 2 copy machines to user and print out the total number of copies from the 2 copy machines.

Totally new to java and here is my progress, some advice what to do next?

```<code>public class CopyMachine {

    static int totalNoOfCopy;

    public String[] copy(String strText, int intNos)
    {
        String[] ac= new String[intNos];
        totalNoOfCopy += intNos;
        return ac;
    }
}

public class UseCopyMachine {
    CopyMachine canon = new CopyMachine();
    CopyMachine fujitsu = new CopyMachine();
 }
</code>```

答:
From my understanding I think you need something like,

You have to iterate over the array using loop to insert and retrieve the elements.

```<code>public class CopyMachine {

    public static int totalNoOfCopy;

    public String[] copy(String strText, int intNos) {
        String[] ac= new String[intNos];
        for (int i=0; i< intNos; i++) {
            ac[i] = strText;
        }
        totalNoOfCopy += intNos;
        return ac;
    }

    public static void main(String[] args) {
        CopyMachine canon = new CopyMachine();
        String[] canonCopys = canon.copy("Flying!", 6);
        CopyMachine fujitsu = new CopyMachine();
        String[] fujitsuCopys = fujitsu.copy("High!", 8);

        System.out.println("Copies from Canon");
        for(String str: canonCopys) {
            System.out.println(str);
        }

        System.out.println("Copies from fujitsu");
        for(String str: fujitsuCopys) {
            System.out.println(str);
        }

        System.out.println("Total copies:" + CopyMachine.totalNoOfCopy);
    }
}
</code>```

Prints,

```<code>Copies from Canon
Flying!
Flying!
Flying!
Flying!
Flying!
Flying!
Copies from fujitsu
High!
High!
High!
High!
High!
High!
High!
High!
Total copies:14
</code>```

Title: How to return string array?

Body:
Design a copy machine template: CopyMachine.java with

Public static variable int totalNoOfCopy, which records the total number of copies made from all the copy machines

method with signature:
public String[] copy(String strText, int intNos), which will update totalNoOfCopy value and return a String array with all its element value being strText and array size being intNos.

Design a program UseCopyMachine.java:

Create object canon and fujistu from CopyMachine.javab

Copy 6  "Flying!" on canon machine and  copy 8 "High!" on fujitsu machine

Show all the copies’ content from the 2 copy machines to user and print out the total number of copies from the 2 copy machines.

Totally new to java and here is my progress, some advice what to do next?

public class CopyMachine {

    static int totalNoOfCopy;

    public String[] copy(String strText, int intNos)
    {
        String[] ac= new String[intNos];
        totalNoOfCopy += intNos;
        return ac;
    }
}

public class UseCopyMachine {
    CopyMachine canon = new CopyMachine();
    CopyMachine fujitsu = new CopyMachine();
 }

Body:
From my understanding I think you need something like,

You have to iterate over the array using loop to insert and retrieve the elements.

public class CopyMachine {

    public static int totalNoOfCopy;

    public String[] copy(String strText, int intNos) {
        String[] ac= new String[intNos];
        for (int i=0; i< intNos; i++) {
            ac[i] = strText;
        }
        totalNoOfCopy += intNos;
        return ac;
    }

    public static void main(String[] args) {
        CopyMachine canon = new CopyMachine();
        String[] canonCopys = canon.copy("Flying!", 6);
        CopyMachine fujitsu = new CopyMachine();
        String[] fujitsuCopys = fujitsu.copy("High!", 8);

        System.out.println("Copies from Canon");
        for(String str: canonCopys) {
            System.out.println(str);
        }

        System.out.println("Copies from fujitsu");
        for(String str: fujitsuCopys) {
            System.out.println(str);
        }

        System.out.println("Total copies:" + CopyMachine.totalNoOfCopy);
    }
}

Prints,

Copies from Canon
Flying!
Flying!
Flying!
Flying!
Flying!
Flying!
Copies from fujitsu
High!
High!
High!
High!
High!
High!
High!
High!
Total copies:14


问:
Youtube / Google Style Carousel Slider
I would like to make a carousel slider similar to what you see on the new design for Youtube.com and pages like this: https://plus.google.com/discover/w29saB

Any recommendations on how to build this, or Jquery plugins that facilitate this.

I've tried itemSlide() but I don't know how to get the CSS so that it renders inside the container DIV properly.  Also Itemslide doesn't give the arrows to scroll to the next page.

Other carousel plugins I've looked at even with their responsive options, make you specify the number of items to fit on a page. I would like that to be determined by css.

Update I've gotten itemSlide() to render in the container div however I still need to be able to add the arrows so that it scrolls when clicked.  I figure getting the buttons to overlay is a matter of the right CSS.  Getting the scroll to work when clicked is likely something specific to the itemSlide api that I should be able to figure out once the arrows are overlaid properly.  itemSlide() as carousel slider library:  http://itemslide.github.io/

答:
Once you get the arrows overlaid you can use the disable_clicktoslide option of the library so that clicking on slides doesn't move to them.

To make the arrows work, call the functions next() and previous() on the carousel object.

Also you can use the function getActiveIndex() to detect where the user is on the carousel.

Good luck!

Title: Youtube / Google Style Carousel Slider


问:
How to initialize data in a Vue.js component from SQL query
I am writing a simple tag browser application using Electron, SQlite and Vue.js. On application startup, I need to populate a HTML table with all rows from an SQL table.

I'm having trouble initializing the data in my Vue component however. When I start the application, I see no results. However, once I refresh the window all the results are there and the table rows are successfully created.

What is the best way to get an async request (in this case an SQLite query) to initialize the data of a Vue.js component?

My attempt so far (irrelevant code removed)

model.js

```<code>module.exports.getAll = function(table, callback) {
    const sql = `SELECT * from ${table}`;

    dbConnect();
    db.all(sql, (err, rows) => {
        callback && callback(rows);
    });
   db.close();
}
</code>```

FileTable.vue

```<code><template>
...
            <tr v-for="file in listings">
                <td>{{ file.filename }}</td>
                <td>{{ file.type }}</td>
                <td>{{ file.size }}</td>
                <td>{{ file.path }}</td>
            </tr>
...
</template>

<script>
    import model from '../../model.js';

    export default {
        data() {
            return {
                listings: {}
            }
        },

        methods: {
            initListings: function() {
                model.getAll('files', rows => {this.listings = rows});
            }
        },

        created() {
            this.initListings();
        }
}
</script>
</code>```

答:
Maybe like this:</p>

```<code>module.exports.getAll = function (table) {
  return new Promise((resolve, reject) => {
    const sql = `SELECT * from ${table}`

    dbConnect();
    db.all(sql, (err, rows) => {
      db.close()
      err ? reject(err) : resolve(rows)
    })
  })
}

<template>
  ...
  <tr v-for="file in listings">
    <td>{{ file.filename }}</td>
    <td>{{ file.type }}</td>
    <td>{{ file.size }}</td>
    <td>{{ file.path }}</td>
  </tr>
  ...
</template>

<script>
  import model from '../../model.js'

  export default {
    data() {
      return {
        listings: []
      }
  },
  methods: {
    async initListings () {
      this.listings = await model.getAll('files')
    }
  },
  created() {
    this.initListings()
  }
</script>
</code>```

Body:
I am writing a simple tag browser application using Electron, SQlite and Vue.js. On application startup, I need to populate a HTML table with all rows from an SQL table.

I'm having trouble initializing the data in my Vue component however. When I start the application, I see no results. However, once I refresh the window all the results are there and the table rows are successfully created.

What is the best way to get an async request (in this case an SQLite query) to initialize the data of a Vue.js component?

My attempt so far (irrelevant code removed)

model.js

module.exports.getAll = function(table, callback) {
    const sql = `SELECT * from ${table}`;

    dbConnect();
    db.all(sql, (err, rows) => {
        callback && callback(rows);
    });
   db.close();
}

FileTable.vue

<template>
...

                {{ file.filename }}
                {{ file.type }}
                {{ file.size }}
                {{ file.path }}

...
</template>

Body:
Maybe like this:

module.exports.getAll = function (table) {
  return new Promise((resolve, reject) => {
    const sql = `SELECT * from ${table}`

    dbConnect();
    db.all(sql, (err, rows) => {
      db.close()
      err ? reject(err) : resolve(rows)
    })
  })
}

<template>
  ...
  <tr v-for="file in listings">
    <td>{{ file.filename }}</td>
    <td>{{ file.type }}</td>
    <td>{{ file.size }}</td>
    <td>{{ file.path }}</td>
  </tr>
  ...
</template>

<script>
  import model from '../../model.js'

  export default {
    data() {
      return {
        listings: []
      }
  },
  methods: {
    async initListings () {
      this.listings = await model.getAll('files')
    }
  },
  created() {
    this.initListings()
  }
</script>


问:
Swift's Decimal precision issue
According to the docs here, Swift 3/4 Decimal type is a representation in base 10 bridged to NSDecimalNumber. However I'm having precision issues that do not reproduce when using NSDecimalNumber.

```<code>let dec24 = Decimal(integerLiteral: 24)
let dec1 = Decimal(integerLiteral: 1)
let decResult = dec1/dec24*dec24
// prints 0.99999999999999999999999999999999999984

let dn24 = NSDecimalNumber(value: 24)
let dn1 = NSDecimalNumber(value: 1)
let dnResult = dn1.dividing(by: dn24).multiplying(by: dn24)
// prints 1
</code>```

Shouldn't the Decimal struct be accurate, or am I misunderstanding something?

答:
NSDecimalNumber  (and its overlay type Decimal) can represent

... any number that can be expressed as mantissa x 10^exponent where mantissa is a decimal integer up to 38 digits long, and exponent is an integer from –128 through 127.

So decimal fractions (with up to 38 decimal digits) can be represented
exactly, but not arbitrary numbers. In particular 1/24 = 0.416666666...
has infinitely many decimal digits (a repeating decimal) and cannot be
represented  exactly as a Decimal.

Also there is no precision difference between Decimal and NSDecimalNumber. That becomes apparent if we print the difference
between the actual result and the "theoretical result":

```<code>let dec24 = Decimal(integerLiteral: 24)
let dec1 = Decimal(integerLiteral: 1)
let decResult = dec1/dec24*dec24

print(decResult - dec1)
// -0.00000000000000000000000000000000000016

let dn24 = NSDecimalNumber(value: 24)
let dn1 = NSDecimalNumber(value: 1)
let dnResult = dn1.dividing(by: dn24).multiplying(by: dn24)

print(dnResult.subtracting(dn1))
// -0.00000000000000000000000000000000000016
</code>```

Title: Swift's Decimal precision issue

Body:
According to the docs here, Swift 3/4 Decimal type is a representation in base 10 bridged to NSDecimalNumber. However I'm having precision issues that do not reproduce when using NSDecimalNumber.

let dec24 = Decimal(integerLiteral: 24)
let dec1 = Decimal(integerLiteral: 1)
let decResult = dec1/dec24*dec24
// prints 0.99999999999999999999999999999999999984

let dn24 = NSDecimalNumber(value: 24)
let dn1 = NSDecimalNumber(value: 1)
let dnResult = dn1.dividing(by: dn24).multiplying(by: dn24)
// prints 1

Shouldn't the Decimal struct be accurate, or am I misunderstanding something?

Body:
NSDecimalNumber  (and its overlay type Decimal) can represent

... any number that can be expressed as mantissa x 10^exponent where mantissa is a decimal integer up to 38 digits long, and exponent is an integer from –128 through 127.

So decimal fractions (with up to 38 decimal digits) can be represented
exactly, but not arbitrary numbers. In particular 1/24 = 0.416666666...
has infinitely many decimal digits (a repeating decimal) and cannot be
represented  exactly as a Decimal.

Also there is no precision difference between Decimal and NSDecimalNumber. That becomes apparent if we print the difference
between the actual result and the "theoretical result":

let dec24 = Decimal(integerLiteral: 24)
let dec1 = Decimal(integerLiteral: 1)
let decResult = dec1/dec24*dec24

print(decResult - dec1)
// -0.00000000000000000000000000000000000016

let dn24 = NSDecimalNumber(value: 24)
let dn1 = NSDecimalNumber(value: 1)
let dnResult = dn1.dividing(by: dn24).multiplying(by: dn24)

print(dnResult.subtracting(dn1))
// -0.00000000000000000000000000000000000016


问:
Correct way to bind "this" in JavaScript event callbacks?
I created a class called SearchBox to handle search interaction (delayed trigger, search on enter key press, preventing searches while one is active, synchronizing results when a search completes and the text has changed, etc.).

All the class methods are prototype methods, meant to be accessed via this.  In the following code, assume p is the class's prototype.

```<code>p.registerListeners = function () {
    $(this.element).on('keypress', this.searchKeyPressed);
};

p.unregisterListeners = function () {
    $(this.element).off('keypress', this.searchKeyPressed);
};
</code>```

That doesn't work, because when the keypress event calls the searchKeyPressed handler, it doesn't do so in the context of this.  The only solution I can come up with is one that only modern browsers support, which is to bind the callback to this, which actually creates a new function.  Since it creates a new function, I have to cache it in order to remove it later, since I have to pass the same reference to off that I passed to on.

Is there a better way to do it than this, or is this ok?

```<code>var boundKeyPressed;

p.registerListeners = function () {
    boundKeyPressed = this.searchKeyPressed.bind(this);
    $(this.element).on('keypress', boundKeyPressed);
};

p.unregisterListeners = function () {
    $(this.element).off('keypress', boundKeyPressed);
};
</code>```

I thought that maybe jQuery.on would provide a way to do this event binding automatically, but instead it seems like it binds this to different things depending on how it's called.  For example, when using on('eventname',instance.func), this is the "currentTarget" (not necessarily "target" in bubbling terms), whereas when using on('eventname','selector',instance.func), this refers to the element matching the selector.  In either case, the func runs as though it has no relationship with instance.

答:
Add bind(this) in the constructor - so you dont create new function every time you call .bind. bind creates new function every time you call it, so if you attach it with this: $el.on("click", this.handler.bind(this)), you cannot detach it with $el.off("click", this.handler.bind(this)) because the handler is not the same. (this.handler.bind(this) !== this.handler.bind(this)) If you save that reference to that binded function (like in the constructor this.handler = this.handler.bind(this)), then you can $el.on("click", this.handler) and $el.off("click", this.handler), because the handler is the same.

With this method, you are essentially overwriting that function for that instance. It will no longer call function like on prototype, but function like on that instnce.

```<code>function MyObject($el) {
    this.testValue = "I am really this!";
    this.$el = $el;
    this.onClick = this.onClick.bind(this);
    this.render();
}
MyObject.prototype.onClick = function(evt) {
    console.log(this.testValue); // logs "I am really this!"
}
MyObject.prototype.render = function() {
    var $a = $("<a>", {"text": "Click on me!"}).appendTo($el.empty());
    $a.on("click", this.onClick);
}
</code>```

Body:
I created a class called SearchBox to handle search interaction (delayed trigger, search on enter key press, preventing searches while one is active, synchronizing results when a search completes and the text has changed, etc.).

All the class methods are prototype methods, meant to be accessed via this.  In the following code, assume p is the class's prototype.

p.registerListeners = function () {
    $(this.element).on('keypress', this.searchKeyPressed);
};

p.unregisterListeners = function () {
    $(this.element).off('keypress', this.searchKeyPressed);
};

That doesn't work, because when the keypress event calls the searchKeyPressed handler, it doesn't do so in the context of this.  The only solution I can come up with is one that only modern browsers support, which is to bind the callback to this, which actually creates a new function.  Since it creates a new function, I have to cache it in order to remove it later, since I have to pass the same reference to off that I passed to on.

Is there a better way to do it than this, or is this ok?

var boundKeyPressed;

p.registerListeners = function () {
    boundKeyPressed = this.searchKeyPressed.bind(this);
    $(this.element).on('keypress', boundKeyPressed);
};

p.unregisterListeners = function () {
    $(this.element).off('keypress', boundKeyPressed);
};

I thought that maybe jQuery.on would provide a way to do this event binding automatically, but instead it seems like it binds this to different things depending on how it's called.  For example, when using on('eventname',instance.func), this is the "currentTarget" (not necessarily "target" in bubbling terms), whereas when using on('eventname','selector',instance.func), this refers to the element matching the selector.  In either case, the func runs as though it has no relationship with instance.

Body:
Add bind(this) in the constructor - so you dont create new function every time you call .bind. bind creates new function every time you call it, so if you attach it with this: $el.on("click", this.handler.bind(this)), you cannot detach it with $el.off("click", this.handler.bind(this)) because the handler is not the same. (this.handler.bind(this) !== this.handler.bind(this)) If you save that reference to that binded function (like in the constructor this.handler = this.handler.bind(this)), then you can $el.on("click", this.handler) and $el.off("click", this.handler), because the handler is the same.

With this method, you are essentially overwriting that function for that instance. It will no longer call function like on prototype, but function like on that instnce.

function MyObject($el) {
    this.testValue = "I am really this!";
    this.$el = $el;
    this.onClick = this.onClick.bind(this);
    this.render();
}
MyObject.prototype.onClick = function(evt) {
    console.log(this.testValue); // logs "I am really this!"
}
MyObject.prototype.render = function() {
    var $a = $("<a>", {"text": "Click on me!"}).appendTo($el.empty());
    $a.on("click", this.onClick);
}


问:
Making inner html content jump down instead of outer one
I have days of the week, and timestamps which can be in any number

When timestamps number increases or we shrink the browser, the expected behavior is to make timestamps jump down like this

However, the behavior is like this

Here is my simplified HTML codes for one day; Monday

```<code><div class="form-group">
    <button class="btn btn-secondary days">
         Monday
         <span class="sprite-1-arrow-black-right"></span>
     </button>
     <div class="timestamps">
         <div class="timestamp">
             00:00 am - 00:00 pm
          </div>
          <div class="timestamp">
            00:00 am - 00:00 pm
           </div>
     </div>
 </div>
</code>```

in simplified css/sass

```<code>.days {
        display: inline-block;
}
.timestamps {
       display:inline-block;
}
.timestamp {
       display: inline-block;
}
</code>```

I think, there should be flex solution, but I don't know how!

答:
In this case, where you have an equal width on the left buttons, the old BFC trick using float/overflow: hidden, combined with inline-block will solve that.

For anyone who can't use Flexbox (to support older browsers), this one will help.

Fiddle demo

Stack snippet

.days {
  float: left;
  width: 80px;
  padding: 0 10px;
}
.timestamps {
  overflow: hidden;
  margin-left: 100px;
}
.timestamp {
  display: inline-block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="form-group">
  <button class="btn btn-secondary days">
    Monday
    <span class="sprite-1-arrow-black-right"></span>
  </button>
  <div class="timestamps">
    <div class="timestamp">00:00 am - 00:00 pm</div>
    <div class="timestamp">00:00 am - 00:00 pm</div>
  </div>
</div></code>```

Body:
I have days of the week, and timestamps which can be in any number

When timestamps number increases or we shrink the browser, the expected behavior is to make timestamps jump down like this

However, the behavior is like this

Here is my simplified HTML codes for one day; Monday

    <button class="btn btn-secondary days">
         Monday

     </button>

             00:00 am - 00:00 pm

            00:00 am - 00:00 pm

in simplified css/sass

.days {
        display: inline-block;
}
.timestamps {
       display:inline-block;
}
.timestamp {
       display: inline-block;
}

I think, there should be flex solution, but I don't know how!

Body:
In this case, where you have an equal width on the left buttons, the old BFC trick using float/overflow: hidden, combined with inline-block will solve that.

For anyone who can't use Flexbox (to support older browsers), this one will help.

Fiddle demo

Stack snippet

.days {
  float: left;
  width: 80px;
  padding: 0 10px;
}
.timestamps {
  overflow: hidden;
  margin-left: 100px;
}
.timestamp {
  display: inline-block;
}

<div class="form-group">
  <button class="btn btn-secondary days">
    Monday
    <span class="sprite-1-arrow-black-right"></span>
  </button>
  <div class="timestamps">
    <div class="timestamp">00:00 am - 00:00 pm</div>
    <div class="timestamp">00:00 am - 00:00 pm</div>
  </div>
</div>