问:
Why does the GridView.builder returns elements expanded in height whereas the ListView.Seperated returns the element with normal height?
I wanted to use the grid view for the landscape mode. So i used GridView but all the Grid elements are expanded vertically.

I even tried for the ListView.builder using GridView.builder setting the crossAxisCount to 1 to make the same effect as the ListView.builder but there also all the items are expanded vertically.

```<code>Widget buildTopNews(BuildContext context) {
  return Container(
    padding: EdgeInsets.only(bottom: 20),
    child: MediaQuery.of(context).orientation == Orientation.portrait
        ? ListView.separated(
            shrinkWrap: true,
            physics: const NeverScrollableScrollPhysics(),
            itemBuilder: (BuildContext context, int index) {
              return NewsCard(
                news: topNews[index],
              );
            },
            itemCount: topNews.length,
            separatorBuilder: (BuildContext context, int index) {
              return SizedBox(
                height: 20,
              );
            },
          )
        : GridView.builder(
            physics: NeverScrollableScrollPhysics(),
            shrinkWrap: true,
            itemCount: topNews.length,
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 2,
              mainAxisSpacing: 20,
            ),
            itemBuilder: (BuildContext context, int index) {
              return NewsCard(
                news: topNews[index],
              );
            },
          ),
  );
}
</code>```

答: Gridview has an aspect ratio for its children. So that's why your items are having the same height as its width(width is set out first). Change the aspect ratio value in your gridview to get the desired height. </p>

Body:
I wanted to use the grid view for the landscape mode. So i used GridView but all the Grid elements are expanded vertically.

I even tried for the ListView.builder using GridView.builder setting the crossAxisCount to 1 to make the same effect as the ListView.builder but there also all the items are expanded vertically.

Widget buildTopNews(BuildContext context) {
  return Container(
    padding: EdgeInsets.only(bottom: 20),
    child: MediaQuery.of(context).orientation == Orientation.portrait
        ? ListView.separated(
            shrinkWrap: true,
            physics: const NeverScrollableScrollPhysics(),
            itemBuilder: (BuildContext context, int index) {
              return NewsCard(
                news: topNews[index],
              );
            },
            itemCount: topNews.length,
            separatorBuilder: (BuildContext context, int index) {
              return SizedBox(
                height: 20,
              );
            },
          )
        : GridView.builder(
            physics: NeverScrollableScrollPhysics(),
            shrinkWrap: true,
            itemCount: topNews.length,
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 2,
              mainAxisSpacing: 20,
            ),
            itemBuilder: (BuildContext context, int index) {
              return NewsCard(
                news: topNews[index],
              );
            },
          ),
  );
}


来源: stackexchange

问:
Multiple route builders defined in single Camel context are sequential?
I wanted to understand how multiple routes in same camel context will behave?

For example, Let's say I have an application wherein I have a single camel context which contains three different route builders each defining one route. Each of these routes are listening to different queues.

Can someone please let me know if all these three routes will work in parallel or only one will process the message while others wait?

答: I believe the queues will function in parallel. You can also specify the number of threads (.threads()) the route uses. So, with that it is safe to presume that the routes run in parallel. </p>

ContentLicense: CC BY-SA 4.0


问:
How to get latest values in table with Spark?
I have a table like the following:

```<code>date       | person | assignment
-----------+--------+-----------
2019-01-01 | joe    | blue
2019-02-01 | joe    | red
2019-01-01 | mel    | green
2019-03-01 | mel    | yellow
2019-02-01 | drew   | blue
</code>```

And I want the following result with a Spark query

```<code>latest     | person | assignment
-----------+--------+-----------
2019-02-01 | joe    | red
2019-03-01 | mel    | yellow
2019-02-01 | drew   | blue
</code>```

I know I could just do person, max(date) latest and then query the full list again. But is there an easy way to do this with a Spark windowing function.

答:
```<code>df.withColumn(
    "num",
    row_number() over Window.partitionBy("person").orderBy(desc("date")))
  .filter($"num" === 1)
  .drop("num")
  .show()
</code>```

Body:
I have a table like the following:

date       | person | assignment
-----------+--------+-----------
2019-01-01 | joe    | blue
2019-02-01 | joe    | red
2019-01-01 | mel    | green
2019-03-01 | mel    | yellow
2019-02-01 | drew   | blue

And I want the following result with a Spark query

latest     | person | assignment
-----------+--------+-----------
2019-02-01 | joe    | red
2019-03-01 | mel    | yellow
2019-02-01 | drew   | blue

I know I could just do person, max(date) latest and then query the full list again. But is there an easy way to do this with a Spark windowing function.


问:
work space specific variable to use in power bi query dynamically
Use Case:
We are getting app insight custom event data from app insight and publishing it in power bi using power bi queries. We have 3 environments (Dev,PreProd and Prod). We have created 3 work spaces for each environments.

Question:
The queries use application insight App ID which is hardcoded for now. Is there a way to pass the App ID dynamically since it will be different for different workspace/environments.

答:
I think what you want to use is parameters. Guy in a Cube did a video about something similar awhile back, but the process can be modified to work with App Insights.

The instructions for creating a connection to App Insights from Power BI Desktop ask you to export the M code from App Insights and then copy it into a blank query. Go ahead and open up the query editor, but instead of copying in the code right away, first make a parameter to hold the link to the specific App Insights instance you want to connect to.

Once you have the parameter created, you can open up the query's advanced editor and paste in the code you exported from App Insights. Replace the connection string with the parameter you created.

Complete the rest of the work on the report, and publish it to the service. Finally, go into each workspace and update the parameter in the dataset's settings menu.

Currently parameters do get overwritten when you publish changes. However, if you use a script to push the updates to the separate workspaces you can also use that script to set the parameter in each.


问:
Python - Why 2 different functions identify the same tuple as <class 'tuple'> while another function identifies the same tuple as None
So when I call

```<code>plot_bounces( ball, numbounces, boxWH_tuple, circle=None )
</code>```

where ball is an object, numbounces is an int, boxWH_tuple and circle are tuples, and put a print(type(circle)) statement in this function, it is a tuple. However, when I call update_ball(ball, boxWH_tuple, circle=None) an put a print(type(circle)) statement in this function, it is a nonetype. I don't understand why nor how to make it a tuple for both functions. This is just part of my code which seems to be problematic.

This is what I used to call plot_bounces

```<code>plot_bounces(Ball(-1,0,0.1), 1, (3,2), ( (0,0) ,0.4) )
</code>```

There's another script with class Ball which deals with the Ball object.

My main concern is why print(type(circle)) gives me class 'tuple' for the first print and class 'NoneType' for the second print.

```<code>def plot_bounces(ball, numbounces, boxWH_tuple, circle=None):
    print(type (circle))
     #make space to store coordinates
    xcoords = []
    ycoords = []
    #store the starting point
    xcoords.append(ball.x)
    ycoords.append(ball.y)

    while numbounces>0 :
        #calls on update_ball and change the old values with new ones

        update_ball(ball, boxWH_tuple, circle=None)
#
        ball=update_ball(ball, boxWH_tuple, circle=None)

        xpoint = ball.x
        ypoint = ball.y

        ycoords.append(ypoint)
        xcoords.append(xpoint)

        numbounces+= -1

def update_ball(ball, boxWH_tuple, circle=None):
    print (type(circle))
</code>```

Should't it be a tuple for both cases?

答:
When calling update_ball() from plot_bounces(), please remove =None after circle,
because when you do circle=None in a call (call, not function definition), then you are passing that argument as a None and therefore the confusion.

The call should be update_ball(ball, boxWH_tuple, circle)

Body:
So when I call

plot_bounces( ball, numbounces, boxWH_tuple, circle=None )

where ball is an object, numbounces is an int, boxWH_tuple and circle are tuples, and put a print(type(circle)) statement in this function, it is a tuple. However, when I call update_ball(ball, boxWH_tuple, circle=None) an put a print(type(circle)) statement in this function, it is a nonetype. I don't understand why nor how to make it a tuple for both functions. This is just part of my code which seems to be problematic.

This is what I used to call plot_bounces

plot_bounces(Ball(-1,0,0.1), 1, (3,2), ( (0,0) ,0.4) )

There's another script with class Ball which deals with the Ball object.

My main concern is why print(type(circle)) gives me class 'tuple' for the first print and class 'NoneType' for the second print.

def plot_bounces(ball, numbounces, boxWH_tuple, circle=None):
    print(type (circle))
     #make space to store coordinates
    xcoords = []
    ycoords = []
    #store the starting point
    xcoords.append(ball.x)
    ycoords.append(ball.y)

    while numbounces>0 :
        #calls on update_ball and change the old values with new ones

        update_ball(ball, boxWH_tuple, circle=None)
#
        ball=update_ball(ball, boxWH_tuple, circle=None)

        xpoint = ball.x
        ypoint = ball.y

        ycoords.append(ypoint)
        xcoords.append(xpoint)

        numbounces+= -1

def update_ball(ball, boxWH_tuple, circle=None):
    print (type(circle))

Should't it be a tuple for both cases?


问:
How to subset based on if it contains a certain string
I have a data frame, which is basically the Hello list of passengers, with columns of Hello(string), Hello (1st, 2nd or 3rd), Hello, Hello (female or male) and Hello(0 or 1).

Basically, I want to extract the unmarried women from my data frame.

I only want to extract the Hello that contain "Hello". I can't use the == operator because it will match it identically. Any help would be appreciated. Thank you all.

I have tried "Hello but that did not work.

```<code> $ Hello    : Hello w/,..: 22 25 26 27 24 31 45 46 50 54 ...
 $ Hello  : Hello w/ 3 levels "1st","2nd","3rd": 1 1 1 1 1 1 1 1 1 1 ...
 $ Hello     : He
 - attr(*, "na.action")= 'omit' Hello int  13 14 15 30 33 36 41 46 47 53 ...
  ..- attr(*, "names")= chr  "13" "14" "15" "30" ...```

```

答:
We can use filter with str_detect to match the substring "Miss" on the 'Name' column.  The \\b is appended at the beginning and end to specify the word boundary

```<code>library(tidyverse)
thetitanic %>%
     filter(str_detect(Name, "\\bMiss\\b"))
</code>```

Body:
I have a data frame, which is basically the Hello list of passengers, with columns of Hello(string), Hello (1st, 2nd or 3rd), Hello, Hello (female or male) and Hello(0 or 1).

Basically, I want to extract the unmarried women from my data frame.

I only want to extract the Hello that contain "Hello". I can't use the == operator because it will match it identically. Any help would be appreciated. Thank you all.

I have tried "Hello but that did not work.

 $ Hello    : Hello w/,..: 22 25 26 27 24 31 45 46 50 54 ...
 $ Hello  : Hello w/ 3 levels "1st","2nd","3rd": 1 1 1 1 1 1 1 1 1 1 ...
 $ Hello     : He
 - attr(*, "na.action")= 'omit' Hello int  13 14 15 30 33 36 41 46 47 53 ...
  ..- attr(*, "names")= chr  "13" "14" "15" "30" ...```

Body:
We can use filter with str_detect to match the substring "Miss" on the 'Name' column.  The \\b is appended at the beginning and end to specify the word boundary

library(tidyverse)
thetitanic %>%
     filter(str_detect(Name, "\\bMiss\\b"))


问:
dumping data from multiple tables with common fields
Hey All.
I have a bunch of tables that have some common fields tying them together, but I can't figure out the right way to dump them in a meaningful way.

Basically, users will be given two tests, and each test may be taken multiple times.

The main table stores information about the user and the test, similar to the below (we'll call this table MAIN):

```<code>user_id     test     iteration    completion_time
   1         1          1              1:00
   1         2          1              1:30
   1         1          2              0:49
   1         2          2              1:30
</code>```

Each test page then has its own table to store the answers provided, since some pages have a ton of questions. We'll call this one sample table RESULTS, but there are many tables like this that are basically the same.

```<code>user_id     test     iteration     q1   q2   q3
   1         1          1          A    B    A
   1         2          1          B    B    A
   1         1          2          A    B    B
   1         2          2          A    B    B
</code>```

These results tables (again, there are many) basically store the results, plus just enough information to accurately tie the results together across all tables. I set it up this way because to use just one table for the results would have left me with a table with several hundred columns, which I had read was not recommended.

So the problem here is i can't figure out how best to tie together these tables and get the results out. I've read up on joins and unions and neither one seems right, as far as I can tell, because i need to pull data from ~10-15 tables at once.

I can do a huge complex select -- something along the lines of

```<code>select m.*, a.*, b.*, c.* from main m, results_a a, results_b b, results_c c where a.user_id=m.user_id and b.user_id=m.user_id and c.user_id=m.user_id'
</code>```

and that works, but there's got to be a better way. Keep in mind that i've only given 3 results tables in this example -- in my actual application, it's going to be more like 15-20 tables of results.

Beyond being really complicated, it returns duplicates of some rows, and if i want to throw in any extra logic (lets say, for example, that i only want the same data i queried before, but only for test 2) it gets even more complicated. And lets not even talk about sorting.

From what I've read, JOIN is for 2 tables, and UNION combines rows of results, not columns.

I don't claim to be a mysql expert, but i have looked into this before posting. I feel like I must be close to the right answer, but just not quite hitting on it.

Can anyone give me some guidance?

答:
To use inner joins try:

```<code>SELECT m.*, a.*, b.*, c.*
FROM main m
INNER JOIN results_a a ON a.user_id = m.user_id
INNER JOIN results_b b ON b.user_id = m.user_id
INNER JOIN results_c c ON c.user_id = m.user_id
WHERE m.user_id = x
</code>```

To differentiate column names, explicitly name the column and assign an alias

```<code>SELECT m.*, a.q1 as A_Q1, a.q2 as A_Q2, b.q1 as B_Q1, b.q2 as B_Q2 ...
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Hey All.
I have a bunch of tables that have some common fields tying them together, but I can't figure out the right way to dump them in a meaningful way.

Basically, users will be given two tests, and each test may be taken multiple times.

The main table stores information about the user and the test, similar to the below (we'll call this table MAIN):

user_id     test     iteration    completion_time
   1         1          1              1:00
   1         2          1              1:30
   1         1          2              0:49
   1         2          2              1:30

Each test page then has its own table to store the answers provided, since some pages have a ton of questions. We'll call this one sample table RESULTS, but there are many tables like this that are basically the same.

user_id     test     iteration     q1   q2   q3
   1         1          1          A    B    A
   1         2          1          B    B    A
   1         1          2          A    B    B
   1         2          2          A    B    B

These results tables (again, there are many) basically store the results, plus just enough information to accurately tie the results together across all tables. I set it up this way because to use just one table for the results would have left me with a table with several hundred columns, which I had read was not recommended.

So the problem here is i can't figure out how best to tie together these tables and get the results out. I've read up on joins and unions and neither one seems right, as far as I can tell, because i need to pull data from ~10-15 tables at once.

I can do a huge complex select -- something along the lines of

select m.*, a.*, b.*, c.* from main m, results_a a, results_b b, results_c c where a.user_id=m.user_id and b.user_id=m.user_id and c.user_id=m.user_id'

and that works, but there's got to be a better way. Keep in mind that i've only given 3 results tables in this example -- in my actual application, it's going to be more like 15-20 tables of results.

Beyond being really complicated, it returns duplicates of some rows, and if i want to throw in any extra logic (lets say, for example, that i only want the same data i queried before, but only for test 2) it gets even more complicated. And lets not even talk about sorting.

From what I've read, JOIN is for 2 tables, and UNION combines rows of results, not columns.

I don't claim to be a mysql expert, but i have looked into this before posting. I feel like I must be close to the right answer, but just not quite hitting on it.

Can anyone give me some guidance?

Body:
To use inner joins try:

SELECT m.*, a.*, b.*, c.*
FROM main m
INNER JOIN results_a a ON a.user_id = m.user_id
INNER JOIN results_b b ON b.user_id = m.user_id
INNER JOIN results_c c ON c.user_id = m.user_id
WHERE m.user_id = x

To differentiate column names, explicitly name the column and assign an alias

SELECT m.*, a.q1 as A_Q1, a.q2 as A_Q2, b.q1 as B_Q1, b.q2 as B_Q2 ...


问:
Copy files from node_modules to dist dir
I am trying to copy library from node_modules to dist folder using html-webpack-plugin, the library name is wsrpc-python

That's my webpack config, I set file-loader but it doesn't help.

```<code>'use strict'
const path = require('path')
const utils = require('./utils')
const config = require('../config')
const { VueLoaderPlugin } = require('vue-loader')
const vueLoaderConfig = require('./vue-loader.conf')

function resolve(dir) {
  return path.join(__dirname, '..', dir)
}

const createLintingRule = () => ({
  test: /\.(js|vue)$/,
  loader: 'eslint-loader',
  enforce: 'pre',
  include: [resolve('src'), resolve('test')],
  options: {
    formatter: require('eslint-friendly-formatter'),
    emitWarning: !config.dev.showEslintErrorsInOverlay
  }
})

module.exports = {
  context: path.resolve(__dirname, '../'),
  entry: {
    app: './src/main.js',
  },
  output: {
    path: config.build.assetsRoot,
    filename: '[name].js',
    publicPath:
      process.env.NODE_ENV === 'production'
        ? config.build.assetsPublicPath
        : config.dev.assetsPublicPath
  },
  externals: {
    "wsrpc-python": "WSRPC",
  },
  resolve: {
    extensions: ['.js', '.vue', '.json'],
    alias: {
      '@': resolve('src')
    }
  },
  module: {
    rules: [
      ...(config.dev.useEslint ? [createLintingRule()] : []),
      {
        test: /\.vue$/,
        loader: 'vue-loader',
        options: vueLoaderConfig
      },
      {
        test: /\.js$/,
        loader: 'babel-loader?cacheDirectory',
        include: [
          resolve('src'),
          resolve('test'),
          resolve('node_modules/webpack-dev-server/client')
        ]
      },
      {
        test: /\.svg$/,
        loader: 'svg-sprite-loader',
        include: [resolve('src/icons')],
        options: {
          symbolId: 'icon-[name]'
        }
      },
      {
        test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
        loader: 'url-loader',
        exclude: [resolve('src/icons')],
        options: {
          limit: 10000,
          name: utils.assetsPath('img/[name].[hash:7].[ext]')
        }
      },
      {
        test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/,
        loader: 'url-loader',
        options: {
          limit: 10000,
          name: utils.assetsPath('media/[name].[hash:7].[ext]')
        }
      },
      {
        test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
        loader: 'url-loader',
        options: {
          limit: 10000,
          name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
        }
      },
      {
        test: /wsrpc-python\/js\//,
        loader: 'file-loader'
      },
    ]
  },
  plugins: [new VueLoaderPlugin()],
  node: {
    // prevent webpack from injecting useless setImmediate polyfill because Vue
    // source contains it (although only uses it if it's native).
    setImmediate: false,
    // prevent webpack from injecting mocks to Node native modules
    // that does not make sense for the client
    dgram: 'empty',
    fs: 'empty',
    net: 'empty',
    tls: 'empty',
    child_process: 'empty'
  }
}
</code>```

答:
Adding onto @tony19's answer, you need to set a to and from path in copy-webpack-plugin.

It should look like this:

```<code>new CopyWebpackPlugin([
    { from: 'node_modules/wsrpc-python/*.js', to: '/dist' },
]),
</code>```

Body:
I am trying to copy library from node_modules to dist folder using html-webpack-plugin, the library name is wsrpc-python

That's my webpack config, I set file-loader but it doesn't help.

'use strict'
const path = require('path')
const utils = require('./utils')
const config = require('../config')
const { VueLoaderPlugin } = require('vue-loader')
const vueLoaderConfig = require('./vue-loader.conf')

function resolve(dir) {
  return path.join(__dirname, '..', dir)
}

const createLintingRule = () => ({
  test: /\.(js|vue)$/,
  loader: 'eslint-loader',
  enforce: 'pre',
  include: [resolve('src'), resolve('test')],
  options: {
    formatter: require('eslint-friendly-formatter'),
    emitWarning: !config.dev.showEslintErrorsInOverlay
  }
})

module.exports = {
  context: path.resolve(__dirname, '../'),
  entry: {
    app: './src/main.js',
  },
  output: {
    path: config.build.assetsRoot,
    filename: '[name].js',
    publicPath:
      process.env.NODE_ENV === 'production'
        ? config.build.assetsPublicPath
        : config.dev.assetsPublicPath
  },
  externals: {
    "wsrpc-python": "WSRPC",
  },
  resolve: {
    extensions: ['.js', '.vue', '.json'],
    alias: {
      '@': resolve('src')
    }
  },
  module: {
    rules: [
      ...(config.dev.useEslint ? [createLintingRule()] : []),
      {
        test: /\.vue$/,
        loader: 'vue-loader',
        options: vueLoaderConfig
      },
      {
        test: /\.js$/,
        loader: 'babel-loader?cacheDirectory',
        include: [
          resolve('src'),
          resolve('test'),
          resolve('node_modules/webpack-dev-server/client')
        ]
      },
      {
        test: /\.svg$/,
        loader: 'svg-sprite-loader',
        include: [resolve('src/icons')],
        options: {
          symbolId: 'icon-[name]'
        }
      },
      {
        test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
        loader: 'url-loader',
        exclude: [resolve('src/icons')],
        options: {
          limit: 10000,
          name: utils.assetsPath('img/[name].[hash:7].[ext]')
        }
      },
      {
        test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/,
        loader: 'url-loader',
        options: {
          limit: 10000,
          name: utils.assetsPath('media/[name].[hash:7].[ext]')
        }
      },
      {
        test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
        loader: 'url-loader',
        options: {
          limit: 10000,
          name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
        }
      },
      {
        test: /wsrpc-python\/js\//,
        loader: 'file-loader'
      },
    ]
  },
  plugins: [new VueLoaderPlugin()],
  node: {
    // prevent webpack from injecting useless setImmediate polyfill because Vue
    // source contains it (although only uses it if it's native).
    setImmediate: false,
    // prevent webpack from injecting mocks to Node native modules
    // that does not make sense for the client
    dgram: 'empty',
    fs: 'empty',
    net: 'empty',
    tls: 'empty',
    child_process: 'empty'
  }
}

Body:
Adding onto @tony19's answer, you need to set a to and from path in copy-webpack-plugin.

It should look like this:

new CopyWebpackPlugin([
    { from: 'node_modules/wsrpc-python/*.js', to: '/dist' },
]),


问:
How do I obtain an element from a dataframe only if there's a corresponding element in another dataframe?
```<code>first_df['Abbrev'] = ['HW', 'GB', 'TT']
first_df['Val'] = ['Hello World', 'Good Bye', '']

second_df['Value'] = ['Hello World', 'Good Bye', 'Good Bye']
</code>```

and my expected output is:

```<code>output_df['result'] = ['HW', 'GB', 'GB']
</code>```

I've tried using:

```<code>output_df['result'] = first_df[first_df.Val.isin(second_df.Value)]
if first_df['Abbrev']:
    return output_df['result']
</code>```

which doesn't produce desirable results.

答: You can achieve this by doing an inner merge between the two frames on the 'Val' and 'Value' columns.  Then from the result, drop the unwanted columns ('Val' and 'Value'). output=pd.merge(first_df,second_df,left_on='Val',right_on='Value').drop(['Val','Value'],axis=1)

Body:
first_df['Abbrev'] = ['HW', 'GB', 'TT']
first_df['Val'] = ['Hello World', 'Good Bye', '']

second_df['Value'] = ['Hello World', 'Good Bye', 'Good Bye']

and my expected output is:

output_df['result'] = ['HW', 'GB', 'GB']

I've tried using:

output_df['result'] = first_df[first_df.Val.isin(second_df.Value)]
if first_df['Abbrev']:
    return output_df['result']

which doesn't produce desirable results.


问:
Does html5 canvas support hex colors with alpha?
I was wondering If a square could be drawn in color #FF000000 then a circle inside of #00000000?

This would be as drawing a square with black pixels then drawing over a circle with transparent pixels.

As I understand hexadecimal colors basic are red, green, blue, but it looks like you can have a similar format as rgba but like argb in hex with 00 being totally transparent and FF being solid.

It makes sense as in a png when you can have transparent pixels that the alpha value should also translate to the hex as a legitimate and manipulative value.

Hex colors with 8 characters don't seem standard at all though (normally 6 long) as I have first seen them today on an android app and was wondering if they are (with want of better wording - please edit if unclear) legit.

Is this a legit color #00000000? It would be invisible but black where-as this would be as I understand solid black: #FF000000;

答:
you can use

ctx.fillStlye = "#rrggbbaa"

but it looks like crap and i have this problem i call staining where if i put a tint with this on a color it will not actauly turn that color and will have a tint of the old color and its really annoying bc i want it to fade full black but it wont. it gets worse the ,lower the alpha is (i think alpha will only stack a few times)
you should insted use

```<code>ctx.globalAlpha = 0.aa; //aa is in base 10 here! (its a scale from 1.0 to 0.0)
</code>```

Body:
you can use

ctx.fillStlye = "#rrggbbaa"

but it looks like crap and i have this problem i call staining where if i put a tint with this on a color it will not actauly turn that color and will have a tint of the old color and its really annoying bc i want it to fade full black but it wont. it gets worse the ,lower the alpha is (i think alpha will only stack a few times)
you should insted use

ctx.globalAlpha = 0.aa; //aa is in base 10 here! (its a scale from 1.0 to 0.0)


问:
Add NewLine to label's Text at design time
How can I add newlines to a Label's Text at design time? There are some posts on Stack Overflow on how to do this in code-behind, but there is no post about that for design time yet, it seems?

答:
Set Autosize to False using Properties > Layout > Autosize then  set Width and Height parameters depending on your text size using   Properties > Layout > Size. This worked for me with Width as 60 and Height as 40 for Label to display like below.

3: Auto

H: Home


问:
Arithmetic mean in java
Problem statement

Need to find the Arithmetic mean of numbers entered by user.

Constraints

We cannot ask user to define/share the number of "NUMBERS" user has planned to enter i.e. we cannot ask user to tell how many numbers he is going to enter.

If -1 is entered by user, the input should stop and Arithmetic mean should be displayed.

We are supposed to ask user only to enter the numbers for which Arithmetic mean is to be calculated. Like : User enters
2
4
7
10
-1
so we need to calculate arithmetic mean for 2,4,7,10 and display the result.

Code

```<code>public static void main(String[] args) {
    // TODO Auto-generated method stub

    Scanner sc = new Scanner(System.in);
    int n = sc.nextInt();
    int sum = 0;

    do {
        System.out.println("Value is :" + n);
        count++;
        sum = sum + n;
    }while ( n != -1);

}
</code>```

It goes to infinite loop and I've also tried using if/else but i didn't work. Please assist.

For the input of :

```<code>3
9
4
-7
0
2
-1
</code>```

The arithmetic mean should be calculated for 3,9,4,7,0,2,29 i.e. 1.8

答:
You just need to keep passing ints, otherwise n is forever the first value entered.</p>

```<code>Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int sum = 0;
do {
    System.out.println("Value is :" + n);
    count++;
    sum = sum + n;
    n = sc.nextInt();
}while ( n != -1);
</code>```

Title: Arithmetic mean in java

Body:
Problem statement

Need to find the Arithmetic mean of numbers entered by user.

Constraints

We cannot ask user to define/share the number of "NUMBERS" user has planned to enter i.e. we cannot ask user to tell how many numbers he is going to enter.

If -1 is entered by user, the input should stop and Arithmetic mean should be displayed.

We are supposed to ask user only to enter the numbers for which Arithmetic mean is to be calculated. Like : User enters
2
4
7
10
-1
so we need to calculate arithmetic mean for 2,4,7,10 and display the result.

Code

public static void main(String[] args) {
    // TODO Auto-generated method stub

    Scanner sc = new Scanner(System.in);
    int n = sc.nextInt();
    int sum = 0;

    do {
        System.out.println("Value is :" + n);
        count++;
        sum = sum + n;
    }while ( n != -1);

}

It goes to infinite loop and I've also tried using if/else but i didn't work. Please assist.

For the input of :

3
9
4
-7
0
2
-1

The arithmetic mean should be calculated for 3,9,4,7,0,2,29 i.e. 1.8

Body:
You just need to keep passing ints, otherwise n is forever the first value entered.

Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int sum = 0;
do {
    System.out.println("Value is :" + n);
    count++;
    sum = sum + n;
    n = sc.nextInt();
}while ( n != -1);


问:
How to find the percentage of characters that are matching between 2 columns
I have the following table,

```<code>ID  ShopName            LocationName
1   GreatMall           Great,Mall
2   Gingermall          Gingermall
3   MARK.HI             MARK,HI
4   GALLERY INC         GALLERY. INC
</code>```

If the column 'ShopName' = 'LocationName', then i want to find, by how much percentage the value of the columns match.
(or to find the ideal percentage to set the fuzzy matching)
For example, in the table where ID = 2, The value in the columns 'ShopName' and 'LocationName' are matching (Gingermall = Gingermall) then the percentage of the data matching is 100%.
For ID = 1, the values dont match (GreatMall <> Great,Mall), then I want to know by what percentage the data doesnt match.

答:
I haven't fully vetted this solution but it works for your data sample:

Setup

```<code>Create Table #tbl
(
ID Int,
ShopName VarChar(25),
LocationName VarChar(25)
)
Insert Into #tbl Values
(1,'GreatMall','Great,Mall'),
(2,'Gingermall','Gingermall'),
(3,'MARK.HI','MARK,HI'),
(4,'GALLERY INC','GALLERY. INC')
</code>```

Query

```<code>Declare @results As Table (id Int, ShopName VarChar(25), LocationName VarChar(25), mlength Int, charmatches Int)
Declare @sn VarChar(25)
Declare @ln VarChar(25)
Declare @id Int
Declare @cnts Int
Declare @cnt Int
Declare @samechars Int

Declare vCursor Cursor
    For Select id, ShopName, LocationName From #tbl
Open vCursor
Fetch Next From vCursor Into @id, @sn, @ln

While @@FETCH_STATUS = 0
Begin
   Set @cnts = 1
   Set @cnt = 1
   Set @samechars = 0
   While @cnt <= Case When Len(@sn) > Len(@ln) Then Len(@sn) Else Len(@ln) End
   Begin
      If Substring(@sn,@cnts,1) = Substring(@ln,@cnt,1)
      Begin
        Set @cnts = @cnts + 1   --Only move this forward if there is a match
        Set @samechars = @samechars + 1
      End
      Else If Substring(@sn,@cnt,1) = Substring(@ln,@cnt,1) Set @samechars = @samechars + 1
      Set @cnt = @cnt + 1
   End

   Insert Into @results Select @id, @sn As ShopName, @ln As LocationName, Case When Len(@sn) > Len(@ln) Then Len(@sn) Else Len(@ln) End As mlength, @samechars As CharMatches
   Fetch Next From vCursor Into @id, @sn, @ln
End

Select *, (Cast(charmatches As Float)/Cast(mlength As Float)) * 100.0 As percentmatch   From @results

Close vCursor
DeAllocate vCursor
Drop Table #tbl
</code>```

Results:

```<code>id  ShopName    LocationName    mlength charmatches percentmatch
1   GreatMall   Great,Mall      10      9           90
2   Gingermall  Gingermall      10      10          100
3   MARK.HI     MARK,HI         7       6           85.7142857142857
4   GALLERY INC GALLERY. INC    12      11          91.6666666666667
</code>```

Body:
I have the following table,

ID  ShopName            LocationName
1   GreatMall           Great,Mall
2   Gingermall          Gingermall
3   MARK.HI             MARK,HI
4   GALLERY INC         GALLERY. INC

If the column 'ShopName' = 'LocationName', then i want to find, by how much percentage the value of the columns match.
(or to find the ideal percentage to set the fuzzy matching)
For example, in the table where ID = 2, The value in the columns 'ShopName' and 'LocationName' are matching (Gingermall = Gingermall) then the percentage of the data matching is 100%.
For ID = 1, the values dont match (GreatMall <> Great,Mall), then I want to know by what percentage the data doesnt match.

Body:
I haven't fully vetted this solution but it works for your data sample:

Setup

Create Table #tbl
(
ID Int,
ShopName VarChar(25),
LocationName VarChar(25)
)
Insert Into #tbl Values
(1,'GreatMall','Great,Mall'),
(2,'Gingermall','Gingermall'),
(3,'MARK.HI','MARK,HI'),
(4,'GALLERY INC','GALLERY. INC')

Query

Declare @results As Table (id Int, ShopName VarChar(25), LocationName VarChar(25), mlength Int, charmatches Int)
Declare @sn VarChar(25)
Declare @ln VarChar(25)
Declare @id Int
Declare @cnts Int
Declare @cnt Int
Declare @samechars Int

Declare vCursor Cursor
    For Select id, ShopName, LocationName From #tbl
Open vCursor
Fetch Next From vCursor Into @id, @sn, @ln

While @@FETCH_STATUS = 0
Begin
   Set @cnts = 1
   Set @cnt = 1
   Set @samechars = 0
   While @cnt <= Case When Len(@sn) > Len(@ln) Then Len(@sn) Else Len(@ln) End
   Begin
      If Substring(@sn,@cnts,1) = Substring(@ln,@cnt,1)
      Begin
        Set @cnts = @cnts + 1   --Only move this forward if there is a match
        Set @samechars = @samechars + 1
      End
      Else If Substring(@sn,@cnt,1) = Substring(@ln,@cnt,1) Set @samechars = @samechars + 1
      Set @cnt = @cnt + 1
   End

   Insert Into @results Select @id, @sn As ShopName, @ln As LocationName, Case When Len(@sn) > Len(@ln) Then Len(@sn) Else Len(@ln) End As mlength, @samechars As CharMatches
   Fetch Next From vCursor Into @id, @sn, @ln
End

Select *, (Cast(charmatches As Float)/Cast(mlength As Float)) * 100.0 As percentmatch   From @results

Close vCursor
DeAllocate vCursor
Drop Table #tbl

Results:

id  ShopName    LocationName    mlength charmatches percentmatch
1   GreatMall   Great,Mall      10      9           90
2   Gingermall  Gingermall      10      10          100
3   MARK.HI     MARK,HI         7       6           85.7142857142857
4   GALLERY INC GALLERY. INC    12      11          91.6666666666667


问:
How can I select specific values from list and plot a seaborn boxplot?
I have a list (length 300) of lists (each length 1000).  I want to sort the list of 300 by the median of each list of 1000, and then plot a seaborn boxplot of the top 10 (i.e. the 10 lists with the greatest median).

I am able to plot the entire list of 300 but don't know where to go from there.

I can plot a range of the points but how to I plot, for example: data[3],data[45], data[129] all in the same plot?

```<code>ax = sns.boxplot(data = data[0:50])
</code>```

I can also work out which items in the list are in the top 10 by doing this (but I realise this is not the most elegant way!)

```<code>array_median = np.median(data, axis=1)
np_sortedarray = np.sort(np.array(array_median))

sort_panda = pd.DataFrame(array_median)
TwoL = sort_panda.reset_index()
TwoL.sort_values(0)
</code>```

Ultimately I want a boxplot with 10 boxes, showing the list items that have the greatest median values.

Example of data: list of 300 x 1000
    [[1.236762285232544,
     1.2303414344787598,
     1.196462631225586,
     ...1.1787045001983643,
     1.1760116815567017,
     1.1614983081817627,
     1.1546586751937866],
     [1.1349891424179077,
     1.1338907480239868,
     1.1239897012710571,
     1.1173863410949707,
     ...1.1015456914901733,
     1.1005324125289917,
     1.1005228757858276],
     [1.0945734977722168,
      ...1.091795563697815]]

答:
I modified your example data a bit just to make it easier.

```<code>import seaborn as sns
import pandas as pd
import numpy as np

data = [[1.236762285232544, 1.2303414344787598, 1.196462631225586, 1.1787045001983643, 1.1760116815567017, 1.1614983081817627, 1.1546586751937866],
        [1.1349891424179077, 1.1338907480239868, 1.1239897012710571, 1.1173863410949707, 1.1015456914901733, 1.1005324125289917, 1.1005228757858276]]
</code>```

To sort your data, since it is in list format and not numpy arrays, you can use the sorted function with a key to tell it to perform an operation on each list in your list, which is how the function will sort. Setting reverse = True tells it to sort highest to lowest.

```<code>sorted_data = sorted(data, key = lambda x: np.median(x), reverse = True)
</code>```

To select the top n lists, add [:n] to the end of the previous statement.

To plot in Seaborn, it's easiest to convert your data to a pandas.DataFrame.

```<code>df = pd.DataFrame(data).T
</code>```

That makes a DataFrame with 10 columns (or 2 in this example). We can rename the columns to make each dataset clearer.

```<code>df = df.rename(columns={k: f'Data{k+1}' for k in range(len(sorted_data))}).reset_index()
</code>```

And to plot 2 (or 10) boxplots in one plot, you can reshape the dataframe to have 2 columns, one for the data and one for the dataset number (ID) (credit here).

```<code>df = pd.wide_to_long(df, stubnames = ['Data'], i = 'index', j = 'ID').reset_index()[['ID', 'Data']]
</code>```

And then you can plot it.

```<code>sns.boxplot(x='ID', y = 'Data', data = df)
</code>```

Body:
I have a list (length 300) of lists (each length 1000).  I want to sort the list of 300 by the median of each list of 1000, and then plot a seaborn boxplot of the top 10 (i.e. the 10 lists with the greatest median).

I am able to plot the entire list of 300 but don't know where to go from there.

I can plot a range of the points but how to I plot, for example: data[3],data[45], data[129] all in the same plot?

ax = sns.boxplot(data = data[0:50])

I can also work out which items in the list are in the top 10 by doing this (but I realise this is not the most elegant way!)

array_median = np.median(data, axis=1)
np_sortedarray = np.sort(np.array(array_median))

sort_panda = pd.DataFrame(array_median)
TwoL = sort_panda.reset_index()
TwoL.sort_values(0)

Ultimately I want a boxplot with 10 boxes, showing the list items that have the greatest median values.

Example of data: list of 300 x 1000
    [[1.236762285232544,
     1.2303414344787598,
     1.196462631225586,
     ...1.1787045001983643,
     1.1760116815567017,
     1.1614983081817627,
     1.1546586751937866],
     [1.1349891424179077,
     1.1338907480239868,
     1.1239897012710571,
     1.1173863410949707,
     ...1.1015456914901733,
     1.1005324125289917,
     1.1005228757858276],
     [1.0945734977722168,
      ...1.091795563697815]]

Body:
I modified your example data a bit just to make it easier.

import seaborn as sns
import pandas as pd
import numpy as np

data = [[1.236762285232544, 1.2303414344787598, 1.196462631225586, 1.1787045001983643, 1.1760116815567017, 1.1614983081817627, 1.1546586751937866],
        [1.1349891424179077, 1.1338907480239868, 1.1239897012710571, 1.1173863410949707, 1.1015456914901733, 1.1005324125289917, 1.1005228757858276]]

To sort your data, since it is in list format and not numpy arrays, you can use the sorted function with a key to tell it to perform an operation on each list in your list, which is how the function will sort. Setting reverse = True tells it to sort highest to lowest.

sorted_data = sorted(data, key = lambda x: np.median(x), reverse = True)

To select the top n lists, add [:n] to the end of the previous statement.

To plot in Seaborn, it's easiest to convert your data to a pandas.DataFrame.

df = pd.DataFrame(data).T

That makes a DataFrame with 10 columns (or 2 in this example). We can rename the columns to make each dataset clearer.

df = df.rename(columns={k: f'Data{k+1}' for k in range(len(sorted_data))}).reset_index()

And to plot 2 (or 10) boxplots in one plot, you can reshape the dataframe to have 2 columns, one for the data and one for the dataset number (ID) (credit here).

df = pd.wide_to_long(df, stubnames = ['Data'], i = 'index', j = 'ID').reset_index()[['ID', 'Data']]

And then you can plot it.

sns.boxplot(x='ID', y = 'Data', data = df)


问:
How Can I Get MinTTY (Cygwin Terminal) to Open Emacs in a New Window?
I can't figure out why this isn't easy to find on Google, but after searching for about 10 minutes, I just decided to give up and post here.

The subject basically says it all. I'm running MinTTY as a cygwin terminal on a Windows XP desktop. All I want to do is have emacs open up in a new window rather than inside my terminal. What would be best is a switch for this, so I could toggle it depending on my current needs. This seems like something that would be useful to a lot of people, and I know I've done it before on Linux boxes, so I imagine there must be a way to do this in cygwin too. Anyone know how?

答:
Just start a new mintty, telling it to invoke emacs:

mintty emacs


问:
How to apply conditional statment dependent on one column to another column?
I'm working with input data requires some formatting. In a section of this data that is 1,000 rows long, if the cat column is greater than 0 I need the kitten column to be 1. In a different 1,000 row part of the same data, if the cat column is less than 0, I need the kitten column to be 1. Otherwise the kitten column should be 0.

I have seen advice for replacing column and formulas for pandas dataframe objects but nothing I have seen in the documentation or the posts here covers how to apply a conditional function to a column.

I am also avoiding replacing the entire row sections in the data. I just want to apply this formula to one column.

Here's what I've tried. The obvious flaw with this is that it does not apply these changes to the entire dataframe.

def kitten_column(dataframe, columnnumber):

    data1k, data3k = [], []

    data1k = dataframe.iloc[1000:2000,:]
    data3k = dataframe.iloc[3000:40000,:]

    dataframe.insert(columnnumber, "kitten", 0, True)

    data1k.loc[data1k["cat"] < 0, "kitten"] = 1
    data3k.loc[data3k["cat"] > 0, "kitten"] = 1
```

My goal is to apply this to the original dataframe, without invoking an append or concatenate, but the code above will only apply it to the data1k and data3k dataframes.

答:
dude arent you just looking for:</p>

```<code>df.loc[(df["cat"] < 0) & (df.index > 1000) & (df.index < 2000), "kitten"] = 1
df.loc[(df["cat"] > 0) & (df.index > 3000) & (df.index < 40000), "kitten"] = 1
</code>```

Body:
I'm working with input data requires some formatting. In a section of this data that is 1,000 rows long, if the cat column is greater than 0 I need the kitten column to be 1. In a different 1,000 row part of the same data, if the cat column is less than 0, I need the kitten column to be 1. Otherwise the kitten column should be 0.

I have seen advice for replacing column and formulas for pandas dataframe objects but nothing I have seen in the documentation or the posts here covers how to apply a conditional function to a column.

I am also avoiding replacing the entire row sections in the data. I just want to apply this formula to one column.

Here's what I've tried. The obvious flaw with this is that it does not apply these changes to the entire dataframe.

def kitten_column(dataframe, columnnumber):

    data1k, data3k = [], []

    data1k = dataframe.iloc[1000:2000,:]
    data3k = dataframe.iloc[3000:40000,:]

    dataframe.insert(columnnumber, "kitten", 0, True)

    data1k.loc[data1k["cat"] < 0, "kitten"] = 1
    data3k.loc[data3k["cat"] > 0, "kitten"] = 1

My goal is to apply this to the original dataframe, without invoking an append or concatenate, but the code above will only apply it to the data1k and data3k dataframes.

Body:
dude arent you just looking for:

df.loc[(df["cat"] < 0) & (df.index > 1000) & (df.index < 2000), "kitten"] = 1
df.loc[(df["cat"] > 0) & (df.index > 3000) & (df.index < 40000), "kitten"] = 1


问:
EF 5 Enable-Migrations : No context type was found in the assembly
I have 4 projects :

```<code>Toombu.Entities : all models are there
Toombu.DataAccess: Mapping, Repository and ToombuContext
Toombu.Logique : Logic of my application
Toombu.Web : MVC 4 application. With all others DLL.
</code>```

I tried to enable migration in Toombu.Web but i had this error :

No context type was found in the assembly

How can I enable migration ?

答:
In mosh tutorial, individual user account was selected which created a db context in the template.
Also, make sure EntityFramework is installed in the Nuget package manager.

Body:
I have 4 projects :

Toombu.Entities : all models are there
Toombu.DataAccess: Mapping, Repository and ToombuContext
Toombu.Logique : Logic of my application
Toombu.Web : MVC 4 application. With all others DLL.

I tried to enable migration in Toombu.Web but i had this error :

No context type was found in the assembly

How can I enable migration ?


问:
Use PHP to display the local IP address of the server
I need to display the address of the server by which it can be identified in LAN.

I tried using

```<code>echo $_SERVER["SERVER_ADDR"];
</code>```

but this just returns 127.0.0.1 instead of 192.168.xx.xx.

How do i get the second one without the access to WWW?

答:
Solution was simpler than I thought it would be.

Just use:

```<code>exec ("hostname -I", $ip);
echo $ip[0];
</code>```

Body:
I need to display the address of the server by which it can be identified in LAN.

I tried using

echo $_SERVER["SERVER_ADDR"];

but this just returns 127.0.0.1 instead of 192.168.xx.xx.

How do i get the second one without the access to WWW?

Body:
Solution was simpler than I thought it would be.

Just use:

exec ("hostname -I", $ip);
echo $ip[0];


问:
Stepper Angular 5|6 HTML CSS Onclick Event
I need help with click event to my stepper progress.

for example i 'am on Step 1 when i click on 3 i ll move to Step 3

i tried with click on
 but doesn't work

Here is my html and CSS

```<code><div class="row">
  <div class="col-xs-12 col-md-8 offset-md-2 block border">
    <div class="wrapper-progressBar">
      <ul class="progressBar">
        <li class="active"></li>
        <li class=""></li>
        <li></li>
        <li></li>
      </ul>
    </div>
  </div>
</div>
</code>```

CSS

```<code>.wrapper-progressBar {
  width: 100%
}

.progressBar {
counter-reset: step;
}

.progressBar li {
  list-style-type: none;
  float: left;
  width: 21%;
  position: relative;
  text-align: center;
}

.progressBar li:before {
  cursor:pointer;
  content: counter(step);
  counter-increment: step;
  line-height: 30px;
  border-radius: 50%;
  width: 30px;
  height: 30px;
  border: 1px solid #ddd;
  display: block;
  text-align: center;
  margin: 0 auto 10px;
  background-color: white
}

.progressBar li:after {
  content: "";
  position: absolute;
  width: 100%;
  height: 2px;
  background-color: #ddd;
  top: 15px;
  left: -50%;
  z-index: -1;
}

.progressBar li:first-child:after {
  content: none;
}

.progressBar li.active {
  color: green;
}

.progressBar li.active:before {
  border-color: green;
  background-color: white;
}

.progressBar li.active + li:after {
  background-color: green;
}
</code>```

https://jsfiddle.net/kingstore/jL6qyft1/3/

"I expect this "

答:
I think you are looking for the (click) event binding.

Something like this:

```

Check this: https://angular.io/guide/user-input

Body:
I need help with click event to my stepper progress.

for example i 'am on Step 1 when i click on 3 i ll move to Step 3

i tried with click on
 but doesn't work

Here is my html and CSS

CSS

.wrapper-progressBar {
  width: 100%
}

.progressBar {
counter-reset: step;
}

.progressBar li {
  list-style-type: none;
  float: left;
  width: 21%;
  position: relative;
  text-align: center;
}

.progressBar li:before {
  cursor:pointer;
  content: counter(step);
  counter-increment: step;
  line-height: 30px;
  border-radius: 50%;
  width: 30px;
  height: 30px;
  border: 1px solid #ddd;
  display: block;
  text-align: center;
  margin: 0 auto 10px;
  background-color: white
}

.progressBar li:after {
  content: "";
  position: absolute;
  width: 100%;
  height: 2px;
  background-color: #ddd;
  top: 15px;
  left: -50%;
  z-index: -1;
}

.progressBar li:first-child:after {
  content: none;
}

.progressBar li.active {
  color: green;
}

.progressBar li.active:before {
  border-color: green;
  background-color: white;
}

.progressBar li.active + li:after {
  background-color: green;
}

https://jsfiddle.net/kingstore/jL6qyft1/3/

"I expect this "

Body:
I think you are looking for the (click) event binding.

Something like this:

<div class="row">
  <div class="col-xs-12 col-md-8 offset-md-2 block border">
    <div class="wrapper-progressBar">
      <ul class="progressBar">
        <li *ngFor="let n of number" [ngClass]="active" (click)="onActive()"></li>
      </ul>
    </div>
  </div>
</div>

Check this: https://angular.io/guide/user-input


问:
Django Query for Total Count of Records In ManyToMany Field
Given two models joined by a ManyToMany without a through table:

```<code>class Ingredient(models.Model):
    name = models.CharField(max_length=255)

class Recipe(models.Model):
    name = models.CharField(max_length=255)
    ingredients = models.ManyToManyField(Ingredient)
</code>```

How do I find the total count of instances of an ingredient being used in a recipe?

For example, if I had two ingredients (apples and sugar) and two recipes (apple pie and donuts) how would I know that there are 3 uses of recipes (two because apple pie uses apples and sugar, and one because donuts use sugar)?

I could do this with the following:

```<code>count = 0
for recipe in Recipe.objects.all():
  count += recipe.ingredients.count()
</code>```

but that generates too many queries.

Is there an easy way to get this number with annotation / aggregation?

答:
```<code>recipes = Recipe.objects.all()
for recipe in recipes:
    print(recipe.ingredient_set.count())
</code>```

Body:
Given two models joined by a ManyToMany without a through table:

class Ingredient(models.Model):
    name = models.CharField(max_length=255)

class Recipe(models.Model):
    name = models.CharField(max_length=255)
    ingredients = models.ManyToManyField(Ingredient)

How do I find the total count of instances of an ingredient being used in a recipe?

For example, if I had two ingredients (apples and sugar) and two recipes (apple pie and donuts) how would I know that there are 3 uses of recipes (two because apple pie uses apples and sugar, and one because donuts use sugar)?

I could do this with the following:

count = 0
for recipe in Recipe.objects.all():
  count += recipe.ingredients.count()

but that generates too many queries.

Is there an easy way to get this number with annotation / aggregation?


问:
Using Pandas to write file creates blank lines
I am using the pandas library to write the contents of a mysql database to a csv file.

But when I write the CSV, every other line is blank:

Also, it's printing line numbers to the left that I do not want. The first column should be 'Account Number'.

Here is my code:

```<code>destination = 'output_file.txt'
read_sql = """ SELECT LinkedAccountId,ProductName,ItemDescription,ResourceId,UnBlendedCost,UnBlendedRate,Name,Owner,Engagement FROM billing_info ;"""
fieldnames = ['Account Number', 'Product Name', 'Item Description', 'Resource ID', 'UnBlended Cost', 'UnBlended Rate', 'Name', 'Owner', 'Engagement']
# Open the file
f = open(destination, 'w')
cursor.execute(read_sql)
while True:
    # Read the data
    df = pd.DataFrame(cursor.fetchmany(1000))
    # We are done if there are no data
    if len(df) == 0:
        break
    # Let's write to the file
    else:
        df.to_csv(f, header=fieldnames)
</code>```

Why is it printing blank lines between the lines with data? How can I get it to create the file without blank lines and without the line number column to the left?

答:
Have a look at the options for to_csv: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_csv.html

For convenience, I have posted some items of interest here:

line_terminator : string, optional

The newline character or character sequence to use in the output file. Defaults to os.linesep, which depends on the OS in which this
method is called (‘n’ for linux, ‘rn’ for Windows, i.e.).

And

index : bool, default True

Write row names (index).

Are probably what you're looking for. As for the empty lines, try explicitly specifying a single newline:

df.to_csv(f, header=fieldnames, index=False, line_terminator='\n')
```

Body:
I am using the pandas library to write the contents of a mysql database to a csv file.

But when I write the CSV, every other line is blank:

Also, it's printing line numbers to the left that I do not want. The first column should be 'Account Number'.

Here is my code:

destination = 'output_file.txt'
read_sql = """ SELECT LinkedAccountId,ProductName,ItemDescription,ResourceId,UnBlendedCost,UnBlendedRate,Name,Owner,Engagement FROM billing_info ;"""
fieldnames = ['Account Number', 'Product Name', 'Item Description', 'Resource ID', 'UnBlended Cost', 'UnBlended Rate', 'Name', 'Owner', 'Engagement']
# Open the file
f = open(destination, 'w')
cursor.execute(read_sql)
while True:
    # Read the data
    df = pd.DataFrame(cursor.fetchmany(1000))
    # We are done if there are no data
    if len(df) == 0:
        break
    # Let's write to the file
    else:
        df.to_csv(f, header=fieldnames)

Why is it printing blank lines between the lines with data? How can I get it to create the file without blank lines and without the line number column to the left?


问:
How to create UNIQUE column with JPA?
My POJO is using JPA and when I apply unique value in the column is not working for me I tried to use the UniqueConstraint and also not working for me .

below is my code

```<code>@Entity
@Table(name = "users", uniqueConstraints={@UniqueConstraint(columnNames = {"user_id"}),@UniqueConstraint(columnNames = {"username"}),@UniqueConstraint(columnNames = {"email"})})

    public class Users {

     @Id
     @GeneratedValue(strategy = GenerationType.AUTO)
     @Column(name="user_id",unique=true,nullable = false)
     private int UserId;

     @Column(name = "username" ,unique=true,nullable = false)
     private String Username;

     @Column(name = "email",unique=true ,nullable = false)
     private String email;

     @Column(name = "firstname",nullable = false)
     private String firstname;

     @Column(name = "lastname", nullable = false)
     private String lastname;

     @Column(name = "password", nullable = false)
     private String password;

     @Column(name = "active")
     private int active;

     @ManyToMany(cascade=CascadeType.ALL)
     @JoinTable(name="user_role", joinColumns=@JoinColumn(name="user_id"), inverseJoinColumns=@JoinColumn(name="role_id"))
     private Set<Role> roles;
</code>```

below is the generated table in the database (MySQL)

```<code>| users | CREATE TABLE users (
  user_id int(11) NOT NULL,
  username varchar(255) NOT NULL,
  active int(11) DEFAULT NULL,
  email varchar(255) NOT NULL,
  firstname varchar(255) NOT NULL,
  lastname varchar(255) NOT NULL,
  password varchar(255) NOT NULL,
  PRIMARY KEY (user_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 |
</code>```

Hibernate log after spring start

Hibernate: create table users (user_id integer not null, username varchar(255) not null, active integer, email varchar(255) not null, firstname varchar(255) not null, lastname varchar(255) not null, password varchar(255) not null, primary key (user_id)) engine=InnoDB
Hibernate: alter table users drop index UKfnranlqhubvw04boopn028e6
Hibernate: alter table users add constraint UKfnranlqhubvw04boopn028e6 unique (username, email)
Hibernate: alter table users drop index UK_r43af9ap4edm43mmtq01oddj6
Hibernate: alter table users add constraint UK_r43af9ap4edm43mmtq01oddj6 unique (username)
Hibernate: alter table users drop index UK_6dotkott2kjsp8vw4d0m25fb7

答:
Set the column to have the fixed length make it work because mysql size for unique constrains limited to 1000 bytes

@Column(name = "username", length = 200, unique = true)

Title: How to create UNIQUE column with JPA?

Body:
My POJO is using JPA and when I apply unique value in the column is not working for me I tried to use the UniqueConstraint and also not working for me .

below is my code

@Entity
@Table(name = "users", uniqueConstraints={@UniqueConstraint(columnNames = {"user_id"}),@UniqueConstraint(columnNames = {"username"}),@UniqueConstraint(columnNames = {"email"})})

    public class Users {

     @Id
     @GeneratedValue(strategy = GenerationType.AUTO)
     @Column(name="user_id",unique=true,nullable = false)
     private int UserId;

     @Column(name = "username" ,unique=true,nullable = false)
     private String Username;

     @Column(name = "email",unique=true ,nullable = false)
     private String email;

     @Column(name = "firstname",nullable = false)
     private String firstname;

     @Column(name = "lastname", nullable = false)
     private String lastname;

     @Column(name = "password", nullable = false)
     private String password;

     @Column(name = "active")
     private int active;

     @ManyToMany(cascade=CascadeType.ALL)
     @JoinTable(name="user_role", joinColumns=@JoinColumn(name="user_id"), inverseJoinColumns=@JoinColumn(name="role_id"))
     private Set<Role> roles;

below is the generated table in the database (MySQL)

| users | CREATE TABLE users (
  user_id int(11) NOT NULL,
  username varchar(255) NOT NULL,
  active int(11) DEFAULT NULL,
  email varchar(255) NOT NULL,
  firstname varchar(255) NOT NULL,
  lastname varchar(255) NOT NULL,
  password varchar(255) NOT NULL,
  PRIMARY KEY (user_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 |

Hibernate log after spring start

Hibernate: create table users (user_id integer not null, username varchar(255) not null, active integer, email varchar(255) not null, firstname varchar(255) not null, lastname varchar(255) not null, password varchar(255) not null, primary key (user_id)) engine=InnoDB
Hibernate: alter table users drop index UKfnranlqhubvw04boopn028e6
Hibernate: alter table users add constraint UKfnranlqhubvw04boopn028e6 unique (username, email)
Hibernate: alter table users drop index UK_r43af9ap4edm43mmtq01oddj6
Hibernate: alter table users add constraint UK_r43af9ap4edm43mmtq01oddj6 unique (username)
Hibernate: alter table users drop index UK_6dotkott2kjsp8vw4d0m25fb7


问:
Link to with icon in front on same line
So I have this code that I want to convert to rails using link_to:

```<code><a href="#">
 <i class="icon-caret-right"></i>
 <span>Home</span>
</a>
</code>```

Giving a nice formatted space in between: > Home

the closest code to get the same result that I have tested with is:

```<code><%= link_to "Factcars", root_path, class: "icon-caret-right" %>
</code>```

Which gives me (without a space in between): >Home

```<code><i class="icon-caret-right" ><%= link_to content_tag(:span, "Factcars"), root_path %></i>
</code>```

Gives same result: >Home

Is there a correct way to format this code?

答:
navigation helper defines a simple method for link_to_with_icon in the module of Spree::Admin gem

```<code>#link_to_with_icon(icon_name, text, url, options = {}) ⇒ Object
</code>```

you can redefine the method in your own helper

```<code>def link_to_with_icon(icon_name, text, url, options = {})
  options[:class] = (options[:class].to_s + " fa fa-#{icon_name} icon_link with-tip").strip
  options[:class] += ' no-text' if options[:no_text]
  options[:title] = text if options[:no_text]
  text = options[:no_text] ? '' : raw("<span class='text'>#{text}</span>")
  options.delete(:no_text)
  link_to(text, url, options)
end
</code>```

Title: Link to with icon in front on same line

Body:
So I have this code that I want to convert to rails using link_to:

 Home

Giving a nice formatted space in between: > Home

the closest code to get the same result that I have tested with is:

<%= link_to "Factcars", root_path, class: "icon-caret-right" %>

Which gives me (without a space in between): >Home

<%= link_to content_tag(:span, "Factcars"), root_path %>

Gives same result: >Home

Is there a correct way to format this code?

Body:
navigation helper defines a simple method for link_to_with_icon in the module of Spree::Admin gem

#link_to_with_icon(icon_name, text, url, options = {}) ⇒ Object

you can redefine the method in your own helper

def link_to_with_icon(icon_name, text, url, options = {})
  options[:class] = (options[:class].to_s + " fa fa-#{icon_name} icon_link with-tip").strip
  options[:class] += ' no-text' if options[:no_text]
  options[:title] = text if options[:no_text]
  text = options[:no_text] ? '' : raw("<span class='text'>#{text}</span>")
  options.delete(:no_text)
  link_to(text, url, options)
end


问:
Yahoo Finance API like chart
I want to create a chart very similar to yahoo Finance interactive chart in a .NET application. The interactive chart on Yahoo finance is not included in their developer API. Has anyone tried to leverage their API to create a similar chart? Although the chart is very much like the one used on Yahoo, the data used for my analysis is not Stock data. So, I will not be able to call the Yahoo Url by feeding any query params.

Any suggestions?

答: amCharts Stock chart is of the same breed. It's Flash based but you can easily use it with any server side engine. Not sure whether you are looking for web or windows solution though.</p>

Title: Yahoo Finance API like chart

OwnerDisplayName: Alan Mendelevich

ContentLicense: CC BY-SA 2.5


问:
How can I make a separate .html and .scss files for a component for a mobile version?
Is his possible to make Angular 7 pick up a certain template and style file and bring it to the user?

Sometimes I need completely different layout representations and @media isn't that comfortable especially when you need to restructure the whole page it's a mess with the code.

At the moment there is only one solution as I can see - it's hiding ng-templates (some parts of the code) for different devices.

I've read a lot of questions here but they are all old. I hope in this fast-changing IT world something may have changed recently and there is a good and elegant solution to cope with such tasks.

I tried to solve it in this manner -

```<code>(b) ? './app.component.html' : './test2.html';

</code>```

but it doesn't work, unfortunately

I would appreciate any hints on that.

P.S.: I really like the structure of how NativeScript implemented it recently. It would be nice to have the same ability.

答:
This is an excellent example of a problem that can be solved with Lazy Loading Modules.

A great guide and video tutorial for doing this with routing can be found here:  https://angularfirebase.com/lessons/how-to-lazy-load-components-in-angular-4-in-three-steps/

Your problem is essentially that you don't know if your user is on a Desktop or Mobile at load time, so what you want to do is wait until your code can make that decision and then render the corresponding component.

My Solution:

1) Create two modules, one for all of your desktop components, another for all of your mobile components.

2a) Lazy Load both of these into your main AppModule according to the guide linked above

or

2b) Import all of the components in your AppModule if bundle size is a non-issue

3) Create a parent component who's only job is to determine if the user is Desktop or Mobile

parent.component.ts will have logic to determine if the user is mobile or desktop, and could do this with any number of window calculations or npm packages

parent.component.html will have the two components and an ngIf with the isMobile determining which component to render.

Bonus points

Isolate your logic by creating a single class for matching components and just importing different templates

Body:
Is his possible to make Angular 7 pick up a certain template and style file and bring it to the user?

Sometimes I need completely different layout representations and @media isn't that comfortable especially when you need to restructure the whole page it's a mess with the code.

At the moment there is only one solution as I can see - it's hiding ng-templates (some parts of the code) for different devices.

I've read a lot of questions here but they are all old. I hope in this fast-changing IT world something may have changed recently and there is a good and elegant solution to cope with such tasks.

I tried to solve it in this manner -

(b) ? './app.component.html' : './test2.html';

but it doesn't work, unfortunately

I would appreciate any hints on that.

P.S.: I really like the structure of how NativeScript implemented it recently. It would be nice to have the same ability.


问:
how to configure lombok in eclipse luna
I configure lombok in eclipse Luna with Maven. Annotation is added properly, but no getter and setter are generated.

eclipse.ini

```<code>`-vm E:\Program Files\Java\jdk1.7.0_60\bin`
`-vmargs`
`-Dosgi.requiredJavaVersion=1.7`
`-javaagent:F:\Tools\Java Lib\Lombok\lombok.jar`
`-Xbootclasspath/a:F:\Tools\Java Lib\Lombok\lombok.jar`
`-Xms40m`
`-Xmx512m`
</code>```

答:
Step 1: Create a maven project in Eclipse and add the below dependency in the pom.xml

```<code><dependencies>
  <dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.16.18</version>
</dependency>
</code>```

Step 2: Run As --> Configuraitons --> Goto Arguments --> give arguments like below
maven -clean install

Step 3: Run As --> maven clean

Once you do the maven clean you see Build Success and lombok jar file in the maven Dependencies

Step 4: Goto the jar location as shown in the below screen shot.

Step 5: Give command as shown like below after reaching in the .m2 folder

Step 6: Locate where is your eclipse folder once you this window.Once you see Install Successfull message click on Quit Installer option at the bottom.

Step 7 : We have finished installing the lombok.jar successfully .Now restart your Eclipse IDE and Start below Sample Code to check whether the data is coming or not in the getters and setters.

Step 8: Open Eclipse and create simple Java Maven project and see in the Outline section you can see getters and setters are created you can use either @Data or @Getter
@Setter
On top of class or you can give on top of variable

```<code>@Getter @Setter
privateString riverName;
</code>```

{OR}

```<code>@Getter
@Setter
Class River{
String riverName;
}
</code>```

[OR]

```<code>@Data
class River
{
Private String riverName;

}
</code>```

You can see the project structure and Outline Structure how it got created in simple steps.

Title: how to configure lombok in eclipse luna

Body:
I configure lombok in eclipse Luna with Maven. Annotation is added properly, but no getter and setter are generated.

eclipse.ini

`-vm E:\Program Files\Java\jdk1.7.0_60\bin`
`-vmargs`
`-Dosgi.requiredJavaVersion=1.7`
`-javaagent:F:\Tools\Java Lib\Lombok\lombok.jar`
`-Xbootclasspath/a:F:\Tools\Java Lib\Lombok\lombok.jar`
`-Xms40m`
`-Xmx512m`

Body:
Step 1: Create a maven project in Eclipse and add the below dependency in the pom.xml

<dependencies>
  <dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.16.18</version>
</dependency>

Step 2: Run As --> Configuraitons --> Goto Arguments --> give arguments like below
maven -clean install

Step 3: Run As --> maven clean

Once you do the maven clean you see Build Success and lombok jar file in the maven Dependencies

Step 4: Goto the jar location as shown in the below screen shot.

Step 5: Give command as shown like below after reaching in the .m2 folder

Step 6: Locate where is your eclipse folder once you this window.Once you see Install Successfull message click on Quit Installer option at the bottom.

Step 7 : We have finished installing the lombok.jar successfully .Now restart your Eclipse IDE and Start below Sample Code to check whether the data is coming or not in the getters and setters.

Step 8: Open Eclipse and create simple Java Maven project and see in the Outline section you can see getters and setters are created you can use either @Data or @Getter
@Setter
On top of class or you can give on top of variable

@Getter @Setter
privateString riverName;

{OR}

@Getter
@Setter
Class River{
String riverName;
}

[OR]

@Data
class River
{
Private String riverName;

}

You can see the project structure and Outline Structure how it got created in simple steps.


问:
How to pass tuple in read_sql 'where in' clause in pandas python
I am passing a tuple converted to a string in a read_sql method as

```<code>sql = "select * from table1 where col1 in " + str(tuple1) + " and col2 in " + str(tuple2)

df = pd.read_sql(sql, conn)
</code>```

This is working fine but, when tuple have only one value sql fails with ORA-00936: missing expression, as single element tuple has an extra comma

For example

```<code>tuple1 = (4011,)
tuple2 = (23,24)
</code>```

sql formed is as

```<code>select * from table1 where col1 in (4011,) + " and col2 in (23,24)
                                        ^
ORA-00936: missing expression
</code>```

Is there any better way doing this, other than removal of comma with string operations?

Is there a better way to paramatrize read_sql function?

答:
```
select * from table_name where 1=1 and (column_a, column_b) not in ((28,1),(25,1))
```

Body:
I am passing a tuple converted to a string in a read_sql method as

sql = "select * from table1 where col1 in " + str(tuple1) + " and col2 in " + str(tuple2)

df = pd.read_sql(sql, conn)

This is working fine but, when tuple have only one value sql fails with ORA-00936: missing expression, as single element tuple has an extra comma

For example

tuple1 = (4011,)
tuple2 = (23,24)

sql formed is as

select * from table1 where col1 in (4011,) + " and col2 in (23,24)
                                        ^
ORA-00936: missing expression

Is there any better way doing this, other than removal of comma with string operations?

Is there a better way to paramatrize read_sql function?


问:
Configure Spring JPA with PostgreSQL for a large amount of db requests in time
our application is built on Spring Boot 2 (spring-data, JPA, Hibernate, Postgres, tomcat). Performance of an application is very bad because there is a lot of requests in time (for instance 2000 in 1 second). We are aware we need to rewrite it in future. But my question is if there is some solution which improves performance and executing a lot of requests without big changes in the code? Thank you for any advice.</p>

答:
Its a broad question but some techniques that come in mind:

1) Optimistic locking. Thanks to that you do not need to physically lock tables / rows thus your concurring requests do not get queued and stack up. You still would get OptimisticLockExceptions and will need to  handle them but you get some performance benefits on the flip-side.

2) Try to avoid long methods wrapped in transactions that may lock certain data for more then needed. You may need to think about setting your @Transactionl methods with PROPAGATION=REQUIRES_NEW and making them shorter in general.

3) Try to test around with timeouts on your queries so that they do not hang for too long when blocked etc.


答: if you want to change code, I would suggest replacing hibernate with direct SQL with something like MyBatis. But if no code change, I only can suggest you to find bottle neck first.</p>

Title: Configure Spring JPA with PostgreSQL for a large amount of db requests in time

Body: our application is built on Spring Boot 2 (spring-data, JPA, Hibernate, Postgres, tomcat). Performance of an application is very bad because there is a lot of requests in time (for instance 2000 in 1 second). We are aware we need to rewrite it in future. But my question is if there is some solution which improves performance and executing a lot of requests without big changes in the code? Thank you for any advice.


问:
Invert rows using dplyr
How can I invert the rows of a dataframe/tibble using dplyr? I don't want to arrange it by a certain variable, but rather have it just inverted.

I.e. the tibble

# A tibble: 5 x 2
      a b
  <int> <chr>
1     1 one
2     2 two
3     3 three
4     4 four
5     5 five
```

<p>should become</p>

<pre class="lang-r prettyprint-override"><code># A tibble: 5 x 2
      a b
  <int> <chr>
1     5 five
2     4 four
3     3 three
4     2 two
5     1 one
</code>```

答:
Just arrange() by descending row_number() like this:

my_tibble %>%
  dplyr::arrange(-dplyr::row_number())
```

Title: Invert rows using dplyr

Body:
How can I invert the rows of a dataframe/tibble using dplyr? I don't want to arrange it by a certain variable, but rather have it just inverted.

I.e. the tibble

# A tibble: 5 x 2
      a b
  <int> <chr>
1     1 one
2     2 two
3     3 three
4     4 four
5     5 five

should become

# A tibble: 5 x 2
      a b
  <int> <chr>
1     5 five
2     4 four
3     3 three
4     2 two
5     1 one


问:
ACF Post Object in Timber not showing on page template
Data isn't showing on page template using ACF Post Object and calling it with Timber.

Tried to add the data to index.php and the news.php template.

ACF Post Object Field Name:

```<code>news_author_data
</code>```

news.php

```<code>$post = new TimberPost();
$context['post'] = $post;

$context['news_author'] = new
TimberPost(get_field('news_author_data'));
Timber::render('core/news.twig', $context);
</code>```

news.twig

```<code>{% for news in news_author %}
  test
{% endfor %}
</code>```

No error message.  Just no data.

答:
You're going about it the wrong way, support for ACF is baked into Timber, as per the docs here:

[https://timber.github.io/docs/guides/acf-cookbook/]

Assuming this is a repeater field all you need to do is add this to your news.twig file

```<code><div class="my-list">
    {% for item in post.meta('news_author_data') %}
        <div class="item">
            <h4>{{ item.my_repeater_field }}</h4>
            <h6>{{ item.my_repeater_field }}</h6>
            <img src="{{ Image(item.picture).src }}" />
        </div>
    {% endfor %}
</div>
</code>```

Body:
Data isn't showing on page template using ACF Post Object and calling it with Timber.

Tried to add the data to index.php and the news.php template.

ACF Post Object Field Name:

news_author_data

news.php

$post = new TimberPost();
$context['post'] = $post;

$context['news_author'] = new
TimberPost(get_field('news_author_data'));
Timber::render('core/news.twig', $context);

news.twig

{% for news in news_author %}
  test
{% endfor %}

No error message.  Just no data.

Body:
You're going about it the wrong way, support for ACF is baked into Timber, as per the docs here:

[https://timber.github.io/docs/guides/acf-cookbook/]

Assuming this is a repeater field all you need to do is add this to your news.twig file

<div class="my-list">
    {% for item in post.meta('news_author_data') %}
        <div class="item">
            <h4>{{ item.my_repeater_field }}</h4>
            <h6>{{ item.my_repeater_field }}</h6>
            <img src="{{ Image(item.picture).src }}" />
        </div>
    {% endfor %}
</div>


问:
Get the difference of two array of objects with multiple constraints
I am trying to get the difference of two arrays of objects, by applying multiple AND constraints.

Find here a small example:

const dbArr = [{
    name: 'Company1',
    symbol: 'C1',
    ratingID: '1',
    stockID: '2'
  },
  {
    name: 'Company2',
    symbol: 'C2',
    ratingID: '1',
    stockID: '2'
  },
  {
    name: 'Company3',
    symbol: 'C3',
    ratingID: '1',
    stockID: '2'
  },
  {
    name: 'Company4',
    symbol: 'C4',
    ratingID: '1',
    stockID: '2'
  },
]

const diffArr = [{
    name: 'Company1',
    symbol: 'C1',
    ratingID: '1',
    stockID: '2'
  },
  {
    name: 'Company6',
    symbol: 'C6',
    ratingID: '1',
    stockID: '2'
  },
  {
    name: 'Company1',
    symbol: 'C1',
    ratingID: '5',
    stockID: '3'
  },
  {
    name: 'Company10',
    symbol: 'C10',
    ratingID: '1',
    stockID: '2'
  },
]

const res = diffArr.filter(cv => !dbArr.find(e => e.name === cv.name)).filter(cv => !dbArr.find(e => e.ratingID === cv.ratingID)).filter(cv => !dbArr.find(e => e.stockID === cv.stockID))

console.log(res)

/*
RESULT I would like to get:

const dbArr = [{
  name: 'Company1',
  symbol: 'C1',
  ratingID: '1',
  stockID: '2'
},
{
  name: 'Company2',
  symbol: 'C2',
  ratingID: '1',
  stockID: '2'
},
{
  name: 'Company3',
  symbol: 'C3',
  ratingID: '1',
  stockID: '2'
},
{
  name: 'Company4',
  symbol: 'C4',
  ratingID: '1',
  stockID: '2'
},
{
  name: 'Company6',
  symbol: 'C6',
  ratingID: '1',
  stockID: '2'
},
{
  name: 'Company1',
  symbol: 'C1',
  ratingID: '5',
  stockID: '3'
},
{
  name: 'Company10',
  symbol: 'C10',
  ratingID: '1',
  stockID: '2'
},
] */```

As a final result I tried to concatenate multiple finds, however I get an empty array.

However, my method works if I only use find once.

Any suggestions what I am doing wrong?

答:
I used .reduce with JSON.parse, the idea is that it will check an array of strings and push the nonexistent values in the accumulator

const dbArr = [{
    name: 'Company1',
    symbol: 'C1',
    ratingID: '1',
    stockID: '2'
  },
  {
    name: 'Company2',
    symbol: 'C2',
    ratingID: '1',
    stockID: '2'
  },
  {
    name: 'Company3',
    symbol: 'C3',
    ratingID: '1',
    stockID: '2'
  },
  {
    name: 'Company4',
    symbol: 'C4',
    ratingID: '1',
    stockID: '2'
  },
]

const diffArr = [{
    name: 'Company1',
    symbol: 'C1',
    ratingID: '1',
    stockID: '2'
  },
  {
    name: 'Company6',
    symbol: 'C6',
    ratingID: '1',
    stockID: '2'
  },
  {
    name: 'Company1',
    symbol: 'C1',
    ratingID: '5',
    stockID: '3'
  },
  {
    name: 'Company10',
    symbol: 'C10',
    ratingID: '1',
    stockID: '2'
  },
];

const res = diffArr.reduce((acc, item, index, self) => {

  if (typeof acc !== 'object') {
    acc = [];
  }
  acc.push(JSON.stringify(item)); // push the item as a string

  dbArr.forEach(i => {
    let j = JSON.stringify(i); // make dbArr items strings
    if (acc.indexOf(j) === -1) { // check if the item exists in the accumulator
      acc.push(j); // add it
    }
  })

  if (index === self.length - 1) { // when we reach the last index, we'll convert the strings back to Objects
    acc = acc.map(i => JSON.parse(i));
  }

  return acc;

}, []);

console.log(res)```

Body:
I am trying to get the difference of two arrays of objects, by applying multiple AND constraints.

Find here a small example:

const dbArr = [{
    name: 'Company1',
    symbol: 'C1',
    ratingID: '1',
    stockID: '2'
  },
  {
    name: 'Company2',
    symbol: 'C2',
    ratingID: '1',
    stockID: '2'
  },
  {
    name: 'Company3',
    symbol: 'C3',
    ratingID: '1',
    stockID: '2'
  },
  {
    name: 'Company4',
    symbol: 'C4',
    ratingID: '1',
    stockID: '2'
  },
]

const diffArr = [{
    name: 'Company1',
    symbol: 'C1',
    ratingID: '1',
    stockID: '2'
  },
  {
    name: 'Company6',
    symbol: 'C6',
    ratingID: '1',
    stockID: '2'
  },
  {
    name: 'Company1',
    symbol: 'C1',
    ratingID: '5',
    stockID: '3'
  },
  {
    name: 'Company10',
    symbol: 'C10',
    ratingID: '1',
    stockID: '2'
  },
]

const res = diffArr.filter(cv => !dbArr.find(e => e.name === cv.name)).filter(cv => !dbArr.find(e => e.ratingID === cv.ratingID)).filter(cv => !dbArr.find(e => e.stockID === cv.stockID))

console.log(res)

/*
RESULT I would like to get:

const dbArr = [{
  name: 'Company1',
  symbol: 'C1',
  ratingID: '1',
  stockID: '2'
},
{
  name: 'Company2',
  symbol: 'C2',
  ratingID: '1',
  stockID: '2'
},
{
  name: 'Company3',
  symbol: 'C3',
  ratingID: '1',
  stockID: '2'
},
{
  name: 'Company4',
  symbol: 'C4',
  ratingID: '1',
  stockID: '2'
},
{
  name: 'Company6',
  symbol: 'C6',
  ratingID: '1',
  stockID: '2'
},
{
  name: 'Company1',
  symbol: 'C1',
  ratingID: '5',
  stockID: '3'
},
{
  name: 'Company10',
  symbol: 'C10',
  ratingID: '1',
  stockID: '2'
},
] */

As a final result I tried to concatenate multiple finds, however I get an empty array.

However, my method works if I only use find once.

Any suggestions what I am doing wrong?


答:
We can use desc

```<code>my_tibble %>%
    arrange(desc(row_number()))
</code>```

Or another option is slice

```<code>my_tibble %>%
    slice(rev(row_number()))
</code>```

Or the 'a' column

```<code>my_tibble %>%
   arrange(desc(a))
#  a     b
#1 5  five
#2 4  four
#3 3 three
#4 2   two
#5 1   one
</code>```

Title: Invert rows using dplyr

Body:
We can use desc

my_tibble %>%
    arrange(desc(row_number()))

Or another option is slice

my_tibble %>%
    slice(rev(row_number()))

Or the 'a' column

my_tibble %>%
   arrange(desc(a))
#  a     b
#1 5  five
#2 4  four
#3 3 three
#4 2   two
#5 1   one


问:
How to autoselect adjacent cells with same color when clicked
I've created big "patterns" of multiple rows and columns containing a title in the first row and numbers populated in the remaining rows and columns.
Only the first row is visible and the other rows are grouped.
All different "patterns" are visually separated with different background colors.

Is there a way to select all cells inside a "pattern" with a given color without ungrouping the other rows?

答: this is possible to do so only manually. press and hold CTRL key and do the selection of the rows with mouse clicks on the row's numbers. of course, it needs to be ungrouped.


问:
Codeigniter 3 HMVC has been broken
Using this HMVC plugin in Codeigniter. (https://bitbucket.org/wiredesignz/codeigniter-modular-extensions-hmvc/src/codeigniter-3.x/)

Running fine in another server, but in this server I am getting this error!

```<code>A PHP Error was encountered

Severity: 8192

Message: strpos(): Non-string needles will be interpreted as strings in the future. Use an explicit chr() call to preserve the current behavior

Filename: MX/Router.php

Line Number: 239

Backtrace:

File: /var/www/project.test/public/application/third_party/MX/Router.php
Line: 239
Function: strpos

File: /var/www/project.test/public/application/third_party/MX/Router.php
Line: 101
Function: _set_default_controller

File: /var/www/project.test/public/index.php
Line: 324
Function: require_once
</code>```

答:
This server is running PHP 7, please have a look at this pull request:

https://bitbucket.org/wiredesignz/codeigniter-modular-extensions-hmvc/pull-requests/39/php73-fix-for-error-message-strpos-non/diff

Title: Codeigniter 3 HMVC has been broken

Body:
Using this HMVC plugin in Codeigniter. (https://bitbucket.org/wiredesignz/codeigniter-modular-extensions-hmvc/src/codeigniter-3.x/)

Running fine in another server, but in this server I am getting this error!

A PHP Error was encountered

Severity: 8192

Message: strpos(): Non-string needles will be interpreted as strings in the future. Use an explicit chr() call to preserve the current behavior

Filename: MX/Router.php

Line Number: 239

Backtrace:

File: /var/www/project.test/public/application/third_party/MX/Router.php
Line: 239
Function: strpos

File: /var/www/project.test/public/application/third_party/MX/Router.php
Line: 101
Function: _set_default_controller

File: /var/www/project.test/public/index.php
Line: 324
Function: require_once


问:
PHP Function Parameter is always null in Wordpress
I am not an expert Wordpress PHP developer but I am not understanding this situation.  I am passing a variable through a static function into the $GLOBALS variable that contains an array.  That variable when in the static function is always NULL, but before it goes into it, it is a valid type and prints fine.

functions.php

```<code>$badge_Id = get_comment_meta($comment->comment_ID,"badge_id", true);

   if(strlen($badge_Id) > 0) {
        Cisco_Rewards::add_badge_id($badge_id);
                echo $badge_id; // PRINTS PERFECTLY
   }
</code>```

rewards.php

```<code>class Cisco_Rewards {

static function add_badge_id($badge_id) {
        if(count($GLOBALS['badge_ids']) == 0) {
            $GLOBALS['badge_ids'] = array();
        }
        echo $badge_id; // WONT PRINT, IS NULL
        array_push($GLOBALS['badge_ids'], $badge_Id);
        print_r($GLOBALS['badge_ids']); // ALWAYS HAS NULL VALUES
    }
</code>```

答:
Instead of

```<code>if(count($GLOBALS['badge_ids']) == 0) {
  $GLOBALS['badge_ids'] = array();
}
echo $badge_id;
</code>```

try

```<code>var_dump($badge_id); // to check what it contains at the very beginning of the function
if(!is_array($GLOBALS['badge_ids'])) {
  $GLOBALS['badge_ids'] = array();
}
</code>```

Body:
I am not an expert Wordpress PHP developer but I am not understanding this situation.  I am passing a variable through a static function into the $GLOBALS variable that contains an array.  That variable when in the static function is always NULL, but before it goes into it, it is a valid type and prints fine.

functions.php

$badge_Id = get_comment_meta($comment->comment_ID,"badge_id", true);

   if(strlen($badge_Id) > 0) {
        Cisco_Rewards::add_badge_id($badge_id);
                echo $badge_id; // PRINTS PERFECTLY
   }

rewards.php

class Cisco_Rewards {

static function add_badge_id($badge_id) {
        if(count($GLOBALS['badge_ids']) == 0) {
            $GLOBALS['badge_ids'] = array();
        }
        echo $badge_id; // WONT PRINT, IS NULL
        array_push($GLOBALS['badge_ids'], $badge_Id);
        print_r($GLOBALS['badge_ids']); // ALWAYS HAS NULL VALUES
    }

Body:
Instead of

if(count($GLOBALS['badge_ids']) == 0) {
  $GLOBALS['badge_ids'] = array();
}
echo $badge_id;

try

var_dump($badge_id); // to check what it contains at the very beginning of the function
if(!is_array($GLOBALS['badge_ids'])) {
  $GLOBALS['badge_ids'] = array();
}


问:
Android - Fill different colors between two lines using MPAndroidChart
following this (Android - Fill the color between two lines using MPAndroidChart) answer I was able to fill with color the space between two lines using AndroidMPChart library.

But now I want to customize the filling color to have:

the areas above the boundarySet filled with blue color;

the areas below the boundarySet filled with green color.

Like in the following screenshot (please note that the blue line is a lineSet, so it could be that it is not a limit line):

I would like to customize the line color of the chart, setting it as the filling:

blue color for the line above the boundarySet;

green color for the line below the boundary set.

Is it possible?
I'm not able to find anything similar in the examples using MPAndroidChart.

Thank you!

答: you can try to override the drawLinear in LineChartRender</p>


问:
Readmore.js Implementation
I'm implementing Readmore.js on a website.

Links to Readmore:

http://www.fao.org/fileadmin/scripts/jquery/Readmore.js-master/demo.html

https://github.com/jedfoster/Readmore.js

What I want is to show "Read more..." buttons and collapse text only on mobile devices. Say width less 640px.

So I've applied a condition if width of screen less than 640px just then apply: .readmore();

Code below:

```<code>    (function resize(){
    if (document.body.clientWidth<=640) {
      $('.quote-heading').readmore({
      speed: 75,
      lessLink: '<a href="#">Less</a>',
      moreLink:'<a href="#">Read more...</a>',
      collapsedHeight: 100,
      blockProcessed:function(element,collapsable){
          console.log(element);
      }
        });
    }
    if (document.body.clientWidth>640){
      $('.quote-heading').readmore('destroy');
    }
    })();
</code>```

The problem is if you resize your screen more than 640px "Read more..." buttons still there. Only if your screen more than 640px and your reload your page just then the second condition is met.
Btw I tried to invoke function "onresize" event but error pops up saying that .readmore() is not a function.

答:
Give this code ago...

```<code>$(window).on('resize', function() {
  var $reader = $('.quote-heading').readmore({
    speed: 75,
    lessLink: '<a href="#">Less</a>',
    moreLink: '<a href="#">Read more...</a>',
    collapsedHeight: 100
  });

  if ($(window).width() < 640) {
    $reader.readmore('destroy');
  }
}).trigger('resize');
</code>```

A working example can be found here: https://jsfiddle.net/o6cz8e1h/

Title: Readmore.js Implementation

Body:
I'm implementing Readmore.js on a website.

Links to Readmore:

http://www.fao.org/fileadmin/scripts/jquery/Readmore.js-master/demo.html

https://github.com/jedfoster/Readmore.js

What I want is to show "Read more..." buttons and collapse text only on mobile devices. Say width less 640px.

So I've applied a condition if width of screen less than 640px just then apply: .readmore();

Code below:

    (function resize(){
    if (document.body.clientWidth<=640) {
      $('.quote-heading').readmore({
      speed: 75,
      lessLink: 'Less',
      moreLink:'Read more...',
      collapsedHeight: 100,
      blockProcessed:function(element,collapsable){
          console.log(element);
      }
        });
    }
    if (document.body.clientWidth>640){
      $('.quote-heading').readmore('destroy');
    }
    })();

The problem is if you resize your screen more than 640px "Read more..." buttons still there. Only if your screen more than 640px and your reload your page just then the second condition is met.
Btw I tried to invoke function "onresize" event but error pops up saying that .readmore() is not a function.

Body:
Give this code ago...

$(window).on('resize', function() {
  var $reader = $('.quote-heading').readmore({
    speed: 75,
    lessLink: '<a href="#">Less</a>',
    moreLink: '<a href="#">Read more...</a>',
    collapsedHeight: 100
  });

  if ($(window).width() < 640) {
    $reader.readmore('destroy');
  }
}).trigger('resize');

A working example can be found here: https://jsfiddle.net/o6cz8e1h/


问:
API YouTube API problem with insert to database
I wanted to make a connection to Youtube analytics which writes data to the database can be mysql or mariodb.
Unfortunately, I have a problem with automatic authorization, I am getting an authorization error.

```<code>A service error occurred: { "error": { "code": 401, "message": "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.", "errors": [ { "message": "Login Required.", "domain": "global", "reason": "required", "location": "Authorization", "locationType": "header" } ], "status": "UNAUTHENTICATED" } }
</code>```

What may be the reason for the lack of authorization ?

Skorzystałem z kodu Harvey Connor: YouTube Analytics API php Samples

```<code>set_include_path(get_include_path() . PATH_SEPARATOR . '/home/google-api-php-client/src');

require_once('Google/autoload.php');

require_once 'Google/Client.php';
require_once 'Google/Service/YouTube.php';

session_start();

$client = new Google_Client();
$client->setClientId($OAUTH2_CLIENT_ID);
$client->setClientSecret($OAUTH2_CLIENT_SECRET);
$client->setAccessType("offline");
$client->setScopes(array('https://www.googleapis.com/auth/youtube.force-ssl', 'https://www.googleapis.com/auth/youtubepartner-channel-audit', 'https://www.googleapis.com/auth/youtube', 'https://www.googleapis.com/auth/youtube.readonly', 'https://www.googleapis.com/auth/yt-analytics.readonly', 'https://www.googleapis.com/auth/yt-analytics-monetary.readonly','https://www.googleapis.com/auth/youtubepartner'));
$client->setDeveloperKey($key);

$analytics = new Google_Service_YouTubeAnalytics($client);

$ids = 'channel==' . $channel_url . '';
$end_date = date("Y-m-d");
$start_date = date('Y-m-d', strtotime("-30 days"));
$optparams = array(
'dimensions' => 'day',
);

$metric = 'views';

try{

$api = $analytics->reports->query($ids, $start_date, $end_date, $metric, $optparams);

foreach ($api->rows as $r) {
    $date = $r[0];
    $views = $r[1];

$stmt = $db->prepare("INSERT INTO test (date,views,channel_url) VALUES (:date,:views,:channel_url)");
$stmt->execute([':date' => $date, ':views' => $views, ':channel_url' => $channel_url]);
}
}catch (Google_Service_Exception $e) {
    echo sprintf('<p>A service error occurred: <code>%s</code></p>',
    htmlspecialchars($e->getMessage()));
}
</code>```

My ideas are now running out

答:
Authorization goes here :</p>

```<code>
$client = new Google_Client();
$client->setClientId($OAUTH2_CLIENT_ID);
$client->setClientSecret($OAUTH2_CLIENT_SECRET);
$client->setAccessType("offline");
$client->setScopes(array('https://www.googleapis.com/auth/youtube.force-ssl', 'https://www.googleapis.com/auth/youtubepartner-channel-audit', 'https://www.googleapis.com/auth/youtube', 'https://www.googleapis.com/auth/youtube.readonly', 'https://www.googleapis.com/auth/yt-analytics.readonly', 'https://www.googleapis.com/auth/yt-analytics-monetary.readonly','https://www.googleapis.com/auth/youtubepartner'));
$client->setDeveloperKey($key);

$analytics = new Google_Service_YouTubeAnalytics($client);
</code>```

Body:
I wanted to make a connection to Youtube analytics which writes data to the database can be mysql or mariodb.
Unfortunately, I have a problem with automatic authorization, I am getting an authorization error.

A service error occurred: { "error": { "code": 401, "message": "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.", "errors": [ { "message": "Login Required.", "domain": "global", "reason": "required", "location": "Authorization", "locationType": "header" } ], "status": "UNAUTHENTICATED" } }

What may be the reason for the lack of authorization ?

Skorzystałem z kodu Harvey Connor: YouTube Analytics API php Samples

set_include_path(get_include_path() . PATH_SEPARATOR . '/home/google-api-php-client/src');

require_once('Google/autoload.php');

require_once 'Google/Client.php';
require_once 'Google/Service/YouTube.php';

session_start();

$client = new Google_Client();
$client->setClientId($OAUTH2_CLIENT_ID);
$client->setClientSecret($OAUTH2_CLIENT_SECRET);
$client->setAccessType("offline");
$client->setScopes(array('https://www.googleapis.com/auth/youtube.force-ssl', 'https://www.googleapis.com/auth/youtubepartner-channel-audit', 'https://www.googleapis.com/auth/youtube', 'https://www.googleapis.com/auth/youtube.readonly', 'https://www.googleapis.com/auth/yt-analytics.readonly', 'https://www.googleapis.com/auth/yt-analytics-monetary.readonly','https://www.googleapis.com/auth/youtubepartner'));
$client->setDeveloperKey($key);

$analytics = new Google_Service_YouTubeAnalytics($client);

$ids = 'channel==' . $channel_url . '';
$end_date = date("Y-m-d");
$start_date = date('Y-m-d', strtotime("-30 days"));
$optparams = array(
'dimensions' => 'day',
);

$metric = 'views';

try{

$api = $analytics->reports->query($ids, $start_date, $end_date, $metric, $optparams);

foreach ($api->rows as $r) {
    $date = $r[0];
    $views = $r[1];

$stmt = $db->prepare("INSERT INTO test (date,views,channel_url) VALUES (:date,:views,:channel_url)");
$stmt->execute([':date' => $date, ':views' => $views, ':channel_url' => $channel_url]);
}
}catch (Google_Service_Exception $e) {
    echo sprintf('
A service error occurred: %s
',
    htmlspecialchars($e->getMessage()));
}

My ideas are now running out

Body:
Authorization goes here :

$client = new Google_Client();
$client->setClientId($OAUTH2_CLIENT_ID);
$client->setClientSecret($OAUTH2_CLIENT_SECRET);
$client->setAccessType("offline");
$client->setScopes(array('https://www.googleapis.com/auth/youtube.force-ssl', 'https://www.googleapis.com/auth/youtubepartner-channel-audit', 'https://www.googleapis.com/auth/youtube', 'https://www.googleapis.com/auth/youtube.readonly', 'https://www.googleapis.com/auth/yt-analytics.readonly', 'https://www.googleapis.com/auth/yt-analytics-monetary.readonly','https://www.googleapis.com/auth/youtubepartner'));
$client->setDeveloperKey($key);

$analytics = new Google_Service_YouTubeAnalytics($client);