问:
What is the relationship between bind and join?
I got the impression that (>>=) (used by Haskell) and join (preferred by mathematicians) are "equal" since one can write one in terms of the other:

```<code>import Control.Monad (join)

join x = x >>= id
x >>= f = join (fmap f x)
</code>```

Additionally every monad is a functor since bind can be used to replace fmap:

```<code>fmap f x = x >>= (return . f)
</code>```

I have the following questions:

Is there a (non-recursive) definition of fmap in terms of join? (fmap f x = join $ fmap (return . f) x follows from the equations above but is recursive.)

Is "every monad is a functor" a conclusion when using bind (in the definition of a monad), but an assumption when using join?

Is bind more "powerful" than join? And what would "more powerful" mean?

答:
Is there a [definition] of fmap in terms of join?

No, there isn't. That can be demonstrated by attempting to do it. Suppose we are given an arbitrary type constructor T, and functions:

```<code>returnT :: a -> T a
joinT :: T (T a) -> T a
</code>```

From this data alone, we want to define:

```<code>fmapT :: (a -> b) -> T a -> T b
</code>```

So let's sketch it:

```<code>fmapT :: (a -> b) -> T a -> T b
fmapT f ta = tb
    where
    tb = undefined  -- tb :: T b
</code>```

We need to get a value of type T b somehow. ta :: T a on its own won't do, so we need functions that produce T b values. The only two candidates are joinT and returnT. joinT doesn't help:

```<code>fmapT :: (a -> b) -> T a -> T b
fmapT f ta = joinT ttb
    where
    ttb = undefined  -- ttb :: T (T b)
</code>```

It just kicks the can down the road, as needing a T (T b) value under these circumstances is no improvement.

We might try returnT instead:

```<code>fmapT :: (a -> b) -> T a -> T b
fmapT f ta = returnT b
    where
    b = undefined  -- b :: b
</code>```

Now we need a b value. The only thing that can give us one is f:

```<code>fmapT :: (a -> b) -> T a -> T b
fmapT f ta = returnT (f a)
    where
    a = undefined  -- a :: a
</code>```

And now we are stuck: nothing can give us an a. We have exhausted all available possibilities, so fmapT cannot be defined in such terms.

A digression: it wouldn't suffice to cheat by using a function like this:

```<code>extractT :: T a -> a
</code>```

With an extractT, we might try a = extractT ta, leading to:

```<code>fmapT :: (a -> b) -> T a -> T b
fmapT f ta = returnT (f (extractT ta))
</code>```

It is not enough, however, for fmapT to have the right type: it must also follow the functor laws. In particular, fmapT id = id should hold. With this definition, fmapT id is returnT . extractT, which, in general, is not id (most functors which are instances of both Monad and Comonad serve as examples).

Is "every monad is a functor" a conclusion when using bind (in the definition of a monad), but an assumption when using join?

"Every monad is a functor" is an assumption, or, more precisely, part of the definition of monad. To pick an arbitrary illustration, here is Emily Riehl, Category Theory In Context, p. 154:

Definition 5.1.1. A monad on a category C consists of

an endofunctor T : C → C,

a unit natural transformation η : 1C ⇒ T, and

a multiplication natural transformation μ :T2 ⇒ T,

so that the following diagrams commute in CC: [diagrams of the monad laws]

A monad, therefore, involves an endofunctor by definition. For a Haskell type constructor T that instantiates Monad, the object mapping of that endofunctor is T itself, and the morphism mapping is its fmap. That T will be a Functor instance, and therefore will have an fmap, is, in contemporary Haskell, guaranteed by Applicative (and, by extension, Functor) being a superclass of Monad.

Is that the whole story, though? As far as Haskell is concerned. we know that liftM exists, and also that in a not-so-distant past Functor was not a superclass of Monad. Are those two facts mere Haskellisms? Not quite. In the classic paper Notions of computation and monads, Eugenio Moggi unearths the following definition (p. 3):

Definition 1.2 ([Man76]) A Kleisli triple over a category C is a triple (T, η, _*), where T : Obj(C) → Obj(C), ηA : A → T A for A ∈ Obj(C), f* : T A → T B for f : A → T B and the following equations hold:

ηA* = idT A

ηA; f* = f   for     f : A → T B

f*; g* = (f; g*)*   for   f : A → T B   and   g : B → T C

The important detail here is that T is presented as merely an object mapping in the category C, and not as an endofunctor in C. Working in the Hask category, that amounts to taking a type constructor T without presupposing it is a Functor instance. In code, we might write that as:

```<code>class KleisliTriple t where
    return :: a -> t a
    (=<<) :: (a -> t b) -> t a -> t b

-- (return =<<) = id
-- (f =<<) . return = f
-- (g =<<) . (f =<<) = ((g =<<) . f =<<)
</code>```

Flipped bind aside, that is the pre-AMP definition of Monad in Haskell. Unsurprisingly, Moggi's paper doesn't take long to show that "there is a one-to-one correspondence between Kleisli triples and monads" (p. 5), establishing along the way that T can be extended to an endofunctor (in Haskell, that step amounts to defining the morphism mapping liftM f m = return . f =<< m, and then showing it follows the functor laws).

All in all, if you write lawful definitions of return and (>>=) without presupposing fmap, you indeed get a lawful implementation of Functor as a consequence. "There is a one-to-one correspondence between Kleisli triples and monads" is a consequence of the definition of Kleisli triple, while "a monad involves an endofunctor" is part of the definition of monad. It is tempting to consider whether it would be more accurate to describe what Haskellers did when writing Monad instances as "setting up a Klesili triple" rather than "setting up a monad", but I will refrain out of fear of getting mired down terminological pedantry -- and in any case, now that Functor is a superclass of Monad there is no practical reason to worry about that.

Is bind more "powerful" than join? And what would "more powerful" mean?

Trick question!

Taken at face value, the answer would be yes, to the extent that, together with return, (>>=) makes it possible to implement fmap (via liftM, as noted above), while join doesn't. However, I don't feel it is worthwhile to insist on this distinction. Why so? Because of the monad laws. Just like it doesn't make sense to talk about a lawful (>>=) without presupposing return, it doesn't make sense to talk about a lawful join without pressuposing return and fmap.

One might get the impression that I am giving too much weight to the laws by using them to tie Monad and Functor in this way. It is true that there are cases of laws that involve two classes, and that only apply to types which instantiate them both. Foldable provides a good example of that: we can find the following law in the Traversable documentation:

The superclass instances should satisfy the following: [...]

In the Foldable instance, foldMap should be equivalent to traversal with a constant applicative functor (foldMapDefault).

That this specific law doesn't always apply is not a problem, because we don't need it to characterise what Foldable is (alternatives include "a Foldable is a container from which we can extract some sequence of elements", and "a Foldable is a container that can be converted to the free monoid on its element type"). With the monad laws, though, it isn't like that: the meaning of the class is inextricably bound to all three of the monad laws.

Body:
I got the impression that (>>=) (used by Haskell) and join (preferred by mathematicians) are "equal" since one can write one in terms of the other:

import Control.Monad (join)

join x = x >>= id
x >>= f = join (fmap f x)

Additionally every monad is a functor since bind can be used to replace fmap:

fmap f x = x >>= (return . f)

I have the following questions:

Is there a (non-recursive) definition of fmap in terms of join? (fmap f x = join $ fmap (return . f) x follows from the equations above but is recursive.)

Is "every monad is a functor" a conclusion when using bind (in the definition of a monad), but an assumption when using join?

Is bind more "powerful" than join? And what would "more powerful" mean?

Body:
Is there a [definition] of fmap in terms of join?

No, there isn't. That can be demonstrated by attempting to do it. Suppose we are given an arbitrary type constructor T, and functions:

returnT :: a -> T a
joinT :: T (T a) -> T a

From this data alone, we want to define:

fmapT :: (a -> b) -> T a -> T b

So let's sketch it:

fmapT :: (a -> b) -> T a -> T b
fmapT f ta = tb
    where
    tb = undefined  -- tb :: T b

We need to get a value of type T b somehow. ta :: T a on its own won't do, so we need functions that produce T b values. The only two candidates are joinT and returnT. joinT doesn't help:

fmapT :: (a -> b) -> T a -> T b
fmapT f ta = joinT ttb
    where
    ttb = undefined  -- ttb :: T (T b)

It just kicks the can down the road, as needing a T (T b) value under these circumstances is no improvement.

We might try returnT instead:

fmapT :: (a -> b) -> T a -> T b
fmapT f ta = returnT b
    where
    b = undefined  -- b :: b

Now we need a b value. The only thing that can give us one is f:

fmapT :: (a -> b) -> T a -> T b
fmapT f ta = returnT (f a)
    where
    a = undefined  -- a :: a

And now we are stuck: nothing can give us an a. We have exhausted all available possibilities, so fmapT cannot be defined in such terms.

A digression: it wouldn't suffice to cheat by using a function like this:

extractT :: T a -> a

With an extractT, we might try a = extractT ta, leading to:

fmapT :: (a -> b) -> T a -> T b
fmapT f ta = returnT (f (extractT ta))

It is not enough, however, for fmapT to have the right type: it must also follow the functor laws. In particular, fmapT id = id should hold. With this definition, fmapT id is returnT . extractT, which, in general, is not id (most functors which are instances of both Monad and Comonad serve as examples).

Is "every monad is a functor" a conclusion when using bind (in the definition of a monad), but an assumption when using join?

"Every monad is a functor" is an assumption, or, more precisely, part of the definition of monad. To pick an arbitrary illustration, here is Emily Riehl, Category Theory In Context, p. 154:

Definition 5.1.1. A monad on a category C consists of

an endofunctor T : C → C,

a unit natural transformation η : 1C ⇒ T, and

a multiplication natural transformation μ :T2 ⇒ T,

so that the following diagrams commute in CC: [diagrams of the monad laws]

A monad, therefore, involves an endofunctor by definition. For a Haskell type constructor T that instantiates Monad, the object mapping of that endofunctor is T itself, and the morphism mapping is its fmap. That T will be a Functor instance, and therefore will have an fmap, is, in contemporary Haskell, guaranteed by Applicative (and, by extension, Functor) being a superclass of Monad.

Is that the whole story, though? As far as Haskell is concerned. we know that liftM exists, and also that in a not-so-distant past Functor was not a superclass of Monad. Are those two facts mere Haskellisms? Not quite. In the classic paper Notions of computation and monads, Eugenio Moggi unearths the following definition (p. 3):

Definition 1.2 ([Man76]) A Kleisli triple over a category C is a triple (T, η, _*), where T : Obj(C) → Obj(C), ηA : A → T A for A ∈ Obj(C), f* : T A → T B for f : A → T B and the following equations hold:

ηA* = idT A

ηA; f* = f   for     f : A → T B

f*; g* = (f; g*)*   for   f : A → T B   and   g : B → T C

The important detail here is that T is presented as merely an object mapping in the category C, and not as an endofunctor in C. Working in the Hask category, that amounts to taking a type constructor T without presupposing it is a Functor instance. In code, we might write that as:

class KleisliTriple t where
    return :: a -> t a
    (=<<) :: (a -> t b) -> t a -> t b

-- (return =<<) = id
-- (f =<<) . return = f
-- (g =<<) . (f =<<) = ((g =<<) . f =<<)

Flipped bind aside, that is the pre-AMP definition of Monad in Haskell. Unsurprisingly, Moggi's paper doesn't take long to show that "there is a one-to-one correspondence between Kleisli triples and monads" (p. 5), establishing along the way that T can be extended to an endofunctor (in Haskell, that step amounts to defining the morphism mapping liftM f m = return . f =<< m, and then showing it follows the functor laws).

All in all, if you write lawful definitions of return and (>>=) without presupposing fmap, you indeed get a lawful implementation of Functor as a consequence. "There is a one-to-one correspondence between Kleisli triples and monads" is a consequence of the definition of Kleisli triple, while "a monad involves an endofunctor" is part of the definition of monad. It is tempting to consider whether it would be more accurate to describe what Haskellers did when writing Monad instances as "setting up a Klesili triple" rather than "setting up a monad", but I will refrain out of fear of getting mired down terminological pedantry -- and in any case, now that Functor is a superclass of Monad there is no practical reason to worry about that.

Is bind more "powerful" than join? And what would "more powerful" mean?

Trick question!

Taken at face value, the answer would be yes, to the extent that, together with return, (>>=) makes it possible to implement fmap (via liftM, as noted above), while join doesn't. However, I don't feel it is worthwhile to insist on this distinction. Why so? Because of the monad laws. Just like it doesn't make sense to talk about a lawful (>>=) without presupposing return, it doesn't make sense to talk about a lawful join without pressuposing return and fmap.

One might get the impression that I am giving too much weight to the laws by using them to tie Monad and Functor in this way. It is true that there are cases of laws that involve two classes, and that only apply to types which instantiate them both. Foldable provides a good example of that: we can find the following law in the Traversable documentation:

The superclass instances should satisfy the following: [...]

In the Foldable instance, foldMap should be equivalent to traversal with a constant applicative functor (foldMapDefault).

That this specific law doesn't always apply is not a problem, because we don't need it to characterise what Foldable is (alternatives include "a Foldable is a container from which we can extract some sequence of elements", and "a Foldable is a container that can be converted to the free monoid on its element type"). With the monad laws, though, it isn't like that: the meaning of the class is inextricably bound to all three of the monad laws.


来源: stackexchange

问:
How to print Graphene-Django / Graphene-Python Exceptions to the Console for Debugging?
When a GraphQL Error occurs, I cannot easily know where it occured. I have to spend unnecessary time trying to track it down. How do I get a Traceback printed in the console of my text editor?</p>

答:
I answered my own question by accessing the GraphQL error(s) with result.errors, iterating through the list, and using python's print_tb function to print the Traceback.

Does anyone have a different or better way of doing it?

Example usage of the print_graphql_errors function:

```<code>from django.conf.settings import DEBUG

result = schema.execute(
    mutation_str, context_value=request, variable_values=variable_values
)

if result.errors is None:
    return self.handle_success(result)
if DEBUG:
    print_graphql_errors(result.errors)

return self.handle_failure(result)

</code>```

The print_graphql_errors function:

```<code>from traceback import print_tb
from django.conf.settings import DEBUG

def print_graphql_errors(errors, raise_error=False):
    if not DEBUG:
        raise Exception(
            'DevError: This function should not be called in production'
        )

    assert errors, 'DevError: The "errors" parameter cannot be None'
    print_after = []
    current_error = None

    print('######################################################################')
    print('Manually Generated Traceback (with the print_graphql_errors function):')
    print(f'There are {len(errors)} errors:')

    for i, error in enumerate(errors):
        print(f'{i + 1}) ', error)

    print('######################################################################')

    for error in errors:
        current_error = error
        # FYI: This object has these attributes: (example attribute values)
            # tb_frame <frame at 0x000002DDB844D548, file 'site-packages\\graphql\\execution\\executor.py', line 455, code resolve_or_error>
            # tb_lasti 16
            # tb_lineno 447
            # tb_next <traceback object at 0x000002DDBAFBA388>
        # print('error.locations:', error.locations)
        # print('error.positions:', error.positions)
        try:
            print_tb(error.stack)
        except AttributeError as e:
            print(e.__traceback__)
            print(f'Warning: An error occured while trying to print the traceback: {e}. It has the following attributes instead: {dir(error)}')
            print_after.append(error)

    if len(print_after):
        print('###################################################################')
        print(f'Number of errors without the "stack" attribute: {len(print_after)}')
        print('###################################################################')

    if raise_error:
        for error in print_after:
            raise error

        raise current_error
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I answered my own question by accessing the GraphQL error(s) with result.errors, iterating through the list, and using python's print_tb function to print the Traceback.

Does anyone have a different or better way of doing it?

Example usage of the print_graphql_errors function:

from django.conf.settings import DEBUG

result = schema.execute(
    mutation_str, context_value=request, variable_values=variable_values
)

if result.errors is None:
    return self.handle_success(result)
if DEBUG:
    print_graphql_errors(result.errors)

return self.handle_failure(result)

The print_graphql_errors function:

from traceback import print_tb
from django.conf.settings import DEBUG

def print_graphql_errors(errors, raise_error=False):
    if not DEBUG:
        raise Exception(
            'DevError: This function should not be called in production'
        )

    assert errors, 'DevError: The "errors" parameter cannot be None'
    print_after = []
    current_error = None

    print('######################################################################')
    print('Manually Generated Traceback (with the print_graphql_errors function):')
    print(f'There are {len(errors)} errors:')

    for i, error in enumerate(errors):
        print(f'{i + 1}) ', error)

    print('######################################################################')

    for error in errors:
        current_error = error
        # FYI: This object has these attributes: (example attribute values)
            # tb_frame <frame at 0x000002DDB844D548, file 'site-packages\\graphql\\execution\\executor.py', line 455, code resolve_or_error>
            # tb_lasti 16
            # tb_lineno 447
            # tb_next <traceback object at 0x000002DDBAFBA388>
        # print('error.locations:', error.locations)
        # print('error.positions:', error.positions)
        try:
            print_tb(error.stack)
        except AttributeError as e:
            print(e.__traceback__)
            print(f'Warning: An error occured while trying to print the traceback: {e}. It has the following attributes instead: {dir(error)}')
            print_after.append(error)

    if len(print_after):
        print('###################################################################')
        print(f'Number of errors without the "stack" attribute: {len(print_after)}')
        print('###################################################################')

    if raise_error:
        for error in print_after:
            raise error

        raise current_error


问:
What is better to use just one method with switch or 4 different methods?
I have a object and i get some fields from it, i made a method with a switch statement, the idea was make it generic and just call this method through parameters but now I´m not sure.

The options are

```<code>private String getCode(Row row, String code) {
    String result;
    switch (code) {
      case code1:
        result = row.getString("constant1");
        break;
      case code2:
        result = row.getString(constant2);
        break;
      case code3:
        result = row.getString(constant3);
        break;
      case code4:
        result = row.getString(constant4);
        break;
      default:
        result = null;
    }
    return result;
  }
</code>```

or

```<code>private String getcode1(Row row){
    return row.getString("constant1")
  }

  private String getcode1(Row row){
    return row.getString("constant2")
  }
  private String getcode1(Row row){
    return row.getString("constant3")
  }

  private String getcode1(Row row){
    return row.getString("constant4")
  }
</code>```

I wand to use the better way, I´m a little confuse

答:
In case your input code is different than constant, I will suggest the following approach. Create an Enum mapping code and constant.

```<code>public enum Mapping {
    MAPPING_FIRST("code1", "constant1"),
    MAPPING_SECOND("code2", "constant2");

    private String code;
    private String constant;

    // constructor and getters

    public static Mapping getMappingFromCode(String code){
       return Arrays.stream(Mapping.values())
          .filter(mapping -> mapping.getCode().equals(code))
          .findFirst()
          .orElse(null);
    }
}
</code>```

Now, create a method to access value from row.

```<code>private String getValue(Row row, String code) {
   Mapping mapping = Mapping.getMappingFromCode(code);

   if(mapping == null){
      return null;
   }
   return row.getString(mapping.getConstant());
}
</code>```

Body:
I have a object and i get some fields from it, i made a method with a switch statement, the idea was make it generic and just call this method through parameters but now I´m not sure.

The options are

private String getCode(Row row, String code) {
    String result;
    switch (code) {
      case code1:
        result = row.getString("constant1");
        break;
      case code2:
        result = row.getString(constant2);
        break;
      case code3:
        result = row.getString(constant3);
        break;
      case code4:
        result = row.getString(constant4);
        break;
      default:
        result = null;
    }
    return result;
  }

or

private String getcode1(Row row){
    return row.getString("constant1")
  }

  private String getcode1(Row row){
    return row.getString("constant2")
  }
  private String getcode1(Row row){
    return row.getString("constant3")
  }

  private String getcode1(Row row){
    return row.getString("constant4")
  }

I wand to use the better way, I´m a little confuse

Body:
In case your input code is different than constant, I will suggest the following approach. Create an Enum mapping code and constant.

public enum Mapping {
    MAPPING_FIRST("code1", "constant1"),
    MAPPING_SECOND("code2", "constant2");

    private String code;
    private String constant;

    // constructor and getters

    public static Mapping getMappingFromCode(String code){
       return Arrays.stream(Mapping.values())
          .filter(mapping -> mapping.getCode().equals(code))
          .findFirst()
          .orElse(null);
    }
}

Now, create a method to access value from row.

private String getValue(Row row, String code) {
   Mapping mapping = Mapping.getMappingFromCode(code);

   if(mapping == null){
      return null;
   }
   return row.getString(mapping.getConstant());
}


问:
How to combine two columns and apply binarizer?
Tried using MultiLabelBinarizer and did not work

For ex: device category (has two values - android and ios), browser (3 values chrome, safari, and IE) are two columns... If there a android value in device category and safari in browser column then binarizer column name of androd_safari will have to put the value as 1... Like this out will have 6 binarizer columns with value either 0 or 1

Do I need to write my own function or there is a built in dataframe functions that I can use

答:
There are several approaches in normalizing the training/test set data using LocalEncoder, LabelBinarizer, but these are applied on single column

To create the binarization based on two columns (to label your data set) create a temporary DataFrame and do as below:

```<code>import timeit
import numpy as np
import pandas as pd

def two_col_binarizer(df, col1, col2):
    start_time = timeit.default_timer()
    arcol1 = df[col1].unique()
    arcol2 = df[col2].unique()
    arbdc = np.empty((arcol1.size*arcol2.size), dtype=object)

    for i in range(arcol1.size):
        for j in range(arcol2.size):
            arbdc[i*arcol2.size+j] = arcol1[i]+arcol2[j]

    num_rows, num_cols = df.shape
    tempdf = pd.DataFrame(index=range(0, num_rows), columns = arbdc)
    tempdf = tempdf.fillna(0)

    for i in range(len(df.index)):
        tempdf.at[i, df['device.deviceCategory'][i]+df['device.browser'][i]] = 1

    print(timeit.default_timer() - start_time)
    return tempdf

# for example your training data set has devicecategory and browser columns
df=df.join(two_col_binarizer(df, 'devicecategory', 'browser'))
</code>```

Body:
There are several approaches in normalizing the training/test set data using LocalEncoder, LabelBinarizer, but these are applied on single column

To create the binarization based on two columns (to label your data set) create a temporary DataFrame and do as below:

import timeit
import numpy as np
import pandas as pd

def two_col_binarizer(df, col1, col2):
    start_time = timeit.default_timer()
    arcol1 = df[col1].unique()
    arcol2 = df[col2].unique()
    arbdc = np.empty((arcol1.size*arcol2.size), dtype=object)

    for i in range(arcol1.size):
        for j in range(arcol2.size):
            arbdc[i*arcol2.size+j] = arcol1[i]+arcol2[j]

    num_rows, num_cols = df.shape
    tempdf = pd.DataFrame(index=range(0, num_rows), columns = arbdc)
    tempdf = tempdf.fillna(0)

    for i in range(len(df.index)):
        tempdf.at[i, df['device.deviceCategory'][i]+df['device.browser'][i]] = 1

    print(timeit.default_timer() - start_time)
    return tempdf

# for example your training data set has devicecategory and browser columns
df=df.join(two_col_binarizer(df, 'devicecategory', 'browser'))


问:
Can't understand this error "Unknown label type: 'continuous-multioutput' "
I am trying to run several machine learning algorithms on a dataset to predict whether the salary/income is greater than 50k or less than equal to 50k. I made a function and am passing the values to it, with different size sample sets of 1% samples, 10% samples and 100% samples.
I am getting an unknown error 'Unknown label type: 'continuous-multioutput''
I don't know what this error is.

I tried changing the classification algorithms I used but no use. It displays the same error for all the alogrithms.

```<code>from sklearn.metrics import fbeta_score, accuracy_score

def train_predict (learner, sample_size, X_train, X_test, y_train, y_test):
    results = {}
    start = time()
    learner = learner.fit(X_train[:sample_size], y_train)
    end = time()
    results['train_time'] = end - start

    start = time()
    predictions_test = learner.predict(X_test)
    predictions_train = learner.predict(X_train[:sample_size])
    end = time()

    results['pred_time'] = end - start
    results['acc_train'] = accuracy_score(X_train[:sample_size], y_train[:sample_size])
    results['acc_test'] = accuracy_score[X_test, y_test]
    results['f_train'] = fbeta_score(X_train[:sample_size], y_train[:sample_size], beta = 1)
    resutts['f_test'] = fbeta_score(X_test, y_test, beta = 1)
    print("{} trained on {} samples. ".format(learner.__class__.__name__, sample_size))
    return results

from sklearn.tree import DecisionTreeClassifier
from sklearn.naive_bayes import GaussianNB
from sklearn.svm import SVC

clf_A = DecisionTreeClassifier()
clf_B = GaussianNB()
clf_C = SVC()

samples_100 = len(X_train)       #taking 100% i.e. all the data in training set
samples_10 = int(len(X_train)*.1) # taking 10% of the training data
samples_1 = int(len(X_train)*.01) #taking 1% of the training data

results= {}
for clf in [clf_A, clf_B, clf_C]:
    clf_name = clf.__class__.__name__
    results[clf_name] = {}
    for i, samples in enumerate([samples_1, samples_10, samples_100]):
        results[clf_name][i] = \
        train_predict(clf, samples, X_train, y_train, X_test, y_test)
vs.evaluate(results, accuracy, fscore)

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-66-e06d42fbd15b> in <module>
      5     for i, samples in enumerate([samples_1, samples_10, samples_100]):
      6         results[clf_name][i] = \
----> 7         train_predict(clf, samples, X_train, y_train, X_test, y_test)
      8 vs.evaluate(results, accuracy, fscore)

<ipython-input-62-4484b803a707> in train_predict(learner, sample_size, X_train, X_test, y_train, y_test)
      2     results = {}
      3     start = time()
----> 4     learner = learner.fit(X_train[:sample_size], y_train)
      5     end = time()
      6     results['train_time'] = end - start

C:\ProgramData\Anaconda3\lib\site-packages\sklearn\tree\tree.py in fit(self, X, y, sample_weight, check_input, X_idx_sorted)
    799             sample_weight=sample_weight,
    800             check_input=check_input,
--> 801             X_idx_sorted=X_idx_sorted)
    802         return self
    803

C:\ProgramData\Anaconda3\lib\site-packages\sklearn\tree\tree.py in fit(self, X, y, sample_weight, check_input, X_idx_sorted)
    138
    139         if is_classification:
--> 140             check_classification_targets(y)
    141             y = np.copy(y)
    142

C:\ProgramData\Anaconda3\lib\site-packages\sklearn\utils\multiclass.py in check_classification_targets(y)
    169     if y_type not in ['binary', 'multiclass', 'multiclass-multioutput',
    170                       'multilabel-indicator', 'multilabel-sequences']:
--> 171         raise ValueError("Unknown label type: %r" % y_type)
    172
    173

ValueError: Unknown label type: 'continuous-multioutput'
</code>```

I want this code to run and show the accuracy and other metrics of these algorithms for this datasets.

P.S. I know the code is too long and cumbersome but please take efforts to go through it and let me know the solution. I am newbie in this machine learning domain. Any help will be highly appreciated.

P.S. Please don't mark this question as duplicate I have already been through similar questions and tried all that was suggested there but in vain. It wan't of any use to me.

答:
Ok, I got the error the problem was with the way I was sampling the data sets.
I changed the sampling code using frac attribute and the error disappeared.</p>

```<code>samples_100 = df.sample(frac = 1)      #taking 100% i.e. all the data in training set
samples_10 = df.sample(frac = .1)      #taking 10% of the training data
samples_1 = df.sample(frac = .01)      #taking 1% of the training data
</code>```

Body:
I am trying to run several machine learning algorithms on a dataset to predict whether the salary/income is greater than 50k or less than equal to 50k. I made a function and am passing the values to it, with different size sample sets of 1% samples, 10% samples and 100% samples.
I am getting an unknown error 'Unknown label type: 'continuous-multioutput''
I don't know what this error is.

I tried changing the classification algorithms I used but no use. It displays the same error for all the alogrithms.

from sklearn.metrics import fbeta_score, accuracy_score

def train_predict (learner, sample_size, X_train, X_test, y_train, y_test):
    results = {}
    start = time()
    learner = learner.fit(X_train[:sample_size], y_train)
    end = time()
    results['train_time'] = end - start

    start = time()
    predictions_test = learner.predict(X_test)
    predictions_train = learner.predict(X_train[:sample_size])
    end = time()

    results['pred_time'] = end - start
    results['acc_train'] = accuracy_score(X_train[:sample_size], y_train[:sample_size])
    results['acc_test'] = accuracy_score[X_test, y_test]
    results['f_train'] = fbeta_score(X_train[:sample_size], y_train[:sample_size], beta = 1)
    resutts['f_test'] = fbeta_score(X_test, y_test, beta = 1)
    print("{} trained on {} samples. ".format(learner.__class__.__name__, sample_size))
    return results

from sklearn.tree import DecisionTreeClassifier
from sklearn.naive_bayes import GaussianNB
from sklearn.svm import SVC

clf_A = DecisionTreeClassifier()
clf_B = GaussianNB()
clf_C = SVC()

samples_100 = len(X_train)       #taking 100% i.e. all the data in training set
samples_10 = int(len(X_train)*.1) # taking 10% of the training data
samples_1 = int(len(X_train)*.01) #taking 1% of the training data

results= {}
for clf in [clf_A, clf_B, clf_C]:
    clf_name = clf.__class__.__name__
    results[clf_name] = {}
    for i, samples in enumerate([samples_1, samples_10, samples_100]):
        results[clf_name][i] = \
        train_predict(clf, samples, X_train, y_train, X_test, y_test)
vs.evaluate(results, accuracy, fscore)

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-66-e06d42fbd15b> in <module>
      5     for i, samples in enumerate([samples_1, samples_10, samples_100]):
      6         results[clf_name][i] = \
----> 7         train_predict(clf, samples, X_train, y_train, X_test, y_test)
      8 vs.evaluate(results, accuracy, fscore)

<ipython-input-62-4484b803a707> in train_predict(learner, sample_size, X_train, X_test, y_train, y_test)
      2     results = {}
      3     start = time()
----> 4     learner = learner.fit(X_train[:sample_size], y_train)
      5     end = time()
      6     results['train_time'] = end - start

C:\ProgramData\Anaconda3\lib\site-packages\sklearn\tree\tree.py in fit(self, X, y, sample_weight, check_input, X_idx_sorted)
    799             sample_weight=sample_weight,
    800             check_input=check_input,
--> 801             X_idx_sorted=X_idx_sorted)
    802         return self
    803

C:\ProgramData\Anaconda3\lib\site-packages\sklearn\tree\tree.py in fit(self, X, y, sample_weight, check_input, X_idx_sorted)
    138
    139         if is_classification:
--> 140             check_classification_targets(y)
    141             y = np.copy(y)
    142

C:\ProgramData\Anaconda3\lib\site-packages\sklearn\utils\multiclass.py in check_classification_targets(y)
    169     if y_type not in ['binary', 'multiclass', 'multiclass-multioutput',
    170                       'multilabel-indicator', 'multilabel-sequences']:
--> 171         raise ValueError("Unknown label type: %r" % y_type)
    172
    173

ValueError: Unknown label type: 'continuous-multioutput'

I want this code to run and show the accuracy and other metrics of these algorithms for this datasets.

P.S. I know the code is too long and cumbersome but please take efforts to go through it and let me know the solution. I am newbie in this machine learning domain. Any help will be highly appreciated.

P.S. Please don't mark this question as duplicate I have already been through similar questions and tried all that was suggested there but in vain. It wan't of any use to me.

Body:
Ok, I got the error the problem was with the way I was sampling the data sets.
I changed the sampling code using frac attribute and the error disappeared.

samples_100 = df.sample(frac = 1)      #taking 100% i.e. all the data in training set
samples_10 = df.sample(frac = .1)      #taking 10% of the training data
samples_1 = df.sample(frac = .01)      #taking 1% of the training data


问:
Where to get the tools.jar to use with the Java 8 jdk early release
Where to get tools.jar for Java 8 JDK early release? Without it, my Java 1.8 Maven pom based projects in Netbeans will not compile.

The Java 8 early release is set in the Java Platforms setting and all the Java 8 projects that are not Maven-based will compile and run.

https://jdk8.java.net/download.html

It is not found on the downloads page, I can not find anything in their search.

Does anyone have success compiling Maven pom based projects with the Java 8 early release?

Can the old tools.jar be used or where did you find it?

答: Simply copy the tools.jar from your jdk\lib folder and paste into jre\lib folder.


问:
WP7: Store data in users live account
For storing WP7-app-data it would be great if it was possible to use the current users live account. Is this possible somehow? I guess not. The alternative is for me to setup my own server to store the data, which means I also will have to implement account-management and require the user to create a new login and password for my particular app/site. This is not very practical as the user already has a live account on the phone. A compromise would be if I could use the logged in live-account on the phone as some kind of token to validate that the logged in user is who he/she pretends to be, and then store the data on my website. Comments?</p>

答:
This is not possible for security reasons and I wouldn't expect it to change in the foreseeable future.

Allowing applications access to a users live account and be able to interact with content there would raise all sorts of possible issues, particularly around security.

On the phone the users data is sacrosanct and you (your app) cannot interact with it without the user knowing.

ContentLicense: CC BY-SA 3.0

Title: WP7: Store data in users live account


问:
Facebook banner, Interstitial and Rewarded ads load in fragment
This is Rewarded video ads code

```<code>public class YourApplication extends Application {

@Override
public void onCreate() {
    super.onCreate();
    // Initialize the Audience Network SDK
    AudienceNetworkAds.initialize(this);
}
...
}
</code>```

Rewarded Video Ads in main activity

in  fragment  AudienceNetworkAds.initialize(this);   not support

答:
You don't need to initialize it in every Activity/Fragment AudienceNetworkAds.initialize(this);

You can initialize it once and it will work everywhere.

From the official guide

Before creating an ad object and loading ads, you should initialize
  the Audience Network SDK. It is recommended to do this at app launch.

However if you still want to do in fragment. change context this to getActivity()
AudienceNetworkAds.initialize(getActivity());

Body:
This is Rewarded video ads code

public class YourApplication extends Application {

@Override
public void onCreate() {
    super.onCreate();
    // Initialize the Audience Network SDK
    AudienceNetworkAds.initialize(this);
}
...
}

Rewarded Video Ads in main activity

in  fragment  AudienceNetworkAds.initialize(this);   not support


问:
How to merge two network requests response into single object
I am trying to retrieve data from below two API requests using retrofit client and want to display in Listview

I am getting response from both below API requests with differenr fields

In below API, coin name, coin price
https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest

In below API, logo
https://pro-api.coinmarketcap.com/v1/cryptocurrency/info

How to combine both above request responses in separate POJO class?

CoinName.kt
data class CoinName(
      var name: String,
      var price: String
)

CoinInfo.kt
data class CoinInfo(
      var logo: String
)

I want to show coin name, coin price, logo fields in my Listview. But coin name and price is present in class CoinName and logo present in CoinInfo class

答: You need to use zip operator and combine your responses into 3rd class. See this question</p>


问:
Selecting table rows with jquery, but also selecting rows when clicking button, how do I prevent this?
When you click on a table row it adds a class that changes it's appearance to reflect it's selected.

```<code>    $('#my_table tbody').on( 'click', 'tr', function () {
        $(this).toggleClass('selected');
    } );
</code>```

However, I also have some buttons in a column that let you do things specific to the row:

```<code>Item    Amount    Action
--------------------------------
Apple   10        [Buy] [Delete]
Banana  5         [Buy] [Delete]
Orange  14        [Buy] [Delete]
</code>```

When I click one of the individual buttons, it also triggers the table row '.selected' class to be added, but I don't want this to occur when clicking buttons.

答:
You might make sure that the td being clicked on is not in the column with the buttons. With :not, you can ensure that the matched element doesn't match a particular selector, and with :nth-child, you can specify the 3rd td in its container as the one to be excluded:

$('#my_table tbody').on('click', 'tr td:not(:nth-child(3))', function() {
  console.log('click registered');
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="my_table">
  <tr>
    <td>td 1</td>
    <td>td 2</td>
    <td><button>button</button></td>
  </tr>
</table></code>```

Body:
When you click on a table row it adds a class that changes it's appearance to reflect it's selected.

    $('#my_table tbody').on( 'click', 'tr', function () {
        $(this).toggleClass('selected');
    } );

However, I also have some buttons in a column that let you do things specific to the row:

Item    Amount    Action
--------------------------------
Apple   10        [Buy] [Delete]
Banana  5         [Buy] [Delete]
Orange  14        [Buy] [Delete]

When I click one of the individual buttons, it also triggers the table row '.selected' class to be added, but I don't want this to occur when clicking buttons.

Body:
You might make sure that the td being clicked on is not in the column with the buttons. With :not, you can ensure that the matched element doesn't match a particular selector, and with :nth-child, you can specify the 3rd td in its container as the one to be excluded:

$('#my_table tbody').on('click', 'tr td:not(:nth-child(3))', function() {
  console.log('click registered');
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="my_table">
  <tr>
    <td>td 1</td>
    <td>td 2</td>
    <td><button>button</button></td>
  </tr>
</table>


问:
How to convert alphabets to numerical values with spaces and return it back to alphabets?
Want to convert the alphabet to numerical values and transform it back to alphabets using some mathematical techniques like fast Fourier transform in MATLAB.

Example:

The following is the text saved in "text2figure.txt" file

```<code>Hi how r u am fine take care of your health
thank u very much
am 2.0
</code>```

Reading it in MATLAB:

```<code>data=fopen('text2figure.txt','r')
d=fscanf(data,'%s')
temp = fileread( 'text2figure.txt' )
temp = regexprep( temp, ' {6}', '   NaN' )
c=cellstr(temp(:))'
</code>```

Now I wish to convert cell array with spaces to numerical values/integers:

```<code>coding = 'abcdefghijklmnñopqrstuvwxyz .,;'
str = temp %// example text
[~, result] = ismember(str, coding)
y=result

result =

  Columns 1 through 18

     0     9    28     8    16    24    28    19    28    22    28     1    13    28     6     9    14     5

  Columns 19 through 36

    28    21     1    11     5    28     3     1    19     5    28    16     6    28    26    16    22    19

  Columns 37 through 54

    28     8     5     1    12    21     8    28     0     0    21     8     1    14    11    28    22    28

  Columns 55 through 71

    23     5    19    26    28    13    22     3     8     0     0     1    13    28     0    29     0
</code>```

Now I wish to convert the numerical values back to alphabets:

```<code>Hi how r u am fine take care of your health
thank u very much
am 2.0
</code>```

How to write a MATLAB code to return the numerical values in the variable result to alphabets?

答:
Most of the code in the question doesn't have any useful effects. These three lines are the ones that lead to result:

str = fileread('test2figure.txt');
coding = 'abcdefghijklmnñopqrstuvwxyz .,;';
[~, result] = ismember(str, coding);
```

<p><code>ismember</code> returns, in the second output argument, the indices into <code>coding</code> for each element of <code>str</code>. Thus, <code>result</code> are indices that we can use to index into <code>coding</code>:</p>

<pre class="lang-matlab prettyprint-override"><code>out = coding(result);
</code>```

However, this does not work because some elements of str do not occur in coding, and for those elements ismember returns 0, which is not a valid index. We can replace the zeros with a new character:

coding = ['*',coding];
out = coding(result+1);
```

<p>Basically, we're shifting each code by one, adding a new code for 1.</p>

<p>One of the characters we're missing here is the newline character. Thus the three lines have become one line. You can add a code for the newline character by adding it to the <code>coding</code> table:</p>

<pre class="lang-matlab prettyprint-override"><code>str = fileread('test2figure.txt');
coding = ['abcdefghijklmnñopqrstuvwxyz .,;',char(10)]; % char(10) is the newline character
[~, result] = ismember(str, coding);

coding = ['*',coding];
out = coding(result+1);
</code>```

All of this is easier to achieve just using the ASCII code table:

str = fileread('test2figure.txt');
result = double(str);

out = char(result);
```

Body:
Want to convert the alphabet to numerical values and transform it back to alphabets using some mathematical techniques like fast Fourier transform in MATLAB.

Example:

The following is the text saved in "text2figure.txt" file

Hi how r u am fine take care of your health
thank u very much
am 2.0

Reading it in MATLAB:

data=fopen('text2figure.txt','r')
d=fscanf(data,'%s')
temp = fileread( 'text2figure.txt' )
temp = regexprep( temp, ' {6}', '   NaN' )
c=cellstr(temp(:))'

Now I wish to convert cell array with spaces to numerical values/integers:

coding = 'abcdefghijklmnñopqrstuvwxyz .,;'
str = temp %// example text
[~, result] = ismember(str, coding)
y=result

result =

  Columns 1 through 18

     0     9    28     8    16    24    28    19    28    22    28     1    13    28     6     9    14     5

  Columns 19 through 36

    28    21     1    11     5    28     3     1    19     5    28    16     6    28    26    16    22    19

  Columns 37 through 54

    28     8     5     1    12    21     8    28     0     0    21     8     1    14    11    28    22    28

  Columns 55 through 71

    23     5    19    26    28    13    22     3     8     0     0     1    13    28     0    29     0

Now I wish to convert the numerical values back to alphabets:

Hi how r u am fine take care of your health
thank u very much
am 2.0

How to write a MATLAB code to return the numerical values in the variable result to alphabets?

Body:
Most of the code in the question doesn't have any useful effects. These three lines are the ones that lead to result:

str = fileread('test2figure.txt');
coding = 'abcdefghijklmnñopqrstuvwxyz .,;';
[~, result] = ismember(str, coding);

ismember returns, in the second output argument, the indices into coding for each element of str. Thus, result are indices that we can use to index into coding:

out = coding(result);

However, this does not work because some elements of str do not occur in coding, and for those elements ismember returns 0, which is not a valid index. We can replace the zeros with a new character:

coding = ['*',coding];
out = coding(result+1);

Basically, we're shifting each code by one, adding a new code for 1.

One of the characters we're missing here is the newline character. Thus the three lines have become one line. You can add a code for the newline character by adding it to the coding table:

str = fileread('test2figure.txt');
coding = ['abcdefghijklmnñopqrstuvwxyz .,;',char(10)]; % char(10) is the newline character
[~, result] = ismember(str, coding);

coding = ['*',coding];
out = coding(result+1);

All of this is easier to achieve just using the ASCII code table:

str = fileread('test2figure.txt');
result = double(str);

out = char(result);


问:
Multiple path to same Razor view - ASP.NET MVC breadcrum using SiteMap Provider
I have Asp.NET MVC SiteMap Provider version 4.0.

I have written a small test project that has several test Razor views.
Here is MvcSite xml file that has paths defined:

```<code> <mvcSiteMapNode title="Home - default" controller="Home" action="Index">
    <mvcSiteMapNode title="Middle - default" controller="Home" action="Middle">
      <mvcSiteMapNode title="Edit - default" controller="Home" action="Edit" key="keyForEdit">
      </mvcSiteMapNode>
    <mvcSiteMapNode title="Over - another path" controller="Home" action="Over">
      <mvcSiteMapNode title="Edit through over" controller="Home" action="Edit" canonicalKey="keyForEdit">
      </mvcSiteMapNode>
    </mvcSiteMapNode>
    </mvcSiteMapNode>
  </mvcSiteMapNode>
</mvcSiteMap>
</code>```

The idea is to reach "Edit" view from different places in application. I can go through "Middle" or through "Over" Razor view. My goal is to have different bredcrumb displays for these different paths to "Edit" view.
Here is a master layout that the site is built with:

```<code>    @{
        Layout = null;
    }

    <!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>This is layout</title>
    @Html.MvcSiteMap().CanonicalTag()
</head>
<body>
    <div>Hi from Layout!</div>
    <div>@Html.MvcSiteMap().SiteMapPath()</div>
    <div>
        @RenderBody()
    </div>
</body>
</html>
</code>```

Still, each time I get to "Edit" view I have "Edit - default" title inside breadcrumb.
Why is this?
Thank you very much for your time.

答:
You can use URL in your mvc.sitemap nodes: </p>

```<code><mvcSiteMapNode title="Home - default" controller="Home" action="Index">
    <mvcSiteMapNode title="Middle - default" controller="Home" action="Middle">
        <mvcSiteMapNode title="Edit - default" controller="Home" action="Edit" key="keyForEdit" url="/Home/Edit"/>
    </mvcSiteMapNode>
    <mvcSiteMapNode title="Over - another path" controller="Home" action="Over">
        <mvcSiteMapNode title="Edit through over" controller="Home" action="Edit" url="/Home/Edit/Path2" canonicalKey="keyForEdit"/>
    </mvcSiteMapNode>
</mvcSiteMapNode>
</code>```

Body:
I have Asp.NET MVC SiteMap Provider version 4.0.

I have written a small test project that has several test Razor views.
Here is MvcSite xml file that has paths defined:

 <mvcSiteMapNode title="Home - default" controller="Home" action="Index">
    <mvcSiteMapNode title="Middle - default" controller="Home" action="Middle">
      <mvcSiteMapNode title="Edit - default" controller="Home" action="Edit" key="keyForEdit">
      </mvcSiteMapNode>
    <mvcSiteMapNode title="Over - another path" controller="Home" action="Over">
      <mvcSiteMapNode title="Edit through over" controller="Home" action="Edit" canonicalKey="keyForEdit">
      </mvcSiteMapNode>
    </mvcSiteMapNode>
    </mvcSiteMapNode>
  </mvcSiteMapNode>
</mvcSiteMap>

The idea is to reach "Edit" view from different places in application. I can go through "Middle" or through "Over" Razor view. My goal is to have different bredcrumb displays for these different paths to "Edit" view.
Here is a master layout that the site is built with:

    @{
        Layout = null;
    }

    <!DOCTYPE html>

    <meta name="viewport" content="width=device-width" />
    <title>This is layout</title>
    @Html.MvcSiteMap().CanonicalTag()

Hi from Layout!

@Html.MvcSiteMap().SiteMapPath()

        @RenderBody()

Still, each time I get to "Edit" view I have "Edit - default" title inside breadcrumb.
Why is this?
Thank you very much for your time.

Body:
You can use URL in your mvc.sitemap nodes:

<mvcSiteMapNode title="Home - default" controller="Home" action="Index">
    <mvcSiteMapNode title="Middle - default" controller="Home" action="Middle">
        <mvcSiteMapNode title="Edit - default" controller="Home" action="Edit" key="keyForEdit" url="/Home/Edit"/>
    </mvcSiteMapNode>
    <mvcSiteMapNode title="Over - another path" controller="Home" action="Over">
        <mvcSiteMapNode title="Edit through over" controller="Home" action="Edit" url="/Home/Edit/Path2" canonicalKey="keyForEdit"/>
    </mvcSiteMapNode>
</mvcSiteMapNode>


问:
How to get values from foreach with insert statement
I'm a newbie. I use GetSelectedIndices and foreach to get each values in array.

After that, I provided those values for the insert statement. How can I get query_TheLoai from insert statement in foreach? I work it on webform

```<code>var TheLoaiIds = lbxTheLoai.GetSelectedIndices();

foreach (var TheLoaiId in TheLoaiIds)
{
    string query_TheLoai = "SELECT @MaPhim = SCOPE_IDENTITY();INSERT INTO ChiTietTL VALUES ('" + TheLoaiId + "', @MaPhim)";
}
</code>```

Sorry for the awkwardness

答:
```<code>var TheLoaiIds = lbxTheLoai.GetSelectedIndices();
string CStr = "YourConnectionString";

string Query = "INSERT INTO ChiTietTL VALUES ('" + TheLoaiId + "', @MaPhim)";

using(var conn = new SqlConnection(CStr))
{
    foreach (var TheLoaiId in TheLoaiIds)
    {
        using(var cmd = new SqlCommand(Query, conn))
        {
             try
             {
                 cmd.Parameters.AddWithValue("@MaPhim", TheLoaiId);
                 cmd.ExecuteNonQuery();
             }
             catch (SqlException ex)
             {
                 MessageBox.Show(ex.ToString());
             }
         }
     }
}
</code>```

Body:
I'm a newbie. I use GetSelectedIndices and foreach to get each values in array.

After that, I provided those values for the insert statement. How can I get query_TheLoai from insert statement in foreach? I work it on webform

var TheLoaiIds = lbxTheLoai.GetSelectedIndices();

foreach (var TheLoaiId in TheLoaiIds)
{
    string query_TheLoai = "SELECT @MaPhim = SCOPE_IDENTITY();INSERT INTO ChiTietTL VALUES ('" + TheLoaiId + "', @MaPhim)";
}

Sorry for the awkwardness


答:
You are experiencing a feature of the DOM called Event Propagation.

What you want to do is prevent this from occurring by calling Event.stopPropagation() in the handlers for your  clicks

To stop propagation with a jQuery event handler, simply return false on the last line of your td click handlers.

Title: Selecting table rows with jquery, but also selecting rows when clicking button, how do I prevent this?

Body:
You are experiencing a feature of the DOM called Event Propagation.

What you want to do is prevent this from occurring by calling Event.stopPropagation() in the handlers for your <td> clicks

To stop propagation with a jQuery event handler, simply return false on the last line of your td click handlers.


问:
What to use AWS Fargate or AWS Beanstalk
I have a java application that reads from a SQS queue and does some business processing and finally writes it to a datastore. As the SQS queue grows I want to be able to scale to read more messages and process them. Each SQS message will take about 15 to 20 minutes to process. I was looking at a service like AWS Fargate or AWS Beanstalk to deploy my application. Money is not a concern but usability is. What would be the best platform?</p>

答:
Fargate would be an ideal solution, as it has following advantages over Beanstalk:

It's serverless

More fine-grained control for custom application architectures.

No need to write EB extensions.

Build and Test image locally and Promote same to Fargate.

With application autoscaling, you can scale on the go.

Pricing is per second with a 1-minute minimum

FAQ:
https://aws.amazon.com/fargate/faqs/

Pricing:
https://aws.amazon.com/fargate/pricing/


问:
Auto suggestion in text field with data from Google API
I want to make an autocomplete text field with suggestions where data is from the Google API - updated after each new key pressed.
For now, I have a method that downloads 5 suggestions and updates them when another key is pressed.

I've tried AutoCompleteTextField from Gluon, but it didn't work out well.

public class Controller {
    Weather weather = new Weather();
    GooglePlaces googlePlaces = new GooglePlaces();

    @FXML
    AutoCompleteTextField<String> autoCompleteTextField = new AutoCompleteTextField<>();

    @FXML
    public void setAutoComplete() throws IOException {
        ArrayList<String[]> places = googlePlaces.predictPlaces("New yo");

        autoCompleteTextField.setCompleter(s -> {
            ArrayList<String> autoplaces = new ArrayList<>();
            for (int i = 0; i < places.size(); i++) {
                autoplaces.add(places.get(i)[0]);
            }
            System.out.println("test");
            return autoplaces;
        });
    }
}
```

Here I tried to add 5 suggestions from "New yo" phase without updating after each new key, but it didn't work either as it doesn't show anything. "test" isnt printed in the console.

答:
Seems to me that you need to call setCompleter() in a method called initialize():

```<code>public class Controller {

    @FXML
    public void initialize() {
        autoCompleteTextField.setCompleter(input -> {
            List<String[]> places = googlePlaces.predictPlaces(input);
            // ...
        });
    }
}
</code>```

Also see:

JavaFX FXML controller - constructor vs initialize method

Is there a counterpart to @FXML initialize?

Body:
I want to make an autocomplete text field with suggestions where data is from the Google API - updated after each new key pressed.
For now, I have a method that downloads 5 suggestions and updates them when another key is pressed.

I've tried AutoCompleteTextField from Gluon, but it didn't work out well.

public class Controller {
    Weather weather = new Weather();
    GooglePlaces googlePlaces = new GooglePlaces();

    @FXML
    AutoCompleteTextField<String> autoCompleteTextField = new AutoCompleteTextField<>();

    @FXML
    public void setAutoComplete() throws IOException {
        ArrayList<String[]> places = googlePlaces.predictPlaces("New yo");

        autoCompleteTextField.setCompleter(s -> {
            ArrayList<String> autoplaces = new ArrayList<>();
            for (int i = 0; i < places.size(); i++) {
                autoplaces.add(places.get(i)[0]);
            }
            System.out.println("test");
            return autoplaces;
        });
    }
}

Here I tried to add 5 suggestions from "New yo" phase without updating after each new key, but it didn't work either as it doesn't show anything. "test" isnt printed in the console.

Body:
Seems to me that you need to call setCompleter() in a method called initialize():

public class Controller {

    @FXML
    public void initialize() {
        autoCompleteTextField.setCompleter(input -> {
            List<String[]> places = googlePlaces.predictPlaces(input);
            // ...
        });
    }
}

Also see:

JavaFX FXML controller - constructor vs initialize method

Is there a counterpart to @FXML initialize?


问:
Read the data from CSV and put it into .rxt file
I am quite new to shell script and in the starting phase only I have a interested case. So the case is like I have a csv file that contains the data like:

```<code>ip_address,name,address,phone,email_id
192.168.1.1,ABC,Delhi,1234567,abc@gmail.com
192.168.1.2,MNO,Bangalore,1234567,mno@gmail.com
192.168.1.3,CDE,Pune,1234567,cde@gmail.com
192.168.1.4,PQR,Mumbai,1234567,pqr@gmail.com
192.168.1.5,XYZ,Noida,1234567,xyz@gmail.com
</code>```

How can I write a shell script that will login to the server(192.168.1.1, 192.168.1.2 and so on) and shell script should create .rxt file on that particular server inside /root directory and put the respective data to that rxt file like the below?

(i.e we can create directory like /root/data and inside this data we can put our rxt file as details.rxt)

```<code>ip_address=192.168.1.1
name=ABC
address=Delhi
phone=1234567
email_id=abc@gmail.com

ip_address=192.168.1.2
name=MNO
address=Bangalore
phone=1234567
email_id=mno@gmail.com
</code>```

and so on.

EDIT:

I am trying to read the data from csv file like:

```<code>INPUT=serverdetails.csv
OLDIFS=$IFS
IFS=“,”
[ ! -f $INPUT ] && { echo "$INPUT file not found"; exit 99}
while read ip_address name address phone email_id
do
  echo “IPAddress = $ip_address”
  echo “Name = $name”
  echo “Address = $address”
  echo "Telephone = $phone”
  echo “EmailID = $email_id”
done < $INPUT
IFS=$OLDIFS
</code>```

答:
Here's how to do the conversion part, ask a new question if you still need help with the ssh part:

```<code>$ cat tst.awk
BEGIN { FS=","; OFS="=" }
NR==1 {
    for (i=1; i<=NF; i++) {
        name[i] = $i
    }
    next
}
{
    for (i=1; i<=NF; i++) {
        print name[i], $i
    }
    print ""
}
</code>```

.

```<code>$ awk -f tst.awk file
ip_address=192.168.1.1
name=ABC
address=Delhi
phone=1234567
email_id=abc@gmail.com

ip_address=192.168.1.2
name=MNO
address=Bangalore
phone=1234567
email_id=mno@gmail.com

ip_address=192.168.1.3
name=CDE
address=Pune
phone=1234567
email_id=cde@gmail.com

ip_address=192.168.1.4
name=PQR
address=Mumbai
phone=1234567
email_id=pqr@gmail.com

ip_address=192.168.1.5
name=XYZ
address=Noida
phone=1234567
email_id=xyz@gmail.com
</code>```

Body:
I am quite new to shell script and in the starting phase only I have a interested case. So the case is like I have a csv file that contains the data like:

ip_address,name,address,phone,email_id
192.168.1.1,ABC,Delhi,1234567,abc@gmail.com
192.168.1.2,MNO,Bangalore,1234567,mno@gmail.com
192.168.1.3,CDE,Pune,1234567,cde@gmail.com
192.168.1.4,PQR,Mumbai,1234567,pqr@gmail.com
192.168.1.5,XYZ,Noida,1234567,xyz@gmail.com

How can I write a shell script that will login to the server(192.168.1.1, 192.168.1.2 and so on) and shell script should create .rxt file on that particular server inside /root directory and put the respective data to that rxt file like the below?

(i.e we can create directory like /root/data and inside this data we can put our rxt file as details.rxt)

ip_address=192.168.1.1
name=ABC
address=Delhi
phone=1234567
email_id=abc@gmail.com

ip_address=192.168.1.2
name=MNO
address=Bangalore
phone=1234567
email_id=mno@gmail.com

and so on.

EDIT:

I am trying to read the data from csv file like:

INPUT=serverdetails.csv
OLDIFS=$IFS
IFS=“,”
[ ! -f $INPUT ] && { echo "$INPUT file not found"; exit 99}
while read ip_address name address phone email_id
do
  echo “IPAddress = $ip_address”
  echo “Name = $name”
  echo “Address = $address”
  echo "Telephone = $phone”
  echo “EmailID = $email_id”
done < $INPUT
IFS=$OLDIFS

Body:
Here's how to do the conversion part, ask a new question if you still need help with the ssh part:

$ cat tst.awk
BEGIN { FS=","; OFS="=" }
NR==1 {
    for (i=1; i<=NF; i++) {
        name[i] = $i
    }
    next
}
{
    for (i=1; i<=NF; i++) {
        print name[i], $i
    }
    print ""
}

.

$ awk -f tst.awk file
ip_address=192.168.1.1
name=ABC
address=Delhi
phone=1234567
email_id=abc@gmail.com

ip_address=192.168.1.2
name=MNO
address=Bangalore
phone=1234567
email_id=mno@gmail.com

ip_address=192.168.1.3
name=CDE
address=Pune
phone=1234567
email_id=cde@gmail.com

ip_address=192.168.1.4
name=PQR
address=Mumbai
phone=1234567
email_id=pqr@gmail.com

ip_address=192.168.1.5
name=XYZ
address=Noida
phone=1234567
email_id=xyz@gmail.com


问:
Setting up PeerJS With GAE
I'm unable to make peerjs connect to my server. I have setup a GAE-app with the peerjs-server running on it. The server is running fine since I can go the the peerjs endpoint and get the default response ({"name":"PeerJS Server" etc... ).

However, I'm unable to connect to that server from a loca file.

In my file, I have setup the following code:

```<code>        const peer = new Peer(peer_id, {host: '[somepath].appspot.com', path: '/p2p-broker'});

        peer.on('open', (id)=>{
            console.log('Peer id: ' + id);
        });
</code>```

In theory, peer.on('open', ... should trigger immediately, right? I don't get any action at all. I have setup connection callbacks on my server side that inform of new connections (tested locally!) through the terminal, but those don't trigger on in the GAE version at all.

I've tried getting the port on which my peerjs server is running through logs, and including that info in the Peer-constructor, but this immediately throws an error (apart from not working through the browser either).

I'm pretty sure there is no connection happening whatsoever.

What am I doing wrong? What port do I have to specify?

答:
If you have access the endpoint with the browser, is that with https:? If so, it's on port 443.

It's quite possible that port gets routed to port 8080 on the docker instance itself (by something like NGINX).

Not sure if you need to open additional ports so that your app can work, or if you can just use port 443 (although it needs to talk over https, which is a different protocol)

Title: Setting up PeerJS With GAE

Body:
I'm unable to make peerjs connect to my server. I have setup a GAE-app with the peerjs-server running on it. The server is running fine since I can go the the peerjs endpoint and get the default response ({"name":"PeerJS Server" etc... ).

However, I'm unable to connect to that server from a loca file.

In my file, I have setup the following code:

        const peer = new Peer(peer_id, {host: '[somepath].appspot.com', path: '/p2p-broker'});

        peer.on('open', (id)=>{
            console.log('Peer id: ' + id);
        });

In theory, peer.on('open', ... should trigger immediately, right? I don't get any action at all. I have setup connection callbacks on my server side that inform of new connections (tested locally!) through the terminal, but those don't trigger on in the GAE version at all.

I've tried getting the port on which my peerjs server is running through logs, and including that info in the Peer-constructor, but this immediately throws an error (apart from not working through the browser either).

I'm pretty sure there is no connection happening whatsoever.

What am I doing wrong? What port do I have to specify?


问:
Start Bar Shows Up Over Maximized Form (Pocket PC 2003)

Environment

Windows XP SP3 x32

Visual Studio 2005 Standard

Windows Mobile/Pocket PC 2003

.NET Compact Framework 1.0 SP3 and .NET Framework 1.1

Honeywell Dolphin 9500 Handheld Barcode Scanner

Goal

I have a three form application and an external class (Program.cs) that has the application entry point, Main().  The main form loads first and then, from within MainForm_Load(...), instantiates/shows a new form kind of like a splash screen.  I want all three forms to be maximized. All three forms have the following properties set:

this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;

this.WindowState = System.Windows.Forms.FormWindowState.Maximized;

this.ControlBox = false;

Problem

The "splash screen" form shows up full screen without any issue.  I then dispose of it and show the main screen (first to load and the param for Application.Run();.  From the main screen, once a list box SelectedIndexChanged event is detected, a third form is shown (leaving the main form behind said third form).  That third form shows the task bar over the top portion of my form:
Upon closing this form, the main form now has the task bar overlayed as well.

Code

Friend paste links.  Let me know if I should just post the code here.  WorkOrderView is over a thousand lines so I figured this would be easier.

"Main" Form (WorkOrders.cs)

"Third" Form (WorkOrderView.cs) - Pictured above

Unrelated Suggestions

I am quite a green programmer and I especially lack experience in this environment.  So, if you have any suggestions/criticisms on the way I'm doing some things, don't hesitate to hit me with them.  Probably best to just comment on the post instead of posting an answer for those types of replies.

Thanks!

答:
What you're after is usually referred to as "kiosk mode" (which may help your search engine results).

The underlying issue is that the start bar is not part of your app - it's part of the Shell app and you're competing with it for desired behavior.  What you want is something the Platform is trying to prevent you from doing, so you have to be prepared to put your developer boot on the platform's neck to get it to behave.

This blog entry is a really good starting point for this issue and will probably give you what you need, but feel free to use a search engine to find more/aternate proposals. There's actually a lot of material on the web for this - more than would belong in this answer.


问:
Does Python Pytest have anything similiar to Java TestNG DataProvider? How does Pytest Handle Excel Data?
Updated the question and code again to reflect recent changes. Amit I tried your suggestion and I encountered an error. Trying to get openpyxl to read date from each excel sheet in a workbook by passing a testname in, but it keep failing with can't find testname fixture. Can you advise where I went wrong? Thanks. </p>

```<code>  import pytest
  from base.webdriverFactory import WebDriverFactory
  from pages.webpages.login.login_page import LoginPage
  from utilities.excel_utils import ExcelUtils as excelutils

@pytest.fixture(scope="class")
def get_excel_data(testName):
    datafile = "../testdata/TestData.xlsx"
    data = excelutils.get_input_rows(datafile, testName)
    for row in data:
        yield row

     from base.webdriverFactory import WebDriverFactory
from pages.webpages.login.login_page import LoginPage
from utilities.teststatus import TestStatus
from utilities.read_excel import ReadExcel
import unittest, pytest
import utilities.custom_logger as cl
import logging
import inspect

@pytest.mark.usefixtures("setUp", "get_excel_data")
class LoginTests(unittest.TestCase):
    log = cl.customLogger(logging.DEBUG)
    data=""

    @pytest.fixture(autouse=True)
    def classSetup(self, setUp, get_excel_data):
        self.wdf = WebDriverFactory(self.browser, self.os, self.thisdir)
        self.lp = LoginPage(self.driver)
        self.ts = TestStatus(self.driver)
        self.ex = ReadExcel(self.driver)
        data = self.get_excel_data(testName="test_invalidLoginWrongEmail")

    @pytest.mark.run(order=1)
    def test_invalidLoginBlank(self):
        self.log.info("++++++++++++++++++++++++++++++++++++STARTING test_invalidLoginBlank++++++++++++++++++++++++++++++++++++")
        self.lp.clickSignInLink()
        self.lp.blankLogin()
        result = self.lp.verifyBlankLogin()
        assert result == True #Verify login failed is true
        self.ts.markFinal("test_invalidLoginBlank", result, "Verify Can't Login with Blank Fields")
        self.log.info("++++++++++++++++++++++++++++++++++++ENDING test_invalidLoginBlank++++++++++++++++++++++++++++++++++++")

    @pytest.mark.run(order=2)
    @pytest.mark.parametrize("email, password", data)
    def test_invalidLoginWrongEmail(self, email, password):
        self.log.info("++++++++++++++++++++++++++++++++++++STARTING test_invalidLoginWrongEmail++++++++++++++++++++++++++++++++++++")
        self.lp.wrongLogin(email, password)
        browser1 = self.wdf.browser
        result = self.lp.verifyWrongLogin(testbrowser=browser1)
        assert result == True # Verify login failed is True
        self.ts.markFinal("test_invalidLoginWrongEmail", result, "Verify Can't Login with Wrong Email")
        self.log.info("++++++++++++++++++++++++++++++++++++ENDING test_invalidLoginWrongEmail++++++++++++++++++++++++++++++++++++")

from openpyxl import load_workbook

class ExcelUtils():

def __init__(self, driver):
    self.driver = driver

def get_input_rows(self, datafile, testName):

    wb = load_workbook(filename=datafile)

    sheet = wb.active

    # List sheets available
    sheets = wb.get_sheet_names()
    for i in sheets:
        if i == testName:
            sheet = i
    self.log.info("Got active sheet.")

    row_list = []

    # Get second row as the headers' values
    rows2 = sheet.iter_rows(min_row=2, max_row=2)
    secondrowvalues = next(rows2)
    for d in secondrowvalues:
        row_list.append(d.value)

    return row_list
</code>```

答:
You can create another function(or fixture) in which you can read the excel & yield the dictionary elements. Then you can use @pytest.mark.parametrize to run a test for each element in the dictionary.

Here's a similar example where function returns rows from excel, then test is run for each row using @pytest.mark.parametrize

```<code>def get_data():
    data = ExcelUtils("inputData.xlsx", "SheetName").get_input_rows()
    for row in data:
        yield row

@pytest.mark.parametrize("test_input", get_data())
def test_for_all_input_rows(test_input):
    print(test_input)
</code>```

Body:
Updated the question and code again to reflect recent changes. Amit I tried your suggestion and I encountered an error. Trying to get openpyxl to read date from each excel sheet in a workbook by passing a testname in, but it keep failing with can't find testname fixture. Can you advise where I went wrong? Thanks.

  import pytest
  from base.webdriverFactory import WebDriverFactory
  from pages.webpages.login.login_page import LoginPage
  from utilities.excel_utils import ExcelUtils as excelutils

@pytest.fixture(scope="class")
def get_excel_data(testName):
    datafile = "../testdata/TestData.xlsx"
    data = excelutils.get_input_rows(datafile, testName)
    for row in data:
        yield row

     from base.webdriverFactory import WebDriverFactory
from pages.webpages.login.login_page import LoginPage
from utilities.teststatus import TestStatus
from utilities.read_excel import ReadExcel
import unittest, pytest
import utilities.custom_logger as cl
import logging
import inspect

@pytest.mark.usefixtures("setUp", "get_excel_data")
class LoginTests(unittest.TestCase):
    log = cl.customLogger(logging.DEBUG)
    data=""

    @pytest.fixture(autouse=True)
    def classSetup(self, setUp, get_excel_data):
        self.wdf = WebDriverFactory(self.browser, self.os, self.thisdir)
        self.lp = LoginPage(self.driver)
        self.ts = TestStatus(self.driver)
        self.ex = ReadExcel(self.driver)
        data = self.get_excel_data(testName="test_invalidLoginWrongEmail")

    @pytest.mark.run(order=1)
    def test_invalidLoginBlank(self):
        self.log.info("++++++++++++++++++++++++++++++++++++STARTING test_invalidLoginBlank++++++++++++++++++++++++++++++++++++")
        self.lp.clickSignInLink()
        self.lp.blankLogin()
        result = self.lp.verifyBlankLogin()
        assert result == True #Verify login failed is true
        self.ts.markFinal("test_invalidLoginBlank", result, "Verify Can't Login with Blank Fields")
        self.log.info("++++++++++++++++++++++++++++++++++++ENDING test_invalidLoginBlank++++++++++++++++++++++++++++++++++++")

    @pytest.mark.run(order=2)
    @pytest.mark.parametrize("email, password", data)
    def test_invalidLoginWrongEmail(self, email, password):
        self.log.info("++++++++++++++++++++++++++++++++++++STARTING test_invalidLoginWrongEmail++++++++++++++++++++++++++++++++++++")
        self.lp.wrongLogin(email, password)
        browser1 = self.wdf.browser
        result = self.lp.verifyWrongLogin(testbrowser=browser1)
        assert result == True # Verify login failed is True
        self.ts.markFinal("test_invalidLoginWrongEmail", result, "Verify Can't Login with Wrong Email")
        self.log.info("++++++++++++++++++++++++++++++++++++ENDING test_invalidLoginWrongEmail++++++++++++++++++++++++++++++++++++")

from openpyxl import load_workbook

class ExcelUtils():

def __init__(self, driver):
    self.driver = driver

def get_input_rows(self, datafile, testName):

    wb = load_workbook(filename=datafile)

    sheet = wb.active

    # List sheets available
    sheets = wb.get_sheet_names()
    for i in sheets:
        if i == testName:
            sheet = i
    self.log.info("Got active sheet.")

    row_list = []

    # Get second row as the headers' values
    rows2 = sheet.iter_rows(min_row=2, max_row=2)
    secondrowvalues = next(rows2)
    for d in secondrowvalues:
        row_list.append(d.value)

    return row_list

Body:
You can create another function(or fixture) in which you can read the excel & yield the dictionary elements. Then you can use @pytest.mark.parametrize to run a test for each element in the dictionary.

Here's a similar example where function returns rows from excel, then test is run for each row using @pytest.mark.parametrize

def get_data():
    data = ExcelUtils("inputData.xlsx", "SheetName").get_input_rows()
    for row in data:
        yield row

@pytest.mark.parametrize("test_input", get_data())
def test_for_all_input_rows(test_input):
    print(test_input)


问:
Buttons and inputs are not displayed on Modal
Buttons are inputs fields are not getting displayed on modal inside .aspx page but labels are visible

                    <button type="button" class="close" data-dismiss="modal">×Close</button>

Filter

                                            By Number
                                            <input id="txt_filter_number" name="txt_filter_number" type="text" class="form-control" runat="server" />

                            <button type="button" class="btn btn-white" data-dismiss="modal">Close</button>
                            <button type="button" class="btn btn-primary">Apply</button>

```

Output (missing buttons and input fields):

答:
I tried the same html for the modal popup that you reported and its working perfectly. I think you are missing css or other css are hiding your modal elements. have a look here:

    function showModal()
    {
        $('#mdl_filter').modal('show');
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Bootstrap 101 Template</title>

    <!-- Bootstrap -->
    <link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet">

    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
  </head>
  <body>
      <input type="button" id="btnShow" onclick="showModal();" value="Show Modal"/>
   <div class="modal inmodal" id="mdl_filter" tabindex="-1" role="dialog" aria-hidden="true" style="position: absolute;">
        <div class="modal-dialog  modal-lg">
            <div class="modal-content animated bounceInRight">
                <div class="modal-header" style="height: 55px; padding-top: 10px">
                    <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
                    <h4 class="modal-title">Filter</h4>
                </div>
                <div class="modal-body">
                    <div class="tab-content">
                        <div class="space-10"></div>
                        <div id="filter_form" class="wizard-big filter_form">
                            <div class="step-content">
                                <div class="row">
                                    <div class="col-lg-8">
                                        <div class="form-group">
                                            <label>By Number</label>
                                            <input id="txt_filter_number" name="txt_filter_number" type="text" class="form-control" runat="server" />
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-white" data-dismiss="modal">Close</button>
                            <button type="button" class="btn btn-primary">Apply</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <!-- Include all compiled plugins (below), or include individual files as needed -->
    <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>

  </body>
</html></code>```

Body:
Buttons are inputs fields are not getting displayed on modal inside .aspx page but labels are visible

                    <button type="button" class="close" data-dismiss="modal">×Close</button>

Filter

                                            By Number
                                            <input id="txt_filter_number" name="txt_filter_number" type="text" class="form-control" runat="server" />

                            <button type="button" class="btn btn-white" data-dismiss="modal">Close</button>
                            <button type="button" class="btn btn-primary">Apply</button>

Output (missing buttons and input fields):

Body:
I tried the same html for the modal popup that you reported and its working perfectly. I think you are missing css or other css are hiding your modal elements. have a look here:

    function showModal()
    {
        $('#mdl_filter').modal('show');
    }

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Bootstrap 101 Template</title>

    <!-- Bootstrap -->
    <link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet">

    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
  </head>
  <body>
      <input type="button" id="btnShow" onclick="showModal();" value="Show Modal"/>
   <div class="modal inmodal" id="mdl_filter" tabindex="-1" role="dialog" aria-hidden="true" style="position: absolute;">
        <div class="modal-dialog  modal-lg">
            <div class="modal-content animated bounceInRight">
                <div class="modal-header" style="height: 55px; padding-top: 10px">
                    <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
                    <h4 class="modal-title">Filter</h4>
                </div>
                <div class="modal-body">
                    <div class="tab-content">
                        <div class="space-10"></div>
                        <div id="filter_form" class="wizard-big filter_form">
                            <div class="step-content">
                                <div class="row">
                                    <div class="col-lg-8">
                                        <div class="form-group">
                                            <label>By Number</label>
                                            <input id="txt_filter_number" name="txt_filter_number" type="text" class="form-control" runat="server" />
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-white" data-dismiss="modal">Close</button>
                            <button type="button" class="btn btn-primary">Apply</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <!-- Include all compiled plugins (below), or include individual files as needed -->
    <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>

  </body>
</html>


问:
Ember : debounce called multiple times on scroll event listener
I added a debounce method inside a scroll event listener. Something like this.

```<code>$group.on("scroll.topFix",() => {
   console.log('scroll event');
   debounce(this, ()=> {
     console.log('debounce called);
   },1000);
});
</code>```

When I do the scroll on $group the debounce is also called the same number of times the scroll event called. I don't know where is the loophole in this thing.

For example, if 5 times the scroll event printed then debounce called is also called 5 times.

This is the link for ember debounce documentation.

答:
This approach is working for me...

```<code>$group.on("scroll.topFix",() => {
  console.log('scroll event');
  debounce(this, scrollfunction},1000);
});

let scrollfunction = () => {
   console.log('debounce called);
};
</code>```

When scroll event triggers 4 times at the same time debounce called is called only one time.

Body:
I added a debounce method inside a scroll event listener. Something like this.

$group.on("scroll.topFix",() => {
   console.log('scroll event');
   debounce(this, ()=> {
     console.log('debounce called);
   },1000);
});

When I do the scroll on $group the debounce is also called the same number of times the scroll event called. I don't know where is the loophole in this thing.

For example, if 5 times the scroll event printed then debounce called is also called 5 times.

This is the link for ember debounce documentation.

Body:
This approach is working for me...

$group.on("scroll.topFix",() => {
  console.log('scroll event');
  debounce(this, scrollfunction},1000);
});

let scrollfunction = () => {
   console.log('debounce called);
};

When scroll event triggers 4 times at the same time debounce called is called only one time.


答:
You can use Event.stopPropagation() on button click:

$('#my_table tbody').on( 'click', 'tr', function () {
  $(this).toggleClass('selected');
} );
$('#my_table tbody').on( 'click', 'button', function (e) {
  e.stopPropagation();
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.selected{
  background-color: red;
}</code>```

    Item
    Amount
    Action

    Apple
    10
    <button>[Buy]</button><button>[Delete]</button>

    Banana
    5
    <button>[Buy]</button><button>[Delete]</button>

    Orange
    14
    <button>[Buy]</button><button>[Delete]</button>

```

Body:
When you click on a table row it adds a class that changes it's appearance to reflect it's selected.

    $('#my_table tbody').on( 'click', 'tr', function () {
        $(this).toggleClass('selected');
    } );

However, I also have some buttons in a column that let you do things specific to the row:

Item    Amount    Action
--------------------------------
Apple   10        [Buy] [Delete]
Banana  5         [Buy] [Delete]
Orange  14        [Buy] [Delete]

When I click one of the individual buttons, it also triggers the table row '.selected' class to be added, but I don't want this to occur when clicking buttons.

Body:
You can use Event.stopPropagation() on button click:

$('#my_table tbody').on( 'click', 'tr', function () {
  $(this).toggleClass('selected');
} );
$('#my_table tbody').on( 'click', 'button', function (e) {
  e.stopPropagation();
});

.selected{
  background-color: red;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="my_table">
  <thead>
    <th>Item</th>
    <th>Amount</th>
    <th>Action</th>
  </thead>
  <tbody>
  <tr>
    <td>Apple</td>
    <td>10</td>
    <td><button>[Buy]</button><button>[Delete]</button></td>
  </tr>
  <tr>
    <td>Banana</td>
    <td>5</td>
    <td><button>[Buy]</button><button>[Delete]</button></td>
  </tr>
  <tr>
    <td>Orange</td>
    <td>14</td>
    <td><button>[Buy]</button><button>[Delete]</button></td>
  </tr>
  </tbody>
</table>


问:
jest/enzyme test: this.props.showOverlay is not a function
I have a small test that simulates a click (hoping to do more with the test, but this is where I'm stuck so far):

```<code>import React from 'react';
import Enzyme, { mount } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import HamburgerIcon from './HamburgerIcon';

Enzyme.configure({ adapter: new Adapter() });

test('hamburger icon changes class and state on click', () => {
  const wrapper = mount(<HamburgerIcon />);
  const hamburgerIcon = wrapper.find('div#mobile-nav');

  hamburgerIcon.simulate('click');
});
</code>```

When running this test, I get the error:

TypeError: this.props.showOverlay is not a function

After doing some reading, I've realized that this isn't working because the simulated click calls a function that is two levels up from the component that is being tested (HamburgerIcon).

When I first tried to run this, I was using Enzyme's shallow, and I since changed it to mount thinking that this would give the test access to the showOverlay function, but I was wrong.

Then I read that this might be a good use case for a mock function, and I tried to start implementing this:

```<code>...

const showOverlay = jest.fn();
// how to set this.props.ShowOverlay to the const above??

test('has div with class .closed', () => {
  const wrapper = mount(<HamburgerIcon />);
  const hamburgerIcon = wrapper.find('div#mobile-nav');

  hamburgerIcon.simulate('click');
});
</code>```

This is where I am sort of lost -- I'm not sure if mock functions are the right direction here, and I'm also not sure how the syntax of setting up the mock function will work.

答:
Continue with shallow if you're just unit testing a single component. If this component is nested and you're testing against child nodes, then you'll mount the parent.

That said, you're on the right track for using a mock function. Simply pass it into the component like so:

<HamburgerIcon showOverlay={showOverlay} />

For example:

```<code>const showOverlay = jest.fn();

test('shows an overlay', () => {
  const wrapper = mount(<HamburgerIcon showOverlay={showOverlay} />);
  const hamburgerIcon = wrapper.find('div#mobile-nav');

  hamburgerIcon.simulate('click');
  expect(showOverlay).toHaveBeenCalled();
});
</code>```

If you have multiple props, then I like to do something more declarative:

```<code>// define props here if you want an easy way check if they've been
// called (since we're defining at the top-level, all tests have access
// to this function)
const showOverlay = jest.fn();

// then include them in an "initialProps" object (you can also just define
// them within this object as well, but you'll have to use
// "initialProps.nameOfFunction" to check if they're called -- kind of
// repetitive if you have a lot of props that you're checking against)
const initialProps = {
  showOverlay,
  someOtherFunction: jest.fn()
}

// use the spread syntax to pass all the props in the "initialProps" object
// to the component
test('shows an overlay', () => {
  const wrapper = mount(<HamburgerIcon { ...initialProps } />);
  const hamburgerIcon = wrapper.find('div#mobile-nav');

  hamburgerIcon.simulate('click');

  expect(showOverlay).toHaveBeenCalled(); // here we can just use the mock function name
  expect(initialProps.someOtherFunction).toHaveBeenCalledTimes(0); // here we'll have to use "initialProps.property" because it has been scoped to the object
});
</code>```

Body:
I have a small test that simulates a click (hoping to do more with the test, but this is where I'm stuck so far):

import React from 'react';
import Enzyme, { mount } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import HamburgerIcon from './HamburgerIcon';

Enzyme.configure({ adapter: new Adapter() });

test('hamburger icon changes class and state on click', () => {
  const wrapper = mount(<HamburgerIcon />);
  const hamburgerIcon = wrapper.find('div#mobile-nav');

  hamburgerIcon.simulate('click');
});

When running this test, I get the error:

TypeError: this.props.showOverlay is not a function

After doing some reading, I've realized that this isn't working because the simulated click calls a function that is two levels up from the component that is being tested (HamburgerIcon).

When I first tried to run this, I was using Enzyme's shallow, and I since changed it to mount thinking that this would give the test access to the showOverlay function, but I was wrong.

Then I read that this might be a good use case for a mock function, and I tried to start implementing this:

...

const showOverlay = jest.fn();
// how to set this.props.ShowOverlay to the const above??

test('has div with class .closed', () => {
  const wrapper = mount(<HamburgerIcon />);
  const hamburgerIcon = wrapper.find('div#mobile-nav');

  hamburgerIcon.simulate('click');
});

This is where I am sort of lost -- I'm not sure if mock functions are the right direction here, and I'm also not sure how the syntax of setting up the mock function will work.

Body:
Continue with shallow if you're just unit testing a single component. If this component is nested and you're testing against child nodes, then you'll mount the parent.

That said, you're on the right track for using a mock function. Simply pass it into the component like so:

<HamburgerIcon showOverlay={showOverlay} />

For example:

const showOverlay = jest.fn();

test('shows an overlay', () => {
  const wrapper = mount(<HamburgerIcon showOverlay={showOverlay} />);
  const hamburgerIcon = wrapper.find('div#mobile-nav');

  hamburgerIcon.simulate('click');
  expect(showOverlay).toHaveBeenCalled();
});

If you have multiple props, then I like to do something more declarative:

// define props here if you want an easy way check if they've been
// called (since we're defining at the top-level, all tests have access
// to this function)
const showOverlay = jest.fn();

// then include them in an "initialProps" object (you can also just define
// them within this object as well, but you'll have to use
// "initialProps.nameOfFunction" to check if they're called -- kind of
// repetitive if you have a lot of props that you're checking against)
const initialProps = {
  showOverlay,
  someOtherFunction: jest.fn()
}

// use the spread syntax to pass all the props in the "initialProps" object
// to the component
test('shows an overlay', () => {
  const wrapper = mount(<HamburgerIcon { ...initialProps } />);
  const hamburgerIcon = wrapper.find('div#mobile-nav');

  hamburgerIcon.simulate('click');

  expect(showOverlay).toHaveBeenCalled(); // here we can just use the mock function name
  expect(initialProps.someOtherFunction).toHaveBeenCalledTimes(0); // here we'll have to use "initialProps.property" because it has been scoped to the object
});


问:
Adding google maps markers by an address instead of coordinates?
In my Flex project, can I add markers by its address instead of this:

```<code>var myGeographicCoordinates:LatLng = new LatLng(myLatitude, myLongitude);
</code>```

for example add marker by "Paris, France"

答: You should read Google's developer manual on Geocoding.  It explains how to convert an address to a geolocation.  I recommend you try looking at the Dev manual/API/Google before posting here.</p>

Body:
In my Flex project, can I add markers by its address instead of this:

var myGeographicCoordinates:LatLng = new LatLng(myLatitude, myLongitude);

for example add marker by "Paris, France"