问:
Run multiple python scripts, that use user inputs and while loops, simultaneously
Basically I need to run three files simultaneously and independently. These files are started with a user input followed by an infinite While Loop.

I have found some questions similar to mine but the solutions do not quite fit my needs. I am still a beginner.

I have already tried:

```<code>python device1.py &
python device2.py &
python device3.py

</code>```

I also tried doing this all in one file but the file is rather large and complicated, and have not succeeded thus far.

#some code that creates a csv

#input
device = input("input which device you want to connect to")

def function():
    #write to csv file from data

while True:
    #get live data from device

    #csv function
    function()

```

I expect to enter 3 inputs for my 3 scripts, they run their loops, I end the code and have 3 csv files.

答:
Have you tried setting the input in your command?

```<code>echo inputForDevice1 | python device1.py &
echo inputForDevice2 | python device2.py &
echo inputForDevice3 | python device3.py &
</code>```

Also remember to detach from the last python call (python device3.py &), otherwise you'll be stuck in the infinite loop.

Body:
Basically I need to run three files simultaneously and independently. These files are started with a user input followed by an infinite While Loop.

I have found some questions similar to mine but the solutions do not quite fit my needs. I am still a beginner.

I have already tried:

python device1.py &
python device2.py &
python device3.py

I also tried doing this all in one file but the file is rather large and complicated, and have not succeeded thus far.

#some code that creates a csv

#input
device = input("input which device you want to connect to")

def function():
    #write to csv file from data

while True:
    #get live data from device

    #csv function
    function()

I expect to enter 3 inputs for my 3 scripts, they run their loops, I end the code and have 3 csv files.

Body:
Have you tried setting the input in your command?

echo inputForDevice1 | python device1.py &
echo inputForDevice2 | python device2.py &
echo inputForDevice3 | python device3.py &

Also remember to detach from the last python call (python device3.py &), otherwise you'll be stuck in the infinite loop.


来源: stackexchange

问:
Using booleans with set and get methods
To summarize I am making a program for a metro ticket system. and I am using set and get methods for it, when it comes to boolean values (since I need to validate that the person enters enough money for the ticket) how am i supposed to put in the main class( it is defined in brain) using the set method and an if statement.Here is a little fraction of the entire code and the rest is on github(https://github.com/alexxei4/subwayticket). The main is basically the class that will be used for interaction with the user and the brain is where alot of the actions are defined.All help is appreciated, please and thank you.</p>

```<code> if (Choice1a == 10){
            if(subway1.ticketcounter1(true);){
                System.out.println("PRINT SUCCESSFUL, COLLECT YOUR TICKET!");
            }
            if(subway1.ticketcounter1(false);){
                System.out.println("INSEFFICIENT FUNDS, PLEASE ADD MORE");
            }
</code>```

答:
You code is like this

```<code> public void ticketcounter1(boolean ticketcounter1){
    if (credit1 > total1){
        ticketcounter1 = true;
    }
    else {
        ticketcounter1 = false;
    }
}
public void ticketcounter2(boolean ticketcounter2) {
    if (credit2 > total2){
        ticketcounter2 = true;
    }
    else {
        ticketcounter2= false;
    }
}
</code>```

It should be like this. Instead of using the variable and passing it though parameter. Use getter. Besides that your code won't run since subway1.ticketcounter1(true) is giving nothing. It is only changing variables stored in Brain.java. No information is being sent to main.

```<code> public boolean ticketcounter1(){
    if (credit1 > total1){
        return true;
    }
    else {
        return false;
    }
}
public boolean ticketcounter2(){
    if (credit2 > total2){
       return true;
    }
    else {
        return false;
    }
}
</code>```

You can create functions without parameters. I don't know what were you trying to do?

```<code>if (Choice1a == 10){
   if(subway1.ticketcounter1()){
       System.out.println("PRINT SUCCESSFUL, COLLECT YOUR TICKET!");
   }
   if(subway1.ticketcounter1()){
       System.out.println("INSEFFICIENT FUNDS, PLEASE ADD MORE");
   }
}
</code>```

subway1.ticketcounter1() will give either true and false. Do not use ; in if statement condition. ; ends the statement. Check this guide to learn about use of semi-colon If you do want to use ; The code should look like this

```<code>if (Choice1a == 10){
   boolean ticketCounter1 = subway1.ticketcounter1();
   if(ticketCounter1){
      System.out.println("PRINT SUCCESSFUL, COLLECT YOUR TICKET!");
   } else {
      System.out.println("INSEFFICIENT FUNDS, PLEASE ADD MORE");
   }
 }
</code>```

P.S You don't need two ifs if-else would be better in this case

```<code>if(condition) {
// Conditions is true
} else {
// Condition is false
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Using booleans with set and get methods

Body:
To summarize I am making a program for a metro ticket system. and I am using set and get methods for it, when it comes to boolean values (since I need to validate that the person enters enough money for the ticket) how am i supposed to put in the main class( it is defined in brain) using the set method and an if statement.Here is a little fraction of the entire code and the rest is on github(https://github.com/alexxei4/subwayticket). The main is basically the class that will be used for interaction with the user and the brain is where alot of the actions are defined.All help is appreciated, please and thank you.

 if (Choice1a == 10){
            if(subway1.ticketcounter1(true);){
                System.out.println("PRINT SUCCESSFUL, COLLECT YOUR TICKET!");
            }
            if(subway1.ticketcounter1(false);){
                System.out.println("INSEFFICIENT FUNDS, PLEASE ADD MORE");
            }

Body:
You code is like this

 public void ticketcounter1(boolean ticketcounter1){
    if (credit1 > total1){
        ticketcounter1 = true;
    }
    else {
        ticketcounter1 = false;
    }
}
public void ticketcounter2(boolean ticketcounter2) {
    if (credit2 > total2){
        ticketcounter2 = true;
    }
    else {
        ticketcounter2= false;
    }
}

It should be like this. Instead of using the variable and passing it though parameter. Use getter. Besides that your code won't run since subway1.ticketcounter1(true) is giving nothing. It is only changing variables stored in Brain.java. No information is being sent to main.

 public boolean ticketcounter1(){
    if (credit1 > total1){
        return true;
    }
    else {
        return false;
    }
}
public boolean ticketcounter2(){
    if (credit2 > total2){
       return true;
    }
    else {
        return false;
    }
}

You can create functions without parameters. I don't know what were you trying to do?

if (Choice1a == 10){
   if(subway1.ticketcounter1()){
       System.out.println("PRINT SUCCESSFUL, COLLECT YOUR TICKET!");
   }
   if(subway1.ticketcounter1()){
       System.out.println("INSEFFICIENT FUNDS, PLEASE ADD MORE");
   }
}

subway1.ticketcounter1() will give either true and false. Do not use ; in if statement condition. ; ends the statement. Check this guide to learn about use of semi-colon If you do want to use ; The code should look like this

if (Choice1a == 10){
   boolean ticketCounter1 = subway1.ticketcounter1();
   if(ticketCounter1){
      System.out.println("PRINT SUCCESSFUL, COLLECT YOUR TICKET!");
   } else {
      System.out.println("INSEFFICIENT FUNDS, PLEASE ADD MORE");
   }
 }

P.S You don't need two ifs if-else would be better in this case

if(condition) {
// Conditions is true
} else {
// Condition is false
}


问:
How to fix a view from going off of a page when it is constrained to a card view
I have recently converted over an android project into androidx and I am having issues with trying to stop views going off of the page. My layout is as follows, a Constraint Layout that contains a Card View and a Text View. Within this Card View I have a Constraint Layout that contains the Text View. Outside of the Card View I have a Button which is constrained to the Card View.

The issue with this is that when I run the program the Card View goes off of the screen and the button moves all the way to the top even though they are all constrained properly.

I will show below the code I am using to achieve this and an image of my result on the emulator.

Here is the layout in the editor [1]: https://imgur.com/a/0FLa1IK

Here is the layout shown on the Emulator [2]: https://imgur.com/a/SsvKiOG

Any help would be greatly appreciated.

```<code><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.cardview.widget.CardView
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginBottom="8dp"
        app:layout_constraintBottom_toTopOf="@+id/materialButton"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <androidx.constraintlayout.widget.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <TextView
                android:layout_width="0dp"
                android:layout_height="0dp"
                android:layout_marginStart="16dp"
                android:layout_marginTop="16dp"
                android:layout_marginEnd="16dp"
                android:layout_marginBottom="16dp"
                android:text="Text View Test"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent" />
        </androidx.constraintlayout.widget.ConstraintLayout>

    </androidx.cardview.widget.CardView>

    <Button
        android:id="@+id/materialButton"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginBottom="256dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

</code>```

答:
please remove this line from button attribute :

```<code>   android:layout_marginBottom="256dp"
</code>```

your are just pushing to button to the top by setting the margin_bottom , and why it's shown on the preview and not on the device just because of the different screen size

Body:
I have recently converted over an android project into androidx and I am having issues with trying to stop views going off of the page. My layout is as follows, a Constraint Layout that contains a Card View and a Text View. Within this Card View I have a Constraint Layout that contains the Text View. Outside of the Card View I have a Button which is constrained to the Card View.

The issue with this is that when I run the program the Card View goes off of the screen and the button moves all the way to the top even though they are all constrained properly.

I will show below the code I am using to achieve this and an image of my result on the emulator.

Here is the layout in the editor [1]: https://imgur.com/a/0FLa1IK

Here is the layout shown on the Emulator [2]: https://imgur.com/a/SsvKiOG

Any help would be greatly appreciated.

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.cardview.widget.CardView
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginBottom="8dp"
        app:layout_constraintBottom_toTopOf="@+id/materialButton"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <androidx.constraintlayout.widget.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <TextView
                android:layout_width="0dp"
                android:layout_height="0dp"
                android:layout_marginStart="16dp"
                android:layout_marginTop="16dp"
                android:layout_marginEnd="16dp"
                android:layout_marginBottom="16dp"
                android:text="Text View Test"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent" />
        </androidx.constraintlayout.widget.ConstraintLayout>

    </androidx.cardview.widget.CardView>

    <Button
        android:id="@+id/materialButton"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginBottom="256dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

Body:
please remove this line from button attribute :

   android:layout_marginBottom="256dp"

your are just pushing to button to the top by setting the margin_bottom , and why it's shown on the preview and not on the device just because of the different screen size


问:
Matplotlib dot plot with two categorical variables
I would like to produce a specific type of visualization, consisting of a rather simple dot plot but with a twist: both of the axes are categorical variables (i.e. ordinal or non-numerical values). And this complicates matters instead of making it easier.

To illustrate this question, I will be using a small example dataset that is a modification from seaborn.load_dataset("tips") and defined as such:

```<code>import pandas
from six import StringIO
df = """total_bill |  tip  |    sex | smoker | day |   time | size
             16.99 | 1.01  |   Male |     No | Mon | Dinner |    2
             10.34 | 1.66  |   Male |     No | Sun | Dinner |    3
             21.01 | 3.50  |   Male |     No | Sun | Dinner |    3
             23.68 | 3.31  |   Male |     No | Sun | Dinner |    2
             24.59 | 3.61  | Female |     No | Sun | Dinner |    4
             25.29 | 4.71  | Female |     No | Mon | Lunch  |    4
              8.77 | 2.00  | Female |     No | Tue | Lunch  |    2
             26.88 | 3.12  |   Male |     No | Wed | Lunch  |    4
             15.04 | 3.96  |   Male |     No | Sat | Lunch  |    2
             14.78 | 3.23  |   Male |     No | Sun | Lunch  |    2"""
df = pandas.read_csv(StringIO(df.replace(' ','')), sep="|", header=0)
</code>```

My first approach to produce my graph was to try a call to seaborn as such:

```<code>import seaborn
axes = seaborn.pointplot(x="time", y="sex", data=df)
</code>```

This fails with:

```<code>ValueError: Neither the `x` nor `y` variable appears to be numeric.
</code>```

So does the equivalent seaborn.stripplot and seaborn.swarmplot calls. It does work however if one of the variables is categorical and the other one is numerical. Indeed seaborn.pointplot(x="total_bill", y="sex", data=df) works, but is not what I want.

I also attempted a scatterplot like such:

```<code>axes = seaborn.scatterplot(x="time", y="sex", size="day", data=df,
                           x_jitter=True, y_jitter=True)
</code>```

This produces the following graph which does not contain any jitter and has all the dots overlapping, making it useless:

Do you know of any elegant approach or library that could solve my problem ?

I started writing something myself, which I will include below, but this implementation is suboptimal and limited by the number of points that can overlap at the same spot (currently it fails if more than 4 points overlap).

```<code># Modules #
import seaborn, pandas, matplotlib
from six import StringIO

################################################################################
def amount_to_offets(amount):
    """A function that takes an amount of overlapping points (e.g. 3)
    and returns a list of offsets (jittered) coordinates for each of the
    points.

    It follows the logic that two points are displayed side by side:

    2 ->  * *

    Three points are organized in a triangle

    3 ->   *
          * *

    Four points are sorted into a square, and so on.

    4 ->  * *
          * *
    """
    assert isinstance(amount, int)
    solutions = {
        1: [( 0.0,  0.0)],
        2: [(-0.5,  0.0), ( 0.5,  0.0)],
        3: [(-0.5, -0.5), ( 0.0,  0.5), ( 0.5, -0.5)],
        4: [(-0.5, -0.5), ( 0.5,  0.5), ( 0.5, -0.5), (-0.5,  0.5)],
    }
    return solutions[amount]

################################################################################
class JitterDotplot(object):

    def __init__(self, data, x_col='time', y_col='sex', z_col='tip'):
        self.data = data
        self.x_col = x_col
        self.y_col = y_col
        self.z_col = z_col

    def plot(self, **kwargs):
        # Load data #
        self.df = self.data.copy()

        # Assign numerical values to the categorical data #
        # So that ['Dinner', 'Lunch'] becomes [0, 1] etc. #
        self.x_values = self.df[self.x_col].unique()
        self.y_values = self.df[self.y_col].unique()
        self.x_mapping = dict(zip(self.x_values, range(len(self.x_values))))
        self.y_mapping = dict(zip(self.y_values, range(len(self.y_values))))
        self.df = self.df.replace({self.x_col: self.x_mapping, self.y_col: self.y_mapping})

        # Offset points that are overlapping in the same location #
        # So that (2.0, 3.0) becomes (2.05, 2.95) for instance #
        cols = [self.x_col, self.y_col]
        scaling_factor = 0.05
        for values, df_view in self.df.groupby(cols):
            offsets = amount_to_offets(len(df_view))
            offsets = pandas.DataFrame(offsets, index=df_view.index, columns=cols)
            offsets *= scaling_factor
            self.df.loc[offsets.index, cols] += offsets

        # Plot a standard scatter plot #
        g = seaborn.scatterplot(x=self.x_col, y=self.y_col, size=self.z_col, data=self.df, **kwargs)

        # Force integer ticks on the x and y axes #
        locator = matplotlib.ticker.MaxNLocator(integer=True)
        g.xaxis.set_major_locator(locator)
        g.yaxis.set_major_locator(locator)
        g.grid(False)

        # Expand the axis limits for x and y #
        margin = 0.4
        xmin, xmax, ymin, ymax = g.get_xlim() + g.get_ylim()
        g.set_xlim(xmin-margin, xmax+margin)
        g.set_ylim(ymin-margin, ymax+margin)

        # Replace ticks with the original categorical names #
        g.set_xticklabels([''] + list(self.x_mapping.keys()))
        g.set_yticklabels([''] + list(self.y_mapping.keys()))

        # Return for display in notebooks for instance #
        return g

################################################################################
# Graph #
graph = JitterDotplot(data=df)
axes  = graph.plot()
axes.figure.savefig('jitter_dotplot.png')
</code>```

答:
you could first convert time and sex to categorical type and tweak it a little bit:

```<code>df.sex = pd.Categorical(df.sex)
df.time = pd.Categorical(df.time)

axes = sns.scatterplot(x=df.time.cat.codes+np.random.uniform(-0.1,0.1, len(df)),
                       y=df.sex.cat.codes+np.random.uniform(-0.1,0.1, len(df)),
                       size=df.tip)
</code>```

Output:

With that idea, you can modify the offsets (np.random) in the above code to the respective distance. For example:

```<code># grouping
groups = df.groupby(['time', 'sex'])

# compute the number of samples per group
num_samples = groups.tip.transform('size')

# enumerate the samples within a group
sample_ranks = df.groupby(['time']).cumcount() * (2*np.pi) / num_samples

# compute the offset
x_offsets = np.where(num_samples.eq(1), 0, np.cos(df.sample_rank) * 0.03)
y_offsets = np.where(num_samples.eq(1), 0, np.sin(df.sample_rank) * 0.03)

# plot
axes = sns.scatterplot(x=df.time.cat.codes + x_offsets,
                       y=df.sex.cat.codes + y_offsets,
                       size=df.tip)
</code>```

Output:

Body:
I would like to produce a specific type of visualization, consisting of a rather simple dot plot but with a twist: both of the axes are categorical variables (i.e. ordinal or non-numerical values). And this complicates matters instead of making it easier.

To illustrate this question, I will be using a small example dataset that is a modification from seaborn.load_dataset("tips") and defined as such:

import pandas
from six import StringIO
df = """total_bill |  tip  |    sex | smoker | day |   time | size
             16.99 | 1.01  |   Male |     No | Mon | Dinner |    2
             10.34 | 1.66  |   Male |     No | Sun | Dinner |    3
             21.01 | 3.50  |   Male |     No | Sun | Dinner |    3
             23.68 | 3.31  |   Male |     No | Sun | Dinner |    2
             24.59 | 3.61  | Female |     No | Sun | Dinner |    4
             25.29 | 4.71  | Female |     No | Mon | Lunch  |    4
              8.77 | 2.00  | Female |     No | Tue | Lunch  |    2
             26.88 | 3.12  |   Male |     No | Wed | Lunch  |    4
             15.04 | 3.96  |   Male |     No | Sat | Lunch  |    2
             14.78 | 3.23  |   Male |     No | Sun | Lunch  |    2"""
df = pandas.read_csv(StringIO(df.replace(' ','')), sep="|", header=0)

My first approach to produce my graph was to try a call to seaborn as such:

import seaborn
axes = seaborn.pointplot(x="time", y="sex", data=df)

This fails with:

ValueError: Neither the `x` nor `y` variable appears to be numeric.

So does the equivalent seaborn.stripplot and seaborn.swarmplot calls. It does work however if one of the variables is categorical and the other one is numerical. Indeed seaborn.pointplot(x="total_bill", y="sex", data=df) works, but is not what I want.

I also attempted a scatterplot like such:

axes = seaborn.scatterplot(x="time", y="sex", size="day", data=df,
                           x_jitter=True, y_jitter=True)

This produces the following graph which does not contain any jitter and has all the dots overlapping, making it useless:

Do you know of any elegant approach or library that could solve my problem ?

I started writing something myself, which I will include below, but this implementation is suboptimal and limited by the number of points that can overlap at the same spot (currently it fails if more than 4 points overlap).

# Modules #
import seaborn, pandas, matplotlib
from six import StringIO

################################################################################
def amount_to_offets(amount):
    """A function that takes an amount of overlapping points (e.g. 3)
    and returns a list of offsets (jittered) coordinates for each of the
    points.

    It follows the logic that two points are displayed side by side:

    2 ->  * *

    Three points are organized in a triangle

    3 ->   *
          * *

    Four points are sorted into a square, and so on.

    4 ->  * *
          * *
    """
    assert isinstance(amount, int)
    solutions = {
        1: [( 0.0,  0.0)],
        2: [(-0.5,  0.0), ( 0.5,  0.0)],
        3: [(-0.5, -0.5), ( 0.0,  0.5), ( 0.5, -0.5)],
        4: [(-0.5, -0.5), ( 0.5,  0.5), ( 0.5, -0.5), (-0.5,  0.5)],
    }
    return solutions[amount]

################################################################################
class JitterDotplot(object):

    def __init__(self, data, x_col='time', y_col='sex', z_col='tip'):
        self.data = data
        self.x_col = x_col
        self.y_col = y_col
        self.z_col = z_col

    def plot(self, **kwargs):
        # Load data #
        self.df = self.data.copy()

        # Assign numerical values to the categorical data #
        # So that ['Dinner', 'Lunch'] becomes [0, 1] etc. #
        self.x_values = self.df[self.x_col].unique()
        self.y_values = self.df[self.y_col].unique()
        self.x_mapping = dict(zip(self.x_values, range(len(self.x_values))))
        self.y_mapping = dict(zip(self.y_values, range(len(self.y_values))))
        self.df = self.df.replace({self.x_col: self.x_mapping, self.y_col: self.y_mapping})

        # Offset points that are overlapping in the same location #
        # So that (2.0, 3.0) becomes (2.05, 2.95) for instance #
        cols = [self.x_col, self.y_col]
        scaling_factor = 0.05
        for values, df_view in self.df.groupby(cols):
            offsets = amount_to_offets(len(df_view))
            offsets = pandas.DataFrame(offsets, index=df_view.index, columns=cols)
            offsets *= scaling_factor
            self.df.loc[offsets.index, cols] += offsets

        # Plot a standard scatter plot #
        g = seaborn.scatterplot(x=self.x_col, y=self.y_col, size=self.z_col, data=self.df, **kwargs)

        # Force integer ticks on the x and y axes #
        locator = matplotlib.ticker.MaxNLocator(integer=True)
        g.xaxis.set_major_locator(locator)
        g.yaxis.set_major_locator(locator)
        g.grid(False)

        # Expand the axis limits for x and y #
        margin = 0.4
        xmin, xmax, ymin, ymax = g.get_xlim() + g.get_ylim()
        g.set_xlim(xmin-margin, xmax+margin)
        g.set_ylim(ymin-margin, ymax+margin)

        # Replace ticks with the original categorical names #
        g.set_xticklabels([''] + list(self.x_mapping.keys()))
        g.set_yticklabels([''] + list(self.y_mapping.keys()))

        # Return for display in notebooks for instance #
        return g

################################################################################
# Graph #
graph = JitterDotplot(data=df)
axes  = graph.plot()
axes.figure.savefig('jitter_dotplot.png')

Body:
you could first convert time and sex to categorical type and tweak it a little bit:

df.sex = pd.Categorical(df.sex)
df.time = pd.Categorical(df.time)

axes = sns.scatterplot(x=df.time.cat.codes+np.random.uniform(-0.1,0.1, len(df)),
                       y=df.sex.cat.codes+np.random.uniform(-0.1,0.1, len(df)),
                       size=df.tip)

Output:

With that idea, you can modify the offsets (np.random) in the above code to the respective distance. For example:

# grouping
groups = df.groupby(['time', 'sex'])

# compute the number of samples per group
num_samples = groups.tip.transform('size')

# enumerate the samples within a group
sample_ranks = df.groupby(['time']).cumcount() * (2*np.pi) / num_samples

# compute the offset
x_offsets = np.where(num_samples.eq(1), 0, np.cos(df.sample_rank) * 0.03)
y_offsets = np.where(num_samples.eq(1), 0, np.sin(df.sample_rank) * 0.03)

# plot
axes = sns.scatterplot(x=df.time.cat.codes + x_offsets,
                       y=df.sex.cat.codes + y_offsets,
                       size=df.tip)

Output:


问:
Define List that Changes
I have a list of time records that have 1 digit, 1 decimal, 2 digits, and an "hrs" description.

I'm looking to only get the first 4 characters of my list. But my list isn't constant so I can't write a VBA code to backspace records from A2:A100 (example range).

I need help defining my list (because the range of records changes) and then keystroking three backspaces for every value in my list. The reason I use three backspaces is because I can use a color scale on my new list that is now stored as a Number.

Below is a snippet of what I'm working with:

```<code>Original List          New List (I will use a color scale)
1.96 hrs               1.96
1.73 hrs               1.73
0.00 hrs               0.00
1.90 hrs               1.90
</code>```

I will also consider simply being able to use a color scale on my original list. My only guess in achieving this would be to format the values on my original list as Numbers. However, I've tried changing the formatting but I still can't use a color scale.

Any help would be greatly appreciated!

答:
You shouldn't need VBA.  You can just use built-in formulas.

First four characters, converted to value:

```<code>=VALUE(LEFT(A2, 4))
</code>```

Replace " hrs", convert to value:

```<code>=VALUE(SUBSTITUTE(A2, " hrs"))
</code>```

There are lots of other ways to do it.

Title: Define List that Changes

Body:
I have a list of time records that have 1 digit, 1 decimal, 2 digits, and an "hrs" description.

I'm looking to only get the first 4 characters of my list. But my list isn't constant so I can't write a VBA code to backspace records from A2:A100 (example range).

I need help defining my list (because the range of records changes) and then keystroking three backspaces for every value in my list. The reason I use three backspaces is because I can use a color scale on my new list that is now stored as a Number.

Below is a snippet of what I'm working with:

Original List          New List (I will use a color scale)
1.96 hrs               1.96
1.73 hrs               1.73
0.00 hrs               0.00
1.90 hrs               1.90

I will also consider simply being able to use a color scale on my original list. My only guess in achieving this would be to format the values on my original list as Numbers. However, I've tried changing the formatting but I still can't use a color scale.

Any help would be greatly appreciated!

Body:
You shouldn't need VBA.  You can just use built-in formulas.

First four characters, converted to value:

=VALUE(LEFT(A2, 4))

Replace " hrs", convert to value:

=VALUE(SUBSTITUTE(A2, " hrs"))

There are lots of other ways to do it.


问:
Change the background of a label when acting as checkbox
I have labels with images nested inside that is acting as a checkbox. What I can't figure out is how to change the background behind the image when that specific checkbox is selected (label clicked).

It appears as if one of the checkboxes is getting the background to show, but not both and the height element is not working.

Does anyone see what I am doing wrong?

.notificationImgs {
 width: 70px;
 height: auto;
 margin: 0 20px;
 cursor: pointer;
}
.notifCheck {
 display: none;
}
.notifCheck:checked + label {
 background: #CCC;
}
.notifCheck:checked .notificationImgs {
 background-color: #CCC;
 width: 100%;
 height: 70px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><label for="checkText">
   <img src="https://images.pexels.com/photos/67636/rose-blue-flower-rose-blooms-67636.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" alt="Text Notifications" class="notificationImgs">
  </label>
  <input type="checkbox" name="checkText" class="notifCheck" id="checkText" value="text">
  <label for="checkEmail">
   <img src="https://images.pexels.com/photos/67636/rose-blue-flower-rose-blooms-67636.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" alt="Email Notifications" class="notificationImgs">
  </label></code>```

答:
In your example code, you only have one checkbox input present. The 2nd label indicates you most likely meant to include a 2nd input checkbox with the id of #checkEmail.

The space (descendant selector) only selects all elements that are 'descendants of a specified element.
So, .notifCheck:checked .notificationImgs does not compute because notificationImgs is not a descendant of notifCheck.

The '+' (adjacent sibling selector) only selects elements that are are adjacent siblings.
So, notifCheck:checked + label is only selecting the 2nd label element, as this element immediately follows the .notifCheck element.

Body:
I have labels with images nested inside that is acting as a checkbox. What I can't figure out is how to change the background behind the image when that specific checkbox is selected (label clicked).

It appears as if one of the checkboxes is getting the background to show, but not both and the height element is not working.

Does anyone see what I am doing wrong?

.notificationImgs {
 width: 70px;
 height: auto;
 margin: 0 20px;
 cursor: pointer;
}
.notifCheck {
 display: none;
}
.notifCheck:checked + label {
 background: #CCC;
}
.notifCheck:checked .notificationImgs {
 background-color: #CCC;
 width: 100%;
 height: 70px;
}

  <input type="checkbox" name="checkText" class="notifCheck" id="checkText" value="text">


问:
Image Float Issues
I need help on the image float on 'Module 5 - 18. CSS Float and Clear'  of Angela's web devt course. I've tried making the skill images float the image of the second skill keeps getting messed up.

What am I doing wrong?

I tried grouping both 'skill' images in a round class and used:

```<code>.round-skill {
  float: left;
}
</code>```

But only the skill image on top worked out as planned. The skill image below and other elements below that (like the footer) went off

.skill-row {
  width: 50%;
  margin: 100px auto 100px auto;
  text-align: left;
}

.skill-row-sub {
  text-align: left;
  line-height: 2;
}

.skill-row-tab-title {
  text-align: left;
}

.round-skill-1 {
  float: left;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="skills">
  <h2>My Skills.</h2>
  <div class="skill-row">
    <img class="round-skill-1" src="images/avatar.png" alt="">
    <h3 class="skill-row-tab-title">Frontend Development</h3>
    <p class="skill-row-sub">I develop website interface designs using frontend technologies such as HTML and CSS. Still learning Javascript and its frameworks.</p>
  </div>
  <div class="skill-row">
    <img class="round" src="images/avatar.png" alt="">
    <h3>UI/UX</h3>
    <p>I design interfaces using Sketch and Adobe XD</p>
  </div>
</div></code>```

How do I make both skill images float: left without messing up the layout?

答:
make a div or some tag with class "cls"(usually used), and give it css:
.cls {clear: both};

place element with this class after :

I develop website interface designs using frontend technologies such as HTML and CSS. Still learning Javascript and its frameworks.

it should be okay.

clear: both will separate one float from another

like this:

```<code>    `<div class="skills">
    <h2>My Skills.</h2>
     <div class="skill-row">
         <img class="round-skill-1" src="images/tree-3097419__340.jpg" alt="">
         <h3 class="skill-row-tab-title">Frontend Development</h3>
         <p class="skill-row-sub">I develop website interface designs using frontend technologies such as HTML and CSS. Still learning Javascript and its frameworks.</p>
         <div class="cls"></div>
     </div>
     <div class="skill-row">
         <img class="round" src="images/tree-3097419__340.jpg" alt="">
         <h3>UI/UX</h3>
         <p>I design interfaces using Sketch and Adobe XD</p>

     </div>
 </div>`
</code>```

css:

```<code>`.cls {clear: both};`
</code>```

Title: Image Float Issues

Body:
I need help on the image float on 'Module 5 - 18. CSS Float and Clear'  of Angela's web devt course. I've tried making the skill images float the image of the second skill keeps getting messed up.

What am I doing wrong?

I tried grouping both 'skill' images in a round class and used:

.round-skill {
  float: left;
}

But only the skill image on top worked out as planned. The skill image below and other elements below that (like the footer) went off

.skill-row {
  width: 50%;
  margin: 100px auto 100px auto;
  text-align: left;
}

.skill-row-sub {
  text-align: left;
  line-height: 2;
}

.skill-row-tab-title {
  text-align: left;
}

.round-skill-1 {
  float: left;
}

My Skills.

Frontend Development

I develop website interface designs using frontend technologies such as HTML and CSS. Still learning Javascript and its frameworks.

UI/UX

I design interfaces using Sketch and Adobe XD

How do I make both skill images float: left without messing up the layout?

Body:
make a div or some tag with class "cls"(usually used), and give it css:
.cls {clear: both};

place element with this class after :

<p class="skill-row-sub">I develop website interface designs using frontend technologies such as HTML and CSS. Still learning Javascript and its frameworks.</p>

it should be okay.

clear: both will separate one float from another

like this:

    `<div class="skills">
    <h2>My Skills.</h2>
     <div class="skill-row">
         <img class="round-skill-1" src="images/tree-3097419__340.jpg" alt="">
         <h3 class="skill-row-tab-title">Frontend Development</h3>
         <p class="skill-row-sub">I develop website interface designs using frontend technologies such as HTML and CSS. Still learning Javascript and its frameworks.</p>
         <div class="cls"></div>
     </div>
     <div class="skill-row">
         <img class="round" src="images/tree-3097419__340.jpg" alt="">
         <h3>UI/UX</h3>
         <p>I design interfaces using Sketch and Adobe XD</p>

     </div>
 </div>`

css:

`.cls {clear: both};`


问:
Is it possible to reverse the order in a listview?
When I get my data from the firebase realtime database it is automatically listed in ascending order, but I'm trying to get the values that I put into an arraylist to be listed in reverse order rather that ascending.

Is it possible to get a reverse order on values when working with a listview ?

Code in use at the moment is:

```<code>    Query query = userRef.orderByChild("totalNumberOfSteps");
    ValueEventListener valueEventListener = new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot ds : dataSnapshot.getChildren()) {
                String username = ds.child("username").getValue(String.class);
                long totalNumberOfSteps = ds.child("totalNumberOfSteps").getValue(Long.class);
                Log.d(TAG , username + " - Steps: " + totalNumberOfSteps);
                arrayList.add(new String(username + "  -  " + "steps:  " + totalNumberOfSteps));

                arrayAdapter = new ArrayAdapter<>(Leaderboard.this , android.R.layout.simple_list_item_1 , arrayList);

                listView.setAdapter(arrayAdapter);
            }
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {
            Log.d(TAG , databaseError.getMessage()); //Don't ignore errors!
        }
    };
    query.addListenerForSingleValueEvent(valueEventListener);}}
</code>```

The current output of this code is:

```<code>John Doe VI - Steps: 0
John Doe III - Steps: 0
John Doe V - Steps: 12
John Doe I - Steps: 79
John Doe IV - Steps: 88
John Doe II - Steps: 111
</code>```

Preferred output:

```<code>John Doe II - Steps: 111
John Doe IV - Steps: 88
John Doe I - Steps: 79
John Doe V - Steps: 12
John Doe III - Steps: 0
John Doe VI - Steps: 0
</code>```

When adding Collections.reverse(arrayList); to the code, the output is:

```<code>John Doe II - Steps: 111
John Doe IV - Steps: 88
John Doe III - Steps: 0
John Doe VI - Steps: 0
John Doe V - Steps: 12
John Doe I - Steps: 79
</code>```

答:
You can reverse the ArrayList before providing it to the ArrayAdapter by doing so:

```<code>Collections.reverse(arrayList);
</code>```

In your case copy arrayList before reversing it and passing it to the ArrayAdapter's constructor:

```<code>ArrayList<> tmpArr = new ArrayList<>(arrayList);
Collections.reverse(tmpArr);
arrayAdapter = new ArrayAdapter<>(Leaderboard.this , android.R.layout.simple_list_item_1 , tmpArr );
</code>```

Otherwise the arrayList object will get reversed every time onDataChange() gets called and its order will get mixed up.

Body:
When I get my data from the firebase realtime database it is automatically listed in ascending order, but I'm trying to get the values that I put into an arraylist to be listed in reverse order rather that ascending.

Is it possible to get a reverse order on values when working with a listview ?

Code in use at the moment is:

    Query query = userRef.orderByChild("totalNumberOfSteps");
    ValueEventListener valueEventListener = new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot ds : dataSnapshot.getChildren()) {
                String username = ds.child("username").getValue(String.class);
                long totalNumberOfSteps = ds.child("totalNumberOfSteps").getValue(Long.class);
                Log.d(TAG , username + " - Steps: " + totalNumberOfSteps);
                arrayList.add(new String(username + "  -  " + "steps:  " + totalNumberOfSteps));

                arrayAdapter = new ArrayAdapter<>(Leaderboard.this , android.R.layout.simple_list_item_1 , arrayList);

                listView.setAdapter(arrayAdapter);
            }
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {
            Log.d(TAG , databaseError.getMessage()); //Don't ignore errors!
        }
    };
    query.addListenerForSingleValueEvent(valueEventListener);}}

The current output of this code is:

John Doe VI - Steps: 0
John Doe III - Steps: 0
John Doe V - Steps: 12
John Doe I - Steps: 79
John Doe IV - Steps: 88
John Doe II - Steps: 111

Preferred output:

John Doe II - Steps: 111
John Doe IV - Steps: 88
John Doe I - Steps: 79
John Doe V - Steps: 12
John Doe III - Steps: 0
John Doe VI - Steps: 0

When adding Collections.reverse(arrayList); to the code, the output is:

John Doe II - Steps: 111
John Doe IV - Steps: 88
John Doe III - Steps: 0
John Doe VI - Steps: 0
John Doe V - Steps: 12
John Doe I - Steps: 79

Body:
You can reverse the ArrayList before providing it to the ArrayAdapter by doing so:

Collections.reverse(arrayList);

In your case copy arrayList before reversing it and passing it to the ArrayAdapter's constructor:

ArrayList<> tmpArr = new ArrayList<>(arrayList);
Collections.reverse(tmpArr);
arrayAdapter = new ArrayAdapter<>(Leaderboard.this , android.R.layout.simple_list_item_1 , tmpArr );

Otherwise the arrayList object will get reversed every time onDataChange() gets called and its order will get mixed up.


问:
Is there a way to speed up execution time of this firebase cloud function?
I have following firebase cloud function (js sdk) which executes correctly. I'd like to know if there's a way to speed up execution time. This function takes on average 250ms with a userGroups collection of 10 items. I expect to run this function with a userGroups collection of arround 500 items. Any help is appreciated!</p>

```<code>.ref('users/{userId}/mood/')
.onUpdate((change, context) => {
  const userId = context.params.userId
  const beforeData = change.before.val();
  const afterData = change.after.val();
  const afterDataValue = parseInt(afterData.value || 0);
  const afterDataElement = afterData.element;
  const beforeDataValue = parseInt(beforeData.value || 0);
  const beforeDataElement = beforeData.element;

  const userGroups = admin.database().ref('/users/' + userId + '/groups/location/Items');

  const groupMood = userGroups.once("value")
  .then(function(snapshot) {
    snapshot.forEach(function(childSnapshot){
      const itemId = childSnapshot.key
      const currentElementValueRef = admin.database().ref('/groups/location/Items/' + itemId + '/mood/' + afterDataElement + '/value');
      const currentElementVoteCountRef = admin.database().ref('/groups/location/Items/' + itemId + '/mood/' + afterDataElement + '/votecount');

      if(beforeDataElement){
        const previousElementValueRef = admin.database().ref('/groups/location/Items/' + itemId + '/mood/' + beforeDataElement + '/value');
        const previousElementVoteCountRef = admin.database().ref('/groups/location/Items/' + itemId + '/mood/' + beforeDataElement + '/votecount');

        previousElementValueRef.transaction(value => {
          return (parseInt(value || 0) - beforeDataValue>0?parseInt(value || 0) - beforeDataValue:0)
        })

        currentElementValueRef.transaction(value => {
          return parseInt(value || 0) + afterDataValue
        })

        previousElementVoteCountRef.transaction(votecount => {
          return (parseInt(votecount || 0) - 1>0?parseInt(votecount || 0) - 1:0)
        })

        currentElementVoteCountRef.transaction(votecount => {
          return parseInt(votecount || 0) + 1
        })

      } else {
        currentElementValueRef.transaction(value => {
          return parseInt(value || 0) + afterDataValue
        })

        currentElementVoteCountRef.transaction(votecount => {
          return parseInt(votecount || 0) + 1
        })

        const voteCountRef = admin.database().ref('/groups/location/Items/' + itemId + '/mood/votecount');

        voteCountRef.transaction(votecount => {
          return parseInt(votecount || 0) + 1
        })
      }
    })
  })
  return groupMood })
</code>```

答:
Looks like you are reading from the database inside a loop. If I had to guess, that is where most of the function's time is spent. Three thoughts:

Before you do anything else: You should check what is actually taking time, instead of relying on my hunch. You could use https://cloud.google.com/trace/ or simply add some console.log() statements to your code.

You could potentially read the whole /groups/location/Items/ collection into a variable when the function starts. Then your code would simply read from that variable in the loop (fast) instead of reading from the database (slow). This is only possible if the /groups/location/Items/ collection is small enough to fit into memory.

Instead of running one big job like the one above, you may be able to make a small calculation whenever /users/***/groups/location/Items is updated, and store it in a node in the database. I don't fully understand what your code does, but the pattern of many small calculations instead of a single big one has served me well in the past.

Best of luck!

Body:
I have following firebase cloud function (js sdk) which executes correctly. I'd like to know if there's a way to speed up execution time. This function takes on average 250ms with a userGroups collection of 10 items. I expect to run this function with a userGroups collection of arround 500 items. Any help is appreciated!

.ref('users/{userId}/mood/')
.onUpdate((change, context) => {
  const userId = context.params.userId
  const beforeData = change.before.val();
  const afterData = change.after.val();
  const afterDataValue = parseInt(afterData.value || 0);
  const afterDataElement = afterData.element;
  const beforeDataValue = parseInt(beforeData.value || 0);
  const beforeDataElement = beforeData.element;

  const userGroups = admin.database().ref('/users/' + userId + '/groups/location/Items');

  const groupMood = userGroups.once("value")
  .then(function(snapshot) {
    snapshot.forEach(function(childSnapshot){
      const itemId = childSnapshot.key
      const currentElementValueRef = admin.database().ref('/groups/location/Items/' + itemId + '/mood/' + afterDataElement + '/value');
      const currentElementVoteCountRef = admin.database().ref('/groups/location/Items/' + itemId + '/mood/' + afterDataElement + '/votecount');

      if(beforeDataElement){
        const previousElementValueRef = admin.database().ref('/groups/location/Items/' + itemId + '/mood/' + beforeDataElement + '/value');
        const previousElementVoteCountRef = admin.database().ref('/groups/location/Items/' + itemId + '/mood/' + beforeDataElement + '/votecount');

        previousElementValueRef.transaction(value => {
          return (parseInt(value || 0) - beforeDataValue>0?parseInt(value || 0) - beforeDataValue:0)
        })

        currentElementValueRef.transaction(value => {
          return parseInt(value || 0) + afterDataValue
        })

        previousElementVoteCountRef.transaction(votecount => {
          return (parseInt(votecount || 0) - 1>0?parseInt(votecount || 0) - 1:0)
        })

        currentElementVoteCountRef.transaction(votecount => {
          return parseInt(votecount || 0) + 1
        })

      } else {
        currentElementValueRef.transaction(value => {
          return parseInt(value || 0) + afterDataValue
        })

        currentElementVoteCountRef.transaction(votecount => {
          return parseInt(votecount || 0) + 1
        })

        const voteCountRef = admin.database().ref('/groups/location/Items/' + itemId + '/mood/votecount');

        voteCountRef.transaction(votecount => {
          return parseInt(votecount || 0) + 1
        })
      }
    })
  })
  return groupMood })


问:
How to search for specific words and values in a long string?
Ok my objective is:

1.Read in a text file. e.g containing text like this, teacher/student/1/sn/2/3/4/5/9/f/tn/02/

2.pass it to a string.

3.then beable to extract different parts of the string and place them in different arrays.

The bit I dont know how to do is the extracting specific parts of the string?
Is it possible to search for / and to treat what comes after it as a specific peice of information until the next / is read?

Or perhaps there is a more efficient approach?

Help and advice sought

Kindest regards
Adrian

答: Are you sure string passed to program will not bee too large? If it's size for instance 1Gb, you'll have troubles with performance</p>

ContentLicense: CC BY-SA 3.0


问:
How to iterate over a hive table row by row and calculate metric when a specific condition is met?
I have a requirement as below:

I am trying to convert a MS Access table macro loop to work for a hive table. The table called trip_details contains details about a specific trip taken by a truck. The truck can stop at multiple locations and the type of stop is indicated by a flag called type_of_trip. This column contains values like arrival, departure, loading etc.

The ultimate aim is to calculate the dwell time of each truck (how much time does the truck take before beginning for another trip). To calculate this we have to iterate the table row by row and check for trip type.

A typical example look like this:

Do while end of file:

Store the first row in a variable.

Move to the second row.

If the type_of_trip = Arrival:

Move to the third row

If the type_of_trip = End Trip:

Store the third row

Take the difference of timestamps to calculate dwell time

Append the row into the output table

End

What is the best approach to tackle this problem in hive?

I tried checking if hive contains a keyword for loop but could not find one. I was thinking of doing this using a shell script but need guidance on how to approach this.

I cannot disclose the entire data but feel free to shoot any questions in the comments section.

Input

Trip ID   type_of_trip    timestamp            location

```<code>1         Departure       28/5/2019 15:00      Warehouse
1         Arrival         28/5/2019 16:00      Store
1         Live Unload     28/5/2019 16:30      Store
1         End Trip        28/5/2019 17:00      Store
</code>```

Expected Output

Trip ID  Origin_location  Destination_location Dwell_time

```<code>1        Warehouse        Store                2 hours
</code>```

答:
You do not need loop for this, use the power of SQL query.

Convert your timestamps to seconds (using your format specified 'dd/MM/yyyy HH:mm'), calculate min and max per trip_id, taking into account type, subtract seconds, convert seconds difference to 'HH:mm' format or any other format you prefer:

```<code>with trip_details as (--use your table instead of this subquery
select stack (4,
1,'Departure'   ,'28/5/2019 15:00','Warehouse',
1,'Arrival'     ,'28/5/2019 16:00','Store',
1,'Live Unload' ,'28/5/2019 16:30','Store',
1,'End Trip'    ,'28/5/2019 17:00','Store'
) as (trip_id, type_of_trip, `timestamp`, location)
)

select trip_id, origin_location, destination_location,
       from_unixtime(destination_time-origin_time,'HH:mm') dwell_time
  from
(
select trip_id,
       min(case when type_of_trip='Departure' then unix_timestamp(`timestamp`,'dd/MM/yyyy HH:mm') end) origin_time,
       max(case when type_of_trip='End Trip'  then unix_timestamp(`timestamp`,'dd/MM/yyyy HH:mm') end) destination_time,
       max(case when type_of_trip='Departure' then location  end) origin_location,
       max(case when type_of_trip='End Trip' then location  end) destination_location
  from trip_details
 group by trip_id
)s;
</code>```

Result:

```<code>trip_id origin_location destination_location    dwell_time
1   Warehouse   Store   02:00
</code>```

Body:
I have a requirement as below:

I am trying to convert a MS Access table macro loop to work for a hive table. The table called trip_details contains details about a specific trip taken by a truck. The truck can stop at multiple locations and the type of stop is indicated by a flag called type_of_trip. This column contains values like arrival, departure, loading etc.

The ultimate aim is to calculate the dwell time of each truck (how much time does the truck take before beginning for another trip). To calculate this we have to iterate the table row by row and check for trip type.

A typical example look like this:

Do while end of file:

Store the first row in a variable.

Move to the second row.

If the type_of_trip = Arrival:

Move to the third row

If the type_of_trip = End Trip:

Store the third row

Take the difference of timestamps to calculate dwell time

Append the row into the output table

End

What is the best approach to tackle this problem in hive?

I tried checking if hive contains a keyword for loop but could not find one. I was thinking of doing this using a shell script but need guidance on how to approach this.

I cannot disclose the entire data but feel free to shoot any questions in the comments section.

Input

Trip ID   type_of_trip    timestamp            location

1         Departure       28/5/2019 15:00      Warehouse
1         Arrival         28/5/2019 16:00      Store
1         Live Unload     28/5/2019 16:30      Store
1         End Trip        28/5/2019 17:00      Store

Expected Output

Trip ID  Origin_location  Destination_location Dwell_time

1        Warehouse        Store                2 hours

Body:
You do not need loop for this, use the power of SQL query.

Convert your timestamps to seconds (using your format specified 'dd/MM/yyyy HH:mm'), calculate min and max per trip_id, taking into account type, subtract seconds, convert seconds difference to 'HH:mm' format or any other format you prefer:

with trip_details as (--use your table instead of this subquery
select stack (4,
1,'Departure'   ,'28/5/2019 15:00','Warehouse',
1,'Arrival'     ,'28/5/2019 16:00','Store',
1,'Live Unload' ,'28/5/2019 16:30','Store',
1,'End Trip'    ,'28/5/2019 17:00','Store'
) as (trip_id, type_of_trip, `timestamp`, location)
)

select trip_id, origin_location, destination_location,
       from_unixtime(destination_time-origin_time,'HH:mm') dwell_time
  from
(
select trip_id,
       min(case when type_of_trip='Departure' then unix_timestamp(`timestamp`,'dd/MM/yyyy HH:mm') end) origin_time,
       max(case when type_of_trip='End Trip'  then unix_timestamp(`timestamp`,'dd/MM/yyyy HH:mm') end) destination_time,
       max(case when type_of_trip='Departure' then location  end) origin_location,
       max(case when type_of_trip='End Trip' then location  end) destination_location
  from trip_details
 group by trip_id
)s;

Result:

trip_id origin_location destination_location    dwell_time
1   Warehouse   Store   02:00


问:
Creating and applying ml_lib pipeline with external parameter in sparklyr
I am trying to create and apply a Spark ml_pipeline object that can handle an external parameter that will vary (typically a date). According to the Spark documentation, it seems possible: see part with ParamMap here

I haven't tried exactly how to do it. I was thinking of something like this:

```<code>table.df <- data.frame("a" = c(1,2,3))
table.sdf <- sdf_copy_to(sc, table.df)

param = 5
param2 = 4

# operation declaration
table2.sdf <- table.sdf %>%
  mutate(test = param)

# pipeline creation
pipeline_1 = ml_pipeline(sc) %>%
  ft_dplyr_transformer(table2.sdf) %>%
  ml_fit(table.sdf, list("param" = param))

# pipeline application with another value for param
table2.sdf <- pipeline_1 %>%
  ml_transform(table.sdf, list("param" = param2))

#result

glimpse(table2.sdf %>% select(test))
# doesn work...
</code>```

答:
That's really not how Spark ML Pipelines are intended to be used. In general all transformations required to convert input dataset to a format that is suitable for the Pipeline should be applied beforehand and only the common components should be embedded as stages.

When using native (Scala) API, it is technically possible, in such simple cases, like this one, to use an empty SQLTransformer:

import org.apache.spark.ml.Pipeline
import org.apache.spark.ml.feature.SQLTransformer
import org.apache.spark.ml.param.ParamPair

val df = spark.range(1, 4).toDF("a")

val sqlTransformer = new SQLTransformer()
val pipeline = new Pipeline().setStages(Array(sqlTransformer))
```

<p>and supply <code>statement</code> <code>Param</code> for both <code>fit</code></p>

```val model = pipeline.fit(
  df,
  ParamPair(sqlTransformer.statement, "SELECT *, 4 AS `test` FROM __THIS__")
)

model.transform(df).show
```

<pre class="lang-none prettyprint-override"><code>+---+----+
|  a|test|
+---+----+
|  1|   4|
|  2|   4|
|  3|   4|
+---+----+
</code>```

and transform:

model.transform(
  df,
  ParamPair(sqlTransformer.statement, "SELECT *, 5 AS `test` FROM __THIS__")
 ).show
```

<pre class="lang-none prettyprint-override"><code>+---+----+
|  a|test|
+---+----+
|  1|   5|
|  2|   5|
|  3|   5|
+---+----+
</code>```

but neither ml_fit nor ml_transform / ml_predict supports additional Params at the moment (as you can see ... are simply ignored).

Body:
I am trying to create and apply a Spark ml_pipeline object that can handle an external parameter that will vary (typically a date). According to the Spark documentation, it seems possible: see part with ParamMap here

I haven't tried exactly how to do it. I was thinking of something like this:

table.df <- data.frame("a" = c(1,2,3))
table.sdf <- sdf_copy_to(sc, table.df)

param = 5
param2 = 4

# operation declaration
table2.sdf <- table.sdf %>%
  mutate(test = param)

# pipeline creation
pipeline_1 = ml_pipeline(sc) %>%
  ft_dplyr_transformer(table2.sdf) %>%
  ml_fit(table.sdf, list("param" = param))

# pipeline application with another value for param
table2.sdf <- pipeline_1 %>%
  ml_transform(table.sdf, list("param" = param2))

#result

glimpse(table2.sdf %>% select(test))
# doesn work...

Body:
That's really not how Spark ML Pipelines are intended to be used. In general all transformations required to convert input dataset to a format that is suitable for the Pipeline should be applied beforehand and only the common components should be embedded as stages.

When using native (Scala) API, it is technically possible, in such simple cases, like this one, to use an empty SQLTransformer:

import org.apache.spark.ml.Pipeline
import org.apache.spark.ml.feature.SQLTransformer
import org.apache.spark.ml.param.ParamPair

val df = spark.range(1, 4).toDF("a")

val sqlTransformer = new SQLTransformer()
val pipeline = new Pipeline().setStages(Array(sqlTransformer))

and supply statement Param for both fit

val model = pipeline.fit(
  df,
  ParamPair(sqlTransformer.statement, "SELECT *, 4 AS `test` FROM __THIS__")
)

model.transform(df).show

+---+----+
|  a|test|
+---+----+
|  1|   4|
|  2|   4|
|  3|   4|
+---+----+

and transform:

model.transform(
  df,
  ParamPair(sqlTransformer.statement, "SELECT *, 5 AS `test` FROM __THIS__")
 ).show

+---+----+
|  a|test|
+---+----+
|  1|   5|
|  2|   5|
|  3|   5|
+---+----+

but neither ml_fit nor ml_transform / ml_predict supports additional Params at the moment (as you can see ... are simply ignored).


问:
How to find specific nested objects without knowing the parent key in mongodb
I'm using javascript and the mongoose module.
I have an object like this

```<code>my_object = {
    ShopName: String,
    employees: [String],
    info: {
        NameEmployee_1: {
            age: String,
            work: String,
            city: String,
        },

        NameEmployee_2: {
            age: String,
            work: String,
            city: String,
        }
    }

}
</code>```

and i want
find all the emoplyees that have a specific age but without knowing the name of the emplyee, is there a way for do this?

I know that you for example i can so something like this

```<code>db.collection.find({'info.Max': {$exists: true}})
</code>```

for find all the Shops that have atleast one employee with name Max
but what if i want all the Shops that have atleast one emplyee that has age 33

db.collection.find({'info.<name>.age': '33'}) ?

答:
You can utilize the $objectToArray (mongoDB 3.4.4 and up), $filter and $project and get something like this:

```<code>db.collection.aggregate([
  {
    $project: {
      obj: {
        $objectToArray: "$info"
      }
    }
  },
  {
    $project: {
      _id: 0,
      obj: {
        $filter: {
          input: "$obj",
          as: "item",
          cond: {
            $eq: [
              "$$item.v.city",
              "NY"
            ]
          }
        }
      }
    }
  },
  {
    $project: {
      info: {
        $arrayToObject: "$obj"
      }
    }
  },
])
</code>```

You can see it working here

The idea is to break the object to array, filter it and then convert that array back to object.

I filtered on city but I am sure you get the idea.

Body:
I'm using javascript and the mongoose module.
I have an object like this

my_object = {
    ShopName: String,
    employees: [String],
    info: {
        NameEmployee_1: {
            age: String,
            work: String,
            city: String,
        },

        NameEmployee_2: {
            age: String,
            work: String,
            city: String,
        }
    }

}

and i want
find all the emoplyees that have a specific age but without knowing the name of the emplyee, is there a way for do this?

I know that you for example i can so something like this

db.collection.find({'info.Max': {$exists: true}})

for find all the Shops that have atleast one employee with name Max
but what if i want all the Shops that have atleast one emplyee that has age 33

db.collection.find({'info.<name>.age': '33'}) ?

Body:
You can utilize the $objectToArray (mongoDB 3.4.4 and up), $filter and $project and get something like this:

db.collection.aggregate([
  {
    $project: {
      obj: {
        $objectToArray: "$info"
      }
    }
  },
  {
    $project: {
      _id: 0,
      obj: {
        $filter: {
          input: "$obj",
          as: "item",
          cond: {
            $eq: [
              "$$item.v.city",
              "NY"
            ]
          }
        }
      }
    }
  },
  {
    $project: {
      info: {
        $arrayToObject: "$obj"
      }
    }
  },
])

You can see it working here

The idea is to break the object to array, filter it and then convert that array back to object.

I filtered on city but I am sure you get the idea.


问:
Unable to generate embed token for accessing dataset due to missing roles in effective identity
I have embedded powerbi report which was working fine until I changed my database.

I observed datasets.IsEffectiveIdentityRequired (in below code) was false earlier, now as it is true, I'm getting an error - {"error":{"code":"InvalidRequest","message":"Creating embed token for accessing dataset 02c90e15-35dd-4036-a525-4f5d158bfade requires roles to be included in provided effective identity"}}

I'm using standard Embed service code.

// Create a Power BI Client object. It will be used to call Power BI APIs.

```<code>            using (var client = new PowerBIClient(new Uri(ApiUrl), m_tokenCredentials))
            {
                // Get a list of reports.
                var reports = await client.Reports.GetReportsInGroupAsync(WorkspaceId);

                Report report = reports.Value.FirstOrDefault(r => r.Id.Equals(ReportId, StringComparison.InvariantCultureIgnoreCase));

                var datasets = await client.Datasets.GetDatasetByIdInGroupAsync(WorkspaceId, report.DatasetId);
                m_embedConfig.IsEffectiveIdentityRequired = datasets.IsEffectiveIdentityRequired;
                m_embedConfig.IsEffectiveIdentityRolesRequired = datasets.IsEffectiveIdentityRolesRequired;
                GenerateTokenRequest generateTokenRequestParameters;
                // This is how you create embed token with effective identities
                // HERE username IS NULL
                if (!string.IsNullOrWhiteSpace(username))
                {
                    var rls = new EffectiveIdentity(username, new List<string> { report.DatasetId });
                    if (!string.IsNullOrWhiteSpace(roles))
                    {
                        var rolesList = new List<string>();
                        rolesList.AddRange(roles.Split(','));
                        rls.Roles = rolesList;
                    }
                    // Generate Embed Token with effective identities.
                    generateTokenRequestParameters = new GenerateTokenRequest(accessLevel: "view", identities: new List<EffectiveIdentity> { rls });
                }
                else
                {
                    // Generate Embed Token for reports without effective identities.
                    generateTokenRequestParameters = new GenerateTokenRequest(accessLevel: "view");
                }

                var tokenResponse = await client.Reports.GenerateTokenInGroupAsync(WorkspaceId, report.Id, generateTokenRequestParameters);
</code>```

}

First, I completely understand that this error occurs as I'm not passing any identity. So, is there any option to disable IsEffectiveIdentityRequired?

Second, how to set users and roles in powerbi?
--I'm not a PowerBI expert--

答:
IsEffectiveIdentityRequired is a read only property so you can't control it and there is no option to disable it.

Depending on the data source you are connecting to an effective identity may or may not be required.

If IsEffectiveIdentityRequired is true you need to pass an EffectiveIdentity when calling GenerateTokenRequest to generate an embed token. If the data source requires an effective identity and you do not pass one you will get an error when calling GenerateTokenRequest. You will also get an error if you pass an incomplete EffectiveIdentity, such as one that is missing roles when calling GenerateTokenRequest.

Here is an example of how you can use the IsEffectiveIdentityRequired property to generate an embed token with or without an effective identity depending on if the data source requires it or not.

List<EffectiveIdentity> eil = new List<EffectiveIdentity>();
EffectiveIdentity ef = new EffectiveIdentity();

// UserName
ef.Username = FullADUsername;

// Roles
List<string> Roles = new List<string>();

ef.Roles = Roles;

// Datasets
List<string> _Datasets = new List<string>();
_Datasets.Add(report.DatasetId);
ef.Datasets = _Datasets;

eil.Add(ef);

// Look up the data set of the report and look if we need to pass an Effective Identify
Dataset d = client.Datasets.GetDatasetByIdInGroup(WorkspaceId, report.DatasetId);
if (d.IsEffectiveIdentityRequired == true){
    GenerateTokenRequest gtr = new GenerateTokenRequest("View", null, false, eil);
    newEmbedToken = client.Reports.GenerateTokenInGroup(WorkspaceId, ReportId, gtr);
}
else
{
    GenerateTokenRequest gtr = new GenerateTokenRequest();
    newEmbedToken = client.Reports.GenerateTokenInGroup(WorkspaceId, ReportId, gtr);
}
```

Body:
I have embedded powerbi report which was working fine until I changed my database.

I observed datasets.IsEffectiveIdentityRequired (in below code) was false earlier, now as it is true, I'm getting an error - {"error":{"code":"InvalidRequest","message":"Creating embed token for accessing dataset 02c90e15-35dd-4036-a525-4f5d158bfade requires roles to be included in provided effective identity"}}

I'm using standard Embed service code.

// Create a Power BI Client object. It will be used to call Power BI APIs.

            using (var client = new PowerBIClient(new Uri(ApiUrl), m_tokenCredentials))
            {
                // Get a list of reports.
                var reports = await client.Reports.GetReportsInGroupAsync(WorkspaceId);

                Report report = reports.Value.FirstOrDefault(r => r.Id.Equals(ReportId, StringComparison.InvariantCultureIgnoreCase));

                var datasets = await client.Datasets.GetDatasetByIdInGroupAsync(WorkspaceId, report.DatasetId);
                m_embedConfig.IsEffectiveIdentityRequired = datasets.IsEffectiveIdentityRequired;
                m_embedConfig.IsEffectiveIdentityRolesRequired = datasets.IsEffectiveIdentityRolesRequired;
                GenerateTokenRequest generateTokenRequestParameters;
                // This is how you create embed token with effective identities
                // HERE username IS NULL
                if (!string.IsNullOrWhiteSpace(username))
                {
                    var rls = new EffectiveIdentity(username, new List<string> { report.DatasetId });
                    if (!string.IsNullOrWhiteSpace(roles))
                    {
                        var rolesList = new List<string>();
                        rolesList.AddRange(roles.Split(','));
                        rls.Roles = rolesList;
                    }
                    // Generate Embed Token with effective identities.
                    generateTokenRequestParameters = new GenerateTokenRequest(accessLevel: "view", identities: new List<EffectiveIdentity> { rls });
                }
                else
                {
                    // Generate Embed Token for reports without effective identities.
                    generateTokenRequestParameters = new GenerateTokenRequest(accessLevel: "view");
                }

                var tokenResponse = await client.Reports.GenerateTokenInGroupAsync(WorkspaceId, report.Id, generateTokenRequestParameters);

}

First, I completely understand that this error occurs as I'm not passing any identity. So, is there any option to disable IsEffectiveIdentityRequired?

Second, how to set users and roles in powerbi?
--I'm not a PowerBI expert--


问:
How to display Google captcha?
My Google captcha has had the ends chopped off, particularly the right end in both mobile mobile and desktop?

Why is this?

I have the following html:

```<code>"wpcf7-form-control-wrap your-subject"><input type="text"
name="your-subject" value="" size="40" class="wpcf7-form-control
wpcf7-text" aria-invalid="false" /></span> </label></p>
<p><label> Your Message<br />
<span class="wpcf7-form-control-wrap your-message"><textarea
name="your-message" cols="40" rows="10" class="wpcf7-form-control
wpcf7-textarea" aria-invalid="false"></textarea></span> </label></p>
<p><div class="anr_captcha_field"><div id="anr_captcha_field_1"
class="anr_captcha_field_div"></div></div><span class="wpcf7-form-
control-wrap g-recaptcha-response"></span></p>
<p><input type="submit" value="Send" class="wpcf7-form-control
wpcf7-submit" /></p>
<div class="wpcf7-response-output wpcf7-display-none"></div></form>.
</div></div><!-- .entry-content -->
<footer class="entry-footer">
</footer><!-- .entry-footer -->
</code>```

And the following css:

```<code>#anr_captcha_field_1 {overflow: hidden;
border-radius: 0px;
transform: scale(0.9);
transform-origin: left top;
margin-left:35px; background-color: #fff; border: none;
}

@media (max-width: 5000px) and (min-width: 768px)
{#anr_captcha_field_1 {

overflow: hidden;
border-radius: 0px;
transform: scale(0.9);
transform-origin: left top;
margin-left:10px; background-color: #fff; border: none;
}}
</code>```

The problem arose because I wanted to centre the capture in desktop, now the right end's chopped off.

Page: https://adsler.co.uk/contact-us/

答:
You need to increase the max width of your form as well. it is blocking the captcha.</p>

```<code>  @media (max-width: 5000px) and (min-width: 768px){
      .wpcf7 {
          max-width: 330px;
          padding: 0px;
      }
    }

    .rc-anchor-normal {
        height: 74px;
        width: 300px;
    }
</code>```

Title: How to display Google captcha?

Body:
My Google captcha has had the ends chopped off, particularly the right end in both mobile mobile and desktop?

Why is this?

I have the following html:

"wpcf7-form-control-wrap your-subject"><input type="text"
name="your-subject" value="" size="40" class="wpcf7-form-control
wpcf7-text" aria-invalid="false" />

 Your Message

<textarea
name="your-message" cols="40" rows="10" class="wpcf7-form-control
wpcf7-textarea" aria-invalid="false"></textarea>

<input type="submit" value="Send" class="wpcf7-form-control
wpcf7-submit" />

</form>.

And the following css:

#anr_captcha_field_1 {overflow: hidden;
border-radius: 0px;
transform: scale(0.9);
transform-origin: left top;
margin-left:35px; background-color: #fff; border: none;
}

@media (max-width: 5000px) and (min-width: 768px)
{#anr_captcha_field_1 {

overflow: hidden;
border-radius: 0px;
transform: scale(0.9);
transform-origin: left top;
margin-left:10px; background-color: #fff; border: none;
}}

The problem arose because I wanted to centre the capture in desktop, now the right end's chopped off.

Page: https://adsler.co.uk/contact-us/

Body:
You need to increase the max width of your form as well. it is blocking the captcha.

  @media (max-width: 5000px) and (min-width: 768px){
      .wpcf7 {
          max-width: 330px;
          padding: 0px;
      }
    }

    .rc-anchor-normal {
        height: 74px;
        width: 300px;
    }


问:
Adding items into an array - Separately
Goal: Click a button and have ingredients added to an array as separate items.

Current Set Up:

```<code>    <% currentUser.ingredients.forEach(function(items){ %>
   <p class='ingredients'>  <%= items %> </p>
    <% }) %>
</code>```

This gives: Blueberries Mango Lemon Juice

I'd then like to be able to add the ingredients as separate items to an array by clicking a button:

```<code>var allIngredients = []

$("#makeList").click(function() {

allIngredients.push($(".ingredients").text())
console.log(allIngredients)

});
</code>```

This prints ["Blueberrys Mango Lemon Juice"]

The issue is it is all one item not separate items.

What to I need to change to make them separate items?

答:
You need to iterate over $('.ingredients')

```<code>var allIngredients = [];

$("#makeList").click(function() {

    $(".ingredients").each(function() {
        allIngredients.push($(this).text());
    });

    console.log(allIngredients);

});
</code>```

Title: Adding items into an array - Separately

Body:
Goal: Click a button and have ingredients added to an array as separate items.

Current Set Up:

    <% currentUser.ingredients.forEach(function(items){ %>

  <%= items %>

    <% }) %>

This gives: Blueberries Mango Lemon Juice

I'd then like to be able to add the ingredients as separate items to an array by clicking a button:

var allIngredients = []

$("#makeList").click(function() {

allIngredients.push($(".ingredients").text())
console.log(allIngredients)

});

This prints ["Blueberrys Mango Lemon Juice"]

The issue is it is all one item not separate items.

What to I need to change to make them separate items?

Body:
You need to iterate over $('.ingredients')

var allIngredients = [];

$("#makeList").click(function() {

    $(".ingredients").each(function() {
        allIngredients.push($(this).text());
    });

    console.log(allIngredients);

});


问:
Componentheading and contentpagetitle joomla
If have a problem with the componentheading and the contentpagetitle.

I got a sectionblog for my articles. The title of the page is a componentheading. The title of the articles (intro) is a contentpagetitle.

If I click on the title of a article, I can see the entire article. The title of the page is now the title of the article (contentpagetitle), and that is good.

The problem is, this title now needs the same layout as the componentheading. But if I do this, the titles of the articles also get this layout in the sectionblog

How can I make sure I got 2 different styles, or the contentpagetitle changes in a componentheading while looking at the full article?

I you don't uderstand what I'm saying just go to http://csm.infowebpreview.be/nl/realisaties, and click on the first title 'Realisatie'. The full article opens and the title 'Realisatie' should be underlined now.

Or this is also correct: if an article is the only article on a page the title should get another layout

Thanks

答:
You can do this by being more specific with the CSS selector -

This one will apply to all of the titles, make this one the one for the main heading with the underline -

```<code>h2.contentheadingrealisaties{border-bottom: 1px solid #333}
</code>```

Then use this to single out the article titles in a listing:

```<code>.leadingrealisaties h2.contentheadingrealisaties{border:0;}
</code>```

Obviously you will need to add in the rest of the CSS, but this will get you started.

Body:
You can do this by being more specific with the CSS selector -

This one will apply to all of the titles, make this one the one for the main heading with the underline -

h2.contentheadingrealisaties{border-bottom: 1px solid #333}

Then use this to single out the article titles in a listing:

.leadingrealisaties h2.contentheadingrealisaties{border:0;}

Obviously you will need to add in the rest of the CSS, but this will get you started.


问:
Send an email using mailKit in MVC 5
I am trying to find a basic step-by-step tutorial to send an email in ASP.NET using mailKit but every tutorial talks about ASP.NET Core.

Can anyone point me to right direction? What should I use to send emails in MVC 5 and link a step-by-step tutorial?

I do not want to use smtpClient class as it is obsolete now.

答: https://gist.github.com/wattanar/e8cee974456fd80d9ce649d951f36608  Check this code; it is an example :) Might help</p>

Title: Send an email using mailKit in MVC 5


问:
Disable select if there is nothing to show
I made a filter with multiple options. As you can see, there are sometimes no results. I give this back to the visitor as user feedback by saying: no results.

Now I want to make it that if certain combinations are made of filters (certain values), it is only possible to use a filter if there are actually values (so hide a option if there is no value on the page). This way I prevent a user from having to make endless filter combinations to find the right results. Can someone help me?

$("select.filterby").change(function() {
  var filters = $.map($("select.filterby").toArray(), function(e) {
    return $(e).val();
  }).join(".");
  $("div#FilterContainer").find("div.job-offer-card").hide();
  if ($("div#FilterContainer").find("div.job-offer-card." + filters).length) {
    $("div#FilterContainer").find("div.job-offer-card." + filters).show();

  } else {
    $("div#FilterContainer").find("div.noresults").show();
  }
});```
<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>
<span> View by:</span>

    <label for="location">Location</label>
    <select id="location" class="filterby">
       <option value="all">Show All</option>
       <option value="australia">Australia</option>
       <option value="singapore">Singapore</option>
       <option value="newzealand">New Zealand</option>
       <option value="usa">USA</option>
       <option value="uk">UK</option>
       <option value="vietnam">Vietnam</option>
       <option value="global">Global</option>
       <option value="othercountry">Other</option>
    </select>

    <label for="type">Type</label>
    <select id="type" class="filterby">
       <option value="all">Show All</option>
       <option value="accommodation">Accommodation</option>
       <option value="app">App/Technology</option>
       <option value="business">Business</option>
       <option value="health">Health</option>
       <option value="hospitality">Hospitality</option>
       <option value="education">Education</option>
       <option value="retail">Retail</option>
       <option value="services">Services</option>
       <option value="travel">Travel</option>
    </select>

    <label for="code">Code</label>
    <select id="code" class="filterby">
       <option value="all">Show All</option>
       <option value="001">001</option>
       <option value="002">002</option>
       <option value="003">003</option>
       <option value="004">004</option>
    </select>

<div id="FilterContainer">
  <div class="job-offer-card noresults">
    <p>no results</p>
  </div>
  <div class="job-offer-card all vietnam accommodation travel 004">
    <p>1 all vietnam accommodation travel</p>
  </div>
  <div class="job-offer-card all vietnam  travel 003">
    <p>2 all vietnam travel</p>
  </div>
  <div class="job-offer-card all vietnam accommodation travel">
    <p>3 all vietnam accommodation travel</p>
  </div>
  <div class="job-offer-card all australia accommodation travel 003">
    <p>4 all australia accommodation travel</p>
  </div>
  <div class="job-offer-card all australia education">
    <p>5 all australia</p>
  </div>
  <div class="job-offer-card all vietnam newzealand usa accommodation">
    <p>6 all vietnam accommodation</p>
  </div>
  <div class="job-offer-card all vietnam accommodation travel">
    <p>7 all vietnam accommodation travel</p>
  </div>
  <div class="job-offer-card all vietnam  travel">
    <p>8 all vietnam travel</p>
  </div>
  <div class="job-offer-card all vietnam accommodation travel">
    <p>9 all vietnam accommodation travel</p>
  </div>
  <div class="job-offer-card all australia accommodation travel">
    <p>10 all australia accommodation travel</p>
  </div>
  <div class="job-offer-card all australia health 001">
    <p>11 all australia</p>
  </div>
  <div class="job-offer-card all vietnam accommodation 002">
    <p>12 all vietnam accommodation</p>
  </div>
</div></code>```

答:
so if I check correctly your question:</p>

```<code>const
  All_Select          = document.querySelectorAll('select')
, All_FilterContainer = document.querySelectorAll('#FilterContainer div')
;

var List_of_everthing   = new Set();
All_FilterContainer.forEach(d=>{
  d.className.split(' ').forEach(c=>{List_of_everthing.add(c.toLowerCase())});
})

All_Select.forEach(s=>{
  s.querySelectorAll('option').forEach(o=>{
    o.disabled = !List_of_everthing.has(o.value);
  })
})
</code>```

Body:
I made a filter with multiple options. As you can see, there are sometimes no results. I give this back to the visitor as user feedback by saying: no results.

Now I want to make it that if certain combinations are made of filters (certain values), it is only possible to use a filter if there are actually values (so hide a option if there is no value on the page). This way I prevent a user from having to make endless filter combinations to find the right results. Can someone help me?

$("select.filterby").change(function() {
  var filters = $.map($("select.filterby").toArray(), function(e) {
    return $(e).val();
  }).join(".");
  $("div#FilterContainer").find("div.job-offer-card").hide();
  if ($("div#FilterContainer").find("div.job-offer-card." + filters).length) {
    $("div#FilterContainer").find("div.job-offer-card." + filters).show();

  } else {
    $("div#FilterContainer").find("div.noresults").show();
  }
});

 View by:

    Location
    <select id="location" class="filterby">
       <option value="all">Show All</option>
       <option value="australia">Australia</option>
       <option value="singapore">Singapore</option>
       <option value="newzealand">New Zealand</option>
       <option value="usa">USA</option>
       <option value="uk">UK</option>
       <option value="vietnam">Vietnam</option>
       <option value="global">Global</option>
       <option value="othercountry">Other</option>
    </select>

    Type
    <select id="type" class="filterby">
       <option value="all">Show All</option>
       <option value="accommodation">Accommodation</option>
       <option value="app">App/Technology</option>
       <option value="business">Business</option>
       <option value="health">Health</option>
       <option value="hospitality">Hospitality</option>
       <option value="education">Education</option>
       <option value="retail">Retail</option>
       <option value="services">Services</option>
       <option value="travel">Travel</option>
    </select>

    Code
    <select id="code" class="filterby">
       <option value="all">Show All</option>
       <option value="001">001</option>
       <option value="002">002</option>
       <option value="003">003</option>
       <option value="004">004</option>
    </select>

no results

1 all vietnam accommodation travel

2 all vietnam travel

3 all vietnam accommodation travel

4 all australia accommodation travel

5 all australia

6 all vietnam accommodation

7 all vietnam accommodation travel

8 all vietnam travel

9 all vietnam accommodation travel

10 all australia accommodation travel

11 all australia

12 all vietnam accommodation

Body:
so if I check correctly your question:

const
  All_Select          = document.querySelectorAll('select')
, All_FilterContainer = document.querySelectorAll('#FilterContainer div')
;

var List_of_everthing   = new Set();
All_FilterContainer.forEach(d=>{
  d.className.split(' ').forEach(c=>{List_of_everthing.add(c.toLowerCase())});
})

All_Select.forEach(s=>{
  s.querySelectorAll('option').forEach(o=>{
    o.disabled = !List_of_everthing.has(o.value);
  })
})


问:
expand for MongoDB Scala driver?
Casbah has an expand function that lets you retrieve nested keys.
Does the newer MongoDB Scala Driver have this functionality?</p>

答:
```<code>package org.mongodb.scala.bson

import org.mongodb.scala.bson.DefaultHelper.DefaultsTo

import scala.reflect.ClassTag
import scala.util.Try
import scala.collection.JavaConverters._

object Expandable {
  implicit class AddExpand(val underlying: Document) extends AnyVal {
    def expand[TResult <: BsonValue: ClassTag](key: String)(implicit e: TResult DefaultsTo BsonValue): Either[Throwable, TResult] = {
      val path = key.split('.')
      path.init.tail
        .foldLeft(Try(underlying.underlying.get(path.head).asDocument()).toEither){
          case (parent, pathEl) => parent.flatMap(p => get[BsonDocument](p, pathEl))
        }
        .flatMap(p => get[TResult](p, path.last))
    }
  }

  def get[TResult <: BsonValue](parent: BsonDocument, key: String)(implicit e: TResult DefaultsTo BsonValue, ct: ClassTag[TResult]): Either[Throwable, TResult] = {
    Try(parent.asScala.get(key).map(ct.runtimeClass.cast).map(_.asInstanceOf[TResult]).getOrElse(throw new NoSuchElementException(key))).toEither
  }
}
</code>```

This solution is more in spirit of the original expand function from Casbah. It uses the extension method pattern.

Not sure that it is better than the macros on case classes solution. I just didn't have _t in my documents.

I did manage to come up with a custom codec using the macros and case classes and a custom invocation of the codecRegistry, but it was getting ugly fast. Uglier than the expand extension method shown above.

This is less type safe than the macro solution but gets the job done quicker if not dirtier. Quicker in that I don't have to rewrite the entire schema as case classes.

Based on MongoDB Scala Driver version 2.6.0

This should probably be made into a proper pull request, but it'd probably get rejected for one reason or another.

Title: expand for MongoDB Scala driver?

Body:
package org.mongodb.scala.bson

import org.mongodb.scala.bson.DefaultHelper.DefaultsTo

import scala.reflect.ClassTag
import scala.util.Try
import scala.collection.JavaConverters._

object Expandable {
  implicit class AddExpand(val underlying: Document) extends AnyVal {
    def expand[TResult <: BsonValue: ClassTag](key: String)(implicit e: TResult DefaultsTo BsonValue): Either[Throwable, TResult] = {
      val path = key.split('.')
      path.init.tail
        .foldLeft(Try(underlying.underlying.get(path.head).asDocument()).toEither){
          case (parent, pathEl) => parent.flatMap(p => get[BsonDocument](p, pathEl))
        }
        .flatMap(p => get[TResult](p, path.last))
    }
  }

  def get[TResult <: BsonValue](parent: BsonDocument, key: String)(implicit e: TResult DefaultsTo BsonValue, ct: ClassTag[TResult]): Either[Throwable, TResult] = {
    Try(parent.asScala.get(key).map(ct.runtimeClass.cast).map(_.asInstanceOf[TResult]).getOrElse(throw new NoSuchElementException(key))).toEither
  }
}

This solution is more in spirit of the original expand function from Casbah. It uses the extension method pattern.

Not sure that it is better than the macros on case classes solution. I just didn't have _t in my documents.

I did manage to come up with a custom codec using the macros and case classes and a custom invocation of the codecRegistry, but it was getting ugly fast. Uglier than the expand extension method shown above.

This is less type safe than the macro solution but gets the job done quicker if not dirtier. Quicker in that I don't have to rewrite the entire schema as case classes.

Based on MongoDB Scala Driver version 2.6.0

This should probably be made into a proper pull request, but it'd probably get rejected for one reason or another.


问:
How to make reactstrap modal open or close from parent component
I am trying to open / close a reactstrap modal from a parent component button, but I cannot get it to work.

I am passing the state isModalOpen as a prop to the child ModalExample component, and it changes as shown in the debug text fields I made, but the modal does not seem to open.

Any help is appreciated. Here is a jsfiddle: https://jsfiddle.net/67wy5nqp/

```<code>const { Button, Modal, ModalHeader, ModalBody, ModalFooter } = Reactstrap;

class ModalExample extends React.Component {
  constructor(props) {
    super(props);
    console.log(this.props);
  }

  render() {
    return (
      <div>
        <br />
        <label>
          (child) this.props.isOpen
          <input type="text" value={this.props.isOpen} />
        </label>

        <Modal
          isOpen={this.props.isModalOpen}
          toggle={this.props.toggleModalView}
          className={this.props.className}
        >
          <ModalHeader toggle={this.props.toggleModalView}>
            Modal title
          </ModalHeader>
          <ModalBody>
            Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do
            eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim
            ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
            aliquip ex ea commodo consequat. Duis aute irure dolor in
            reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla
            pariatur. Excepteur sint occaecat cupidatat non proident, sunt in
            culpa qui officia deserunt mollit anim id est laborum.
          </ModalBody>
          <ModalFooter>
            <Button color="primary" onClick={this.props.toggleModalView}>
              Do Something
            </Button>
            <Button color="secondary" onClick={this.props.toggleModalView}>
              Cancel
            </Button>
          </ModalFooter>
        </Modal>
      </div>
    );
  }
}

class SampleApp extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isModalOpen: true
    };

    this.showModal = this.showModal.bind(this);
    this.toggle = this.toggle.bind(this);
  }

  toggle() {
    this.setState({
      isModalOpen: !this.state.isModalOpen
    });
  }

  showModal() {
    this.setState({
      isModalOpen: true
    });
  }

  render() {
    return (
      <div>
        <ModalExample
          isOpen={this.state.isModalOpen}
          toggle={this.state.isModalOpen}
        />

        <br />
        <button className="btn btn-primary" onClick={this.toggle}>
          Show Modal From Parent Component
        </button>

        <br />
        <label>
          (parent) this.state.isModalOpen:
          <input type="text" value={this.state.isModalOpen} />
        </label>
      </div>
    );
  }
}

ReactDOM.render(<SampleApp />, document.querySelector("#app"));
</code>```

答:
```<code>    import React from 'react';
import { Button, Modal, ModalFooter, ModalHeader,ModalBody} from 'reactstrap';

class ModalExample extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            modal: props.initialModalState,
            fade: true
        };

        this.toggle = this.toggle.bind(this);
    }

    toggle() {
        this.setState({
            modal: !this.state.modal,
            fade: !this.state.fade

        });
    }

    render() {
        return (
            <div>
                <Button color="danger" onClick={this.toggle}>TOGGLE</Button>
                <Modal isOpen={this.state.modal} toggle={this.toggle}
                       fade={this.state.fade}
                       className={this.props.className}>
                    <ModalHeader toggle={this.toggle}>Modal title</ModalHeader>
                    <ModalBody>

                    </ModalBody>
                    <ModalFooter>
                        <Button color="primary" onClick={this.toggle}>Do Something</Button>{' '}
                        <Button color="secondary" onClick={this.toggle}>Cancel</Button>
                    </ModalFooter>
                </Modal>
            </div>
        );
    }
}

export default class SampleApp extends React.Component {
    constructor(props) {
        super(props);
        this.state = {}
    }

    render() {
        return (
            <div>
                <ModalExample initialModalState={false} />
            </div>
        )
    }
}

**This example getting call component modal from another component**
</code>```

Body:
I am trying to open / close a reactstrap modal from a parent component button, but I cannot get it to work.

I am passing the state isModalOpen as a prop to the child ModalExample component, and it changes as shown in the debug text fields I made, but the modal does not seem to open.

Any help is appreciated. Here is a jsfiddle: https://jsfiddle.net/67wy5nqp/

const { Button, Modal, ModalHeader, ModalBody, ModalFooter } = Reactstrap;

class ModalExample extends React.Component {
  constructor(props) {
    super(props);
    console.log(this.props);
  }

  render() {
    return (

          (child) this.props.isOpen
          <input type="text" value={this.props.isOpen} />

        <Modal
          isOpen={this.props.isModalOpen}
          toggle={this.props.toggleModalView}
          className={this.props.className}
        >
          <ModalHeader toggle={this.props.toggleModalView}>
            Modal title
          </ModalHeader>
          <ModalBody>
            Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do
            eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim
            ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
            aliquip ex ea commodo consequat. Duis aute irure dolor in
            reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla
            pariatur. Excepteur sint occaecat cupidatat non proident, sunt in
            culpa qui officia deserunt mollit anim id est laborum.
          </ModalBody>
          <ModalFooter>
            <Button color="primary" onClick={this.props.toggleModalView}>
              Do Something
            </Button>
            <Button color="secondary" onClick={this.props.toggleModalView}>
              Cancel
            </Button>
          </ModalFooter>
        </Modal>

    );
  }
}

class SampleApp extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isModalOpen: true
    };

    this.showModal = this.showModal.bind(this);
    this.toggle = this.toggle.bind(this);
  }

  toggle() {
    this.setState({
      isModalOpen: !this.state.isModalOpen
    });
  }

  showModal() {
    this.setState({
      isModalOpen: true
    });
  }

  render() {
    return (

        <ModalExample
          isOpen={this.state.isModalOpen}
          toggle={this.state.isModalOpen}
        />

        <button className="btn btn-primary" onClick={this.toggle}>
          Show Modal From Parent Component
        </button>

          (parent) this.state.isModalOpen:
          <input type="text" value={this.state.isModalOpen} />

    );
  }
}

ReactDOM.render(<SampleApp />, document.querySelector("#app"));


问:
Get only numbers from string in python
I want to get only the numbers from a string. For example I have something like this

```<code>just='Standard Price:20000'
</code>```

And I only want it to print out

```<code>20000
</code>```

So I can multiply it by any number.

I tried

```<code>just='Standard Price:20000'
just[0][1:]
</code>```

I got

```<code> ''
</code>```

What's the best way to go about this? I'm a noob.

答:
If you want to keep it simpler avoiding regex, you can also try Python's built-in function filter with str.isdigit function to get the string of digits and convert the returned string to integer. This will not work for float as the decimal character is filtered out by str.isdigit.

Python Built-in Functions Filter

Python Built-in Types str.isdigit

Considering the same code from the question:

```<code>>>> just='Standard Price:20000'
>>> price = int(filter(str.isdigit, just))
>>> price
20000
>>> type(price)
<type 'int'>
>>>
</code>```

Title: Get only numbers from string in python

Body:
I want to get only the numbers from a string. For example I have something like this

just='Standard Price:20000'

And I only want it to print out

20000

So I can multiply it by any number.

I tried

just='Standard Price:20000'
just[0][1:]

I got

 ''

What's the best way to go about this? I'm a noob.

Body:
If you want to keep it simpler avoiding regex, you can also try Python's built-in function filter with str.isdigit function to get the string of digits and convert the returned string to integer. This will not work for float as the decimal character is filtered out by str.isdigit.

Python Built-in Functions Filter

Python Built-in Types str.isdigit

Considering the same code from the question:

>>> just='Standard Price:20000'
>>> price = int(filter(str.isdigit, just))
>>> price
20000
>>> type(price)
<type 'int'>
>>>