问:
How to improve performance on nested graphql connections when using pagination
I'm trying to implement some kind of a basic social network project. It has Posts, Comments and Likes like any other.

A post can have many comments

A post can have many likes

A post can have one author

I have a /posts route on the client application. It lists the Posts by paginating and shows their title, image, authorName, commentCount and likesCount.

The graphql query is like this;

```<code>query {
  posts(first: 10, after: "123456") {
    totalCount
    edges {
      node {
        id
        title
        imageUrl
        author {
          id
          username
        }
        comments {
          totalCount
        }
        likes {
          totalCount
        }
      }
    }
  }
}
</code>```

I'm using apollo-server, TypeORM, PostgreSQL and dataloader. I use dataloader to get author of each post. I simply batch the requested authorIds with dataloader, get authors from PostgreSQL with a where user.id in authorIds query, map the query result to the each authorId. You know, the most basic type of usage of dataloader.

But when I try to query the comments or likes connection under each post, I got stuck. I could use the same technique and use postId for them if there was no pagination. But now I have to include filter parameters for the pagination. And there maybe other filter parameters for some where condition as well.

I've found the cacheKeyFn option of dataloader. I simply create a string key for the passed filter object to the dataloader, and it doesn't duplicate them. It just passes the unique ones to the batchFn. But I can't create a sql query with TypeORM to get the results for each first, after, orderBy arguments separately and map the results back to the function which called the dataloader.

I've searched the spectrum.chat source code and I think they don't allow users to query nested connections. Also tried Github GraphQL Explorer and it lets you query nested connections.

Is there any recommended way to achieve this? I understood how to pass an object to dataloader and batch them using cacheKeyFn, but I can't figure out how to get the results from PostgreSQL in one query and map the results to return from the loader.

Thanks!

答:
So, if you restrict things a bit, this is doable. The restriction is to only allowed batched connections on the first page of results, e.g. so all the connections you're fetching in parallel are being done with the parameters. This is a reasonable constraint because it lets you do things like get the first 10 feed items and the first 3 comments for each of them, which represents a fairly typical use case. Trying to support independent pagination within a single query is unlikely to fulfil any real world use cases for a UI, so it's likely an over-optimisation. With this in mind, you can support the "for each parent get the first N children" use case with PostgreSQL using window.

It's a bit fiddly, but there are answers floating around which will get you in the right direction: Grouped LIMIT in PostgreSQL: show the first N rows for each group?

So use dateloader how you are with cacheKeyFn, and let your loader function recognise whether you can perform the optimisation (e.g. after is null and all other arguments are the same). If you can optimise, use a windowing query, otherwise do unoptimised queries in parallel as you would normally.

Body:
I'm trying to implement some kind of a basic social network project. It has Posts, Comments and Likes like any other.

A post can have many comments

A post can have many likes

A post can have one author

I have a /posts route on the client application. It lists the Posts by paginating and shows their title, image, authorName, commentCount and likesCount.

The graphql query is like this;

query {
  posts(first: 10, after: "123456") {
    totalCount
    edges {
      node {
        id
        title
        imageUrl
        author {
          id
          username
        }
        comments {
          totalCount
        }
        likes {
          totalCount
        }
      }
    }
  }
}

I'm using apollo-server, TypeORM, PostgreSQL and dataloader. I use dataloader to get author of each post. I simply batch the requested authorIds with dataloader, get authors from PostgreSQL with a where user.id in authorIds query, map the query result to the each authorId. You know, the most basic type of usage of dataloader.

But when I try to query the comments or likes connection under each post, I got stuck. I could use the same technique and use postId for them if there was no pagination. But now I have to include filter parameters for the pagination. And there maybe other filter parameters for some where condition as well.

I've found the cacheKeyFn option of dataloader. I simply create a string key for the passed filter object to the dataloader, and it doesn't duplicate them. It just passes the unique ones to the batchFn. But I can't create a sql query with TypeORM to get the results for each first, after, orderBy arguments separately and map the results back to the function which called the dataloader.

I've searched the spectrum.chat source code and I think they don't allow users to query nested connections. Also tried Github GraphQL Explorer and it lets you query nested connections.

Is there any recommended way to achieve this? I understood how to pass an object to dataloader and batch them using cacheKeyFn, but I can't figure out how to get the results from PostgreSQL in one query and map the results to return from the loader.

Thanks!


来源: stackexchange

问:
Multiple conditional statements with groupby in pandas
I have a dataset similar to the following.

```<code>date,score
3/1/16,0.6369
5/1/16,-0.2023
6/1/16,0.04
7/1/16,0.0772
9/1/16,-0.4215
12/1/16,0.2960
15/1/16,0.25
15/1/16,0.7684
</code>```

I want to apply the following conditions on the score.

```<code>Con1: if the score is >.05, count that as positive for that date
Con2: if the score is  -0.05<=score <=.05, count that as neutral for that date
Con3: Else, count that as negative for that date
And add a new_column to the DataFrame alongside the score to put the 'negative'/'positive'/'neutral' result
</code>```

Expected Output:

```<code>date, score, mood
3/1/16,0.6369, positive
5/1/16,-.2023, negative
6/1/16,0.04, neutral
</code>```

And I have multiple scores on the same date. So, I thought of using groupby with multiple columns ('date'and 'score')  and pass through the if conditions and add a new column ['mood'] to the DataFrame.

What I have tried:

```<code>df =pd.read_csv('file.csv')
def SortMood(df)
df['mood']=[] #empty column as a list in the df to store the mood
 for score in df['score']:
      if score>(0.05):
            df['mood'].append('positive')
      elif -0.05<=score <=.05:
            df['mood'].append('neutral')
      else:
          df['mood'].append('negative')
</code>```

I am aware that this function is wrong (I get a ValueError). So, any help is appreciated. Thank you.

答:
There are multiple ways to do it. Very similar to your approach would be the apply method of pandas:

```<code>def get_mood(row):
    if row['score'] > 0.05:
        return 'positive'
    elif row['score'] > -0.05:
        return 'neutral'
    else:
        return 'negative'
df['mood'] = df.apply(get_mood, axis=1)
</code>```

Or shorten it down with lambda expression to:

```<code>df['mood'] = df.apply(lambda x: 'positive' if x > 0.05 else ('neutral' if x > -0.05 else 'negative'), axis=1)
</code>```

Or use map:

```<code>df.loc[:,'mood'] = df['score'].map(lambda x: 'positive' if x > 0.05 else ('neutral' if x > -0.05 else 'negative'))
</code>```

I think this should be a lot faster, than apply

ContentLicense: CC BY-SA 4.0

Body:
I have a dataset similar to the following.

date,score
3/1/16,0.6369
5/1/16,-0.2023
6/1/16,0.04
7/1/16,0.0772
9/1/16,-0.4215
12/1/16,0.2960
15/1/16,0.25
15/1/16,0.7684

I want to apply the following conditions on the score.

Con1: if the score is >.05, count that as positive for that date
Con2: if the score is  -0.05<=score <=.05, count that as neutral for that date
Con3: Else, count that as negative for that date
And add a new_column to the DataFrame alongside the score to put the 'negative'/'positive'/'neutral' result

Expected Output:

date, score, mood
3/1/16,0.6369, positive
5/1/16,-.2023, negative
6/1/16,0.04, neutral

And I have multiple scores on the same date. So, I thought of using groupby with multiple columns ('date'and 'score')  and pass through the if conditions and add a new column ['mood'] to the DataFrame.

What I have tried:

df =pd.read_csv('file.csv')
def SortMood(df)
df['mood']=[] #empty column as a list in the df to store the mood
 for score in df['score']:
      if score>(0.05):
            df['mood'].append('positive')
      elif -0.05<=score <=.05:
            df['mood'].append('neutral')
      else:
          df['mood'].append('negative')

I am aware that this function is wrong (I get a ValueError). So, any help is appreciated. Thank you.

Body:
There are multiple ways to do it. Very similar to your approach would be the apply method of pandas:

def get_mood(row):
    if row['score'] > 0.05:
        return 'positive'
    elif row['score'] > -0.05:
        return 'neutral'
    else:
        return 'negative'
df['mood'] = df.apply(get_mood, axis=1)

Or shorten it down with lambda expression to:

df['mood'] = df.apply(lambda x: 'positive' if x > 0.05 else ('neutral' if x > -0.05 else 'negative'), axis=1)

Or use map:

df.loc[:,'mood'] = df['score'].map(lambda x: 'positive' if x > 0.05 else ('neutral' if x > -0.05 else 'negative'))

I think this should be a lot faster, than apply


问:
Show 3 random colors at once every 4 seconds with jQuery
I have this code and I'm trying to show 3 random colors from an array, at once, every 4 seconds, but instead I get 1 color every 4 seconds, even if they are properly randomized...

What am I missing?

```<code>//set colors
var colors = ["white", "red", "blue", "yellow", "orange", "brown", "black", "violet", "purple", "pink", "green"];

//pick 3 of them randomly
var three_random_colors = (n) => {
    return colors.reduce((memo, val, index) => {
        var p = (n-memo.length); // How many remaining to choose.
        var q = colors.length-index; // How many remaining to choose from.
        if (Math.random() < p/q){
            memo.push(val);
        }
        return memo;
    }, []);
};

//output the colors on the HTML
var counter = 0; //start counter
var elem = document.getElementById("changeText");//the place where we change things
setInterval(change, 4000);//every 4 seconds run the following stuff:
function change() {
 var text = three_random_colors(3);//get what's inside "three_random_colors"
 elem.innerHTML = text[counter];//on div, add content <--- (I want 3 at once here! but I get only 1)
    counter++;
    if(counter >= text.length) { counter = 0; var text = three_random_colors(3); }//reset
}
</code>```

答:
Your problem is that your change function only outputs one colour at a time. You can simplify it to just output (for example)

```<code>text.join(' ')
</code>```

and you will see all three colours:

//set colors
var colors = ["white", "red", "blue", "yellow", "orange", "brown", "black", "violet", "purple", "pink", "green"];

//pick 3 of them randomly
var three_random_colors = (n) => {
  return colors.reduce((memo, val, index) => {
    var p = (n - memo.length); // How many remaining to choose.
    var q = colors.length - index; // How many remaining to choose from.
    if (Math.random() < p / q) {
      memo.push(val);
    }
    return memo;
  }, []);
};

//output the colors on the HTML
var elem = document.getElementById("changeText"); //the place where we change things
setInterval(change, 4000); //every 4 seconds run the following stuff:
function change() {
  var text = three_random_colors(3); //get what's inside "three_random_colors"
  elem.innerHTML = text.join(' '); //on div, add content <--- (I want 3 at once here! but I get only 1)
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="changeText"></div></code>```

Body:
I have this code and I'm trying to show 3 random colors from an array, at once, every 4 seconds, but instead I get 1 color every 4 seconds, even if they are properly randomized...

What am I missing?

//set colors
var colors = ["white", "red", "blue", "yellow", "orange", "brown", "black", "violet", "purple", "pink", "green"];

//pick 3 of them randomly
var three_random_colors = (n) => {
    return colors.reduce((memo, val, index) => {
        var p = (n-memo.length); // How many remaining to choose.
        var q = colors.length-index; // How many remaining to choose from.
        if (Math.random() < p/q){
            memo.push(val);
        }
        return memo;
    }, []);
};

//output the colors on the HTML
var counter = 0; //start counter
var elem = document.getElementById("changeText");//the place where we change things
setInterval(change, 4000);//every 4 seconds run the following stuff:
function change() {
 var text = three_random_colors(3);//get what's inside "three_random_colors"
 elem.innerHTML = text[counter];//on div, add content <--- (I want 3 at once here! but I get only 1)
    counter++;
    if(counter >= text.length) { counter = 0; var text = three_random_colors(3); }//reset
}

Body:
Your problem is that your change function only outputs one colour at a time. You can simplify it to just output (for example)

text.join(' ')

and you will see all three colours:

//set colors
var colors = ["white", "red", "blue", "yellow", "orange", "brown", "black", "violet", "purple", "pink", "green"];

//pick 3 of them randomly
var three_random_colors = (n) => {
  return colors.reduce((memo, val, index) => {
    var p = (n - memo.length); // How many remaining to choose.
    var q = colors.length - index; // How many remaining to choose from.
    if (Math.random() < p / q) {
      memo.push(val);
    }
    return memo;
  }, []);
};

//output the colors on the HTML
var elem = document.getElementById("changeText"); //the place where we change things
setInterval(change, 4000); //every 4 seconds run the following stuff:
function change() {
  var text = three_random_colors(3); //get what's inside "three_random_colors"
  elem.innerHTML = text.join(' '); //on div, add content <--- (I want 3 at once here! but I get only 1)
}

<div id="changeText"></div>


问:
How to show truncated form of large pandas dataframe after style.apply?
Normally, a relatively long dataframe like

```<code>df = pd.DataFrame(np.random.randint(0,10,(100,2)))
df
</code>```

will display a truncated form in jupyter notebook like

With head, tail, ellipsis in between and row column count in the end.
However, after style.apply

```<code>def highlight_max(x):
    return ['background-color: yellow' if v == x.max() else '' for v in x]
df.style.apply(highlight_max)
</code>```

we got all rows displayed

Is it possible to still display the truncated form of dataframe after style.apply?

答:
Something simple like this?

```<code>def display_df(dataframe, function):
    display(dataframe.head().style.apply(function))
    display(dataframe.tail().style.apply(function))
    print(f'{dataframe.shape[0]} rows x {dataframe.shape[1]} columns')

display_df(df, highlight_max)
</code>```

Output:

**** EDIT ****

```<code>def display_df(dataframe, function):
    display(pd.concat([dataframe.iloc[:5,:],
                       pd.DataFrame(index=['...'], columns=dataframe.columns),
                       dataframe.iloc[-5:,:]]).style.apply(function))
    print(f'{dataframe.shape[0]} rows x {dataframe.shape[1]} columns')

display_df(df, highlight_max)
</code>```

Output:

The jupyter preview is basically something like this:

```<code>def display_df(dataframe):
    display(pd.concat([dataframe.iloc[:5,:],
                       pd.DataFrame(index=['...'], columns=dataframe.columns, data={0: '...', 1: '...'}),
                       dataframe.iloc[-5:,:]]))
</code>```

but if you try to apply style you are getting an error (TypeError: '>=' not supported between instances of 'int' and 'str') because it's trying to compare and highlight the string values '...'

Body:
Normally, a relatively long dataframe like

df = pd.DataFrame(np.random.randint(0,10,(100,2)))
df

will display a truncated form in jupyter notebook like

With head, tail, ellipsis in between and row column count in the end.
However, after style.apply

def highlight_max(x):
    return ['background-color: yellow' if v == x.max() else '' for v in x]
df.style.apply(highlight_max)

we got all rows displayed

Is it possible to still display the truncated form of dataframe after style.apply?

Body:
Something simple like this?

def display_df(dataframe, function):
    display(dataframe.head().style.apply(function))
    display(dataframe.tail().style.apply(function))
    print(f'{dataframe.shape[0]} rows x {dataframe.shape[1]} columns')

display_df(df, highlight_max)

Output:

**** EDIT ****

def display_df(dataframe, function):
    display(pd.concat([dataframe.iloc[:5,:],
                       pd.DataFrame(index=['...'], columns=dataframe.columns),
                       dataframe.iloc[-5:,:]]).style.apply(function))
    print(f'{dataframe.shape[0]} rows x {dataframe.shape[1]} columns')

display_df(df, highlight_max)

Output:

The jupyter preview is basically something like this:

def display_df(dataframe):
    display(pd.concat([dataframe.iloc[:5,:],
                       pd.DataFrame(index=['...'], columns=dataframe.columns, data={0: '...', 1: '...'}),
                       dataframe.iloc[-5:,:]]))

but if you try to apply style you are getting an error (TypeError: '>=' not supported between instances of 'int' and 'str') because it's trying to compare and highlight the string values '...'


问:
How to limit upload file size in express.js
i got this error says

```<code>error:request entity too large
</code>```

when uploading a video about 30MB,

here is the setting code

```<code>app.use(express.bodyParser({
    uploadDir:'./Temp',
    maxFieldsSize:'2 * 1024 * 1024 * 1024 ',
}));
</code>```

am not sure how to set the maxFieldsSize property, need some help!!!

答:
In 2020 Express uses the body-parser urlencoded function to control the limit.
http://expressjs.com/en/4x/api.html#express.urlencoded

These are the default settings inside node_modules>body-parser>lib>types>urlencoded.js
https://www.npmjs.com/package/body-parser

```<code>  var extended = opts.extended !== false
  var inflate = opts.inflate !== false
  var limit = typeof opts.limit !== 'number'
    ? bytes.parse(opts.limit || '100kb')
    : opts.limit
  var type = opts.type || 'application/x-www-form-urlencoded'
  var verify = opts.verify || false
</code>```

You can see here that the default setting for limit is 100kb.
so in order to up that you can use

```<code>app.use(express.urlencoded({ extended: false, limit: '2gb' }));
</code>```

here are the filetype options available via NPM package bytes ( used by bodyparser )
https://www.npmjs.com/package/bytes

```<code>"b" for bytes
"kb" for kilobytes
"mb" for megabytes
"gb" for gigabytes
"tb" for terabytes
"pb" for petabytes
</code>```

I'm sure this was overkill but I hope this helps the next person.

ContentLicense: CC BY-SA 3.0

Body:
i got this error says

error:request entity too large

when uploading a video about 30MB,

here is the setting code

app.use(express.bodyParser({
    uploadDir:'./Temp',
    maxFieldsSize:'2 * 1024 * 1024 * 1024 ',
}));

am not sure how to set the maxFieldsSize property, need some help!!!

Body:
In 2020 Express uses the body-parser urlencoded function to control the limit.
http://expressjs.com/en/4x/api.html#express.urlencoded

These are the default settings inside node_modules>body-parser>lib>types>urlencoded.js
https://www.npmjs.com/package/body-parser

  var extended = opts.extended !== false
  var inflate = opts.inflate !== false
  var limit = typeof opts.limit !== 'number'
    ? bytes.parse(opts.limit || '100kb')
    : opts.limit
  var type = opts.type || 'application/x-www-form-urlencoded'
  var verify = opts.verify || false

You can see here that the default setting for limit is 100kb.
so in order to up that you can use

app.use(express.urlencoded({ extended: false, limit: '2gb' }));

here are the filetype options available via NPM package bytes ( used by bodyparser )
https://www.npmjs.com/package/bytes

"b" for bytes
"kb" for kilobytes
"mb" for megabytes
"gb" for gigabytes
"tb" for terabytes
"pb" for petabytes

I'm sure this was overkill but I hope this helps the next person.


问:
Changing a Switchery checkbox state from code
How do I programatically change a jQuery Switchery checkbox state from checked to unchecked (and vice versa)?

I tried using global_switch_sound.prop('checked', true) on the checkbox element but it doesn't work.

HTML:

<input id="sound-active-input" type="checkbox"  />
```

<p>JavaScript:</p>

<pre class="lang-js prettyprint-override"><code> global_switch_sound = new Switchery(document.querySelector('#sound-active-input'));
</code>```

答:
```<code>elems.forEach(function(html) {
    let switchery = new Switchery(html, {
        size: 'medium',
        secondaryColor: '#DC3545'
    });
});
</code>```

Body:
How do I programatically change a jQuery Switchery checkbox state from checked to unchecked (and vice versa)?

I tried using global_switch_sound.prop('checked', true) on the checkbox element but it doesn't work.

HTML:

<input id="sound-active-input" type="checkbox"  />

JavaScript:

 global_switch_sound = new Switchery(document.querySelector('#sound-active-input'));


问:
Migrating from using auto increment id to uuid with sequelize
All right,  I'm trying out some different ORM's, currently working on Sequelize. I've defined two models, asset and asset_category, where each asset has a foreign key relation to an asset_category. All good!
Now, I want to change from using auto increment id to uuid, because it's better for security. So I have data in a database and wrote the following (superlong!) migration:

```<code>up: (queryInterface, Sequelize) => {
    return queryInterface
      .addColumn("asset_categories", "uuid", {
        // Add uuid column
        type: Sequelize.UUID,
        defaultValue: Sequelize.UUIDV4,
        allowNull: false,
      })
      .then(_ => {
        return queryInterface.sequelize.query(
          // Fill uuid column
          `
          UPDATE asset_categories SET uuid=uuid()
          `,
        );
      })
      .then(_ => {
        return queryInterface.addColumn("assets", "category_uuid", {
          // Add assets reference uuid column
          type: Sequelize.UUID,
          allowNull: false,
        });
      })
      .then(_ => {
        return queryInterface.sequelize.query(
          // Fill assets reference uuid column
          `
          UPDATE assets
          SET category_uuid= (SELECT ac.uuid FROM asset_categories ac WHERE ac.id = assets.category_id)
        `,
        );
      })
      .then(_ => {
        // Remove assets category_id column
        return queryInterface.removeColumn("assets", "category_id");
      })
      .then(_ => {
        // Remove asset_categories id column
        return queryInterface.removeColumn("asset_categories", "id");
      })
      .then(_ => {
        // Rename asset_categories uuid to id
        return queryInterface.renameColumn("asset_categories", "uuid", "id");
      })
      .then(_ => {
        // Rename assets category_uuid to category_id
        return queryInterface.renameColumn(
          "assets",
          "category_uuid",
          "category_id",
        );
      })
      .then(_ => {
        return queryInterface.changeColumn("asset_categories", "id", {
          // Add primary key to asset_categories id field
          type: Sequelize.UUID,
          defaultValue: Sequelize.UUIDV4,
          allowNull: false,
          primaryKey: true,
        });
      })
      .then(_ => {
        // Add index to asset_categories id field
        return queryInterface.addIndex("asset_categories", ["id"]);
      })
      .then(_ => {
        // Add index to assets category_id field
        return queryInterface.addIndex("assets", ["category_id"]);
      });
</code>```

And:

```<code>  up: (queryInterface, Sequelize) => {
    // Add uuid column
    return queryInterface
      .addColumn("assets", "uuid", {
        type: Sequelize.UUID,
        defaultValue: Sequelize.UUIDV4,
        allowNull: false,
        primaryKey: false,
      })
      .then(_ => {
        // Fill uuid column
        return queryInterface.sequelize.query(
          `
      UPDATE assets SET uuid=uuid()
      `,
        );
      })
      .then(_ => {
        // Remove assets id column
        return queryInterface.removeColumn("assets", "id");
      })
      .then(_ => {
        // Rename assets uuid to id
        return queryInterface.renameColumn("assets", "uuid", "id");
      })
      .then(_ => {
        // Add primary key to uuid column
        return queryInterface.changeColumn("assets", "id", {
          type: Sequelize.UUID,
          defaultValue: Sequelize.UUIDV4,
          allowNull: false,
          primaryKey: true,
        });
      })
      .then(_ => {
        // add foreign key on assets category_id
        return queryInterface.changeColumn("assets", "category_id", {
          type: Sequelize.UUID,
          allowNull: false,
          references: {
            model: {
              tableName: "asset_categories",
            },
            key: "id",
          },
        });
      });

</code>```

Issue though is I get an error in the last step:
ERROR: Referencing column 'category_id' and referenced column 'id' in foreign key constraint 'assets_ibfk_1' are incompatible.

It seems that along all these steps the asset_category.id changed to
id char(36) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL,

Whilst asset.category_id is
category_id char(36) COLLATE utf8mb4_general_ci NOT NULL,

I'm assuming this is the reason I can't add the foreign key back, cause the columns are not exactly the same.

For starters: how does this happen? What causes a column to get a different character set or collate? And also: is there a better way to approach such a migration, cause compared to using Ruby on Rails + Active Record, this seems like utter garbage...

答:
DROP all the FKs involving the ids that you will be removing.  Add FKs for the uuids after finishing the conversion.

Uuids should be CHAR(36) CHARACTER SET ascii COLLATION ascii_general_ci.

If your table is big, you should consider converting to BINARY(16) to save a bunch of disk space.

Any columns that currently point to ids in other table need to become CHAR(36)... also.

The order of actions to take is critical.

Something like:

Backup the entire dataset -- a screwup below may not be recoverable.

DROP FKs.  Do this for all tables before moving on to the next step.

ADD COLUMN uuid for each id-like column; possibly multiple ones in each table.

Populate uuids that will become the PKs with fresh values.

Populate other uuids by doing a multi-table UPDATE based on the existing ids.

Change client code to reference uuids; test it.

For tables where the PK is changing, DROP PRIMARY KEY and ADD PRIMARY KEY(uuid).

DROP COLUMN for the ids and id-like columns.

ADD FKs for the uuids, where appropriate.

If you choose to use the smaller uuid format, that modifies the details of steps 4,5,6.

Ugh.

Body:
All right,  I'm trying out some different ORM's, currently working on Sequelize. I've defined two models, asset and asset_category, where each asset has a foreign key relation to an asset_category. All good!
Now, I want to change from using auto increment id to uuid, because it's better for security. So I have data in a database and wrote the following (superlong!) migration:

up: (queryInterface, Sequelize) => {
    return queryInterface
      .addColumn("asset_categories", "uuid", {
        // Add uuid column
        type: Sequelize.UUID,
        defaultValue: Sequelize.UUIDV4,
        allowNull: false,
      })
      .then(_ => {
        return queryInterface.sequelize.query(
          // Fill uuid column
          `
          UPDATE asset_categories SET uuid=uuid()
          `,
        );
      })
      .then(_ => {
        return queryInterface.addColumn("assets", "category_uuid", {
          // Add assets reference uuid column
          type: Sequelize.UUID,
          allowNull: false,
        });
      })
      .then(_ => {
        return queryInterface.sequelize.query(
          // Fill assets reference uuid column
          `
          UPDATE assets
          SET category_uuid= (SELECT ac.uuid FROM asset_categories ac WHERE ac.id = assets.category_id)
        `,
        );
      })
      .then(_ => {
        // Remove assets category_id column
        return queryInterface.removeColumn("assets", "category_id");
      })
      .then(_ => {
        // Remove asset_categories id column
        return queryInterface.removeColumn("asset_categories", "id");
      })
      .then(_ => {
        // Rename asset_categories uuid to id
        return queryInterface.renameColumn("asset_categories", "uuid", "id");
      })
      .then(_ => {
        // Rename assets category_uuid to category_id
        return queryInterface.renameColumn(
          "assets",
          "category_uuid",
          "category_id",
        );
      })
      .then(_ => {
        return queryInterface.changeColumn("asset_categories", "id", {
          // Add primary key to asset_categories id field
          type: Sequelize.UUID,
          defaultValue: Sequelize.UUIDV4,
          allowNull: false,
          primaryKey: true,
        });
      })
      .then(_ => {
        // Add index to asset_categories id field
        return queryInterface.addIndex("asset_categories", ["id"]);
      })
      .then(_ => {
        // Add index to assets category_id field
        return queryInterface.addIndex("assets", ["category_id"]);
      });

And:

  up: (queryInterface, Sequelize) => {
    // Add uuid column
    return queryInterface
      .addColumn("assets", "uuid", {
        type: Sequelize.UUID,
        defaultValue: Sequelize.UUIDV4,
        allowNull: false,
        primaryKey: false,
      })
      .then(_ => {
        // Fill uuid column
        return queryInterface.sequelize.query(
          `
      UPDATE assets SET uuid=uuid()
      `,
        );
      })
      .then(_ => {
        // Remove assets id column
        return queryInterface.removeColumn("assets", "id");
      })
      .then(_ => {
        // Rename assets uuid to id
        return queryInterface.renameColumn("assets", "uuid", "id");
      })
      .then(_ => {
        // Add primary key to uuid column
        return queryInterface.changeColumn("assets", "id", {
          type: Sequelize.UUID,
          defaultValue: Sequelize.UUIDV4,
          allowNull: false,
          primaryKey: true,
        });
      })
      .then(_ => {
        // add foreign key on assets category_id
        return queryInterface.changeColumn("assets", "category_id", {
          type: Sequelize.UUID,
          allowNull: false,
          references: {
            model: {
              tableName: "asset_categories",
            },
            key: "id",
          },
        });
      });

Issue though is I get an error in the last step:
ERROR: Referencing column 'category_id' and referenced column 'id' in foreign key constraint 'assets_ibfk_1' are incompatible.

It seems that along all these steps the asset_category.id changed to
id char(36) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL,

Whilst asset.category_id is
category_id char(36) COLLATE utf8mb4_general_ci NOT NULL,

I'm assuming this is the reason I can't add the foreign key back, cause the columns are not exactly the same.

For starters: how does this happen? What causes a column to get a different character set or collate? And also: is there a better way to approach such a migration, cause compared to using Ruby on Rails + Active Record, this seems like utter garbage...


问:
What is the equivalent of console.log in pine-script?
Is it possible to console.log variables, or the results of function invocation in pine-script?
I'd like to convert a pine-script script into JavaScript, and I'd like to verify pinescript variables I'm moving into JavaScript are have the same value in the pinescript script v/s the JavaScript version.
Any work arounds are welcome if this functionality does not exist.
Thanks!

答:
NOTES

While this answer's content is not deprecated, the Pine User Manual now contains a page on debugging techniques explaining much of this answer's content, and more.

RicardoSantos has a very nice DebugConsole library which v5 users can access.

There is actually something similar to a console for Pine developers; it's the Data Window. We use it constantly to debug. The idea is to use plotchar() in this way:

```<code>plotchar(bar_index, "Bar Index", "", location = location.top)
</code>```

This will not disrupt the indicator's scale and won't print anything in it, but it will show a value in the Data Window, as is explained in the second question of the PineCoders FAQ's section on debugging. As you move your mouse over chart bars, the corresponding value of the variable/expression will show in the Data Window. The FAQ explains other useful techniques that can be used to debug on the chart, as that is sometimes more efficient.

We use an AutoHotkey macro that creates the required plotchar() statement from a variable or expression previously copied to the clipboard. This is the AHK macro:

```<code>^+C:: SendInput plotchar(^v, "^v", "", location.top){Return}
</code>```

The Data Window is also a great option as a display panel for scripts requiring the display of many values, such as our Backtesting & Trading Engine, which makes extensive use of it:

Body:
NOTES

While this answer's content is not deprecated, the Pine User Manual now contains a page on debugging techniques explaining much of this answer's content, and more.

RicardoSantos has a very nice DebugConsole library which v5 users can access.

There is actually something similar to a console for Pine developers; it's the Data Window. We use it constantly to debug. The idea is to use plotchar() in this way:

plotchar(bar_index, "Bar Index", "", location = location.top)

This will not disrupt the indicator's scale and won't print anything in it, but it will show a value in the Data Window, as is explained in the second question of the PineCoders FAQ's section on debugging. As you move your mouse over chart bars, the corresponding value of the variable/expression will show in the Data Window. The FAQ explains other useful techniques that can be used to debug on the chart, as that is sometimes more efficient.

We use an AutoHotkey macro that creates the required plotchar() statement from a variable or expression previously copied to the clipboard. This is the AHK macro:

^+C:: SendInput plotchar(^v, "^v", "", location.top){Return}

The Data Window is also a great option as a display panel for scripts requiring the display of many values, such as our Backtesting & Trading Engine, which makes extensive use of it:


问:
Adding skipped/ungraded open-ended questions
Is there a way to include open-ended/free-form questions that are ungraded or skipped by r-exams?

Use case: we want to have an exam with mostly multiple choice questions using the package and its grading capability, but also have 5-10 open ended questions that are printed in the same exam. Ideally, r-exams would provide the grade for the first MCQ section, and we could manually add the grade of the open-ended questions.

答:
There is built-in support for up to three open-ended "string" questions that are printed on a separate sheet that has to be marked by hand. The resulting sheet can then be scanned and evaluated along with the main sheet using nops_scan() and nops_eval(). It's on the wish list for the package to extend that number but it hasn't been implemented yet.

Another "trick" you could do is to use the pages= argument of exams2nops() to include a separate PDF sheet with the extra questions. But this would have to be handled completely separately "by hand" afterwards.


问:
Making scribbles on a monochrome image
Imagine there's a picturebox which loads a monochrome image. And there is a need to make few color scribbles on it. I have no background with graphics. Would it be just a pen drawing pixels or something more complex I don't know.

Target language is C#. Technology: WinForms.

答:
I think the easiest way to achieve what you want would be to create a very lightweight retained mode drawing system. Keep track of all the positions where the user has scribbeled and draw dots/circles/lines/rubberducks/whatever at these positions in the PictureBox's Paint event. On mousedown+move events, call the PictureBox' Invalidate() function. The original picture must either be painted underneath or in the class' OnPaintBackground (which IMO is more elegant).

This tutorial should get you started:

https://web.archive.org/web/20121006140255/http://www.bobpowell.net/backtrack.htm

Title: Making scribbles on a monochrome image


问:
Determining GZIPOutputStream behavior
The following code produces files which is deterministic (shasum is the same) for two strings.

```<code>    try(
            FileOutputStream fos = new FileOutputStream(saveLocation);
            GZIPOutputStream zip = new GZIPOutputStream(fos, GZIP_BUFFER_SIZE);
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(zip, StandardCharsets.UTF_8));
            ){
        writer.append(str);
    }
</code>```

Produces:

```<code>a.gz f0200d53f7f9b35647b5dece0146d72cd1c17949
</code>```

However, if I take the file on the command line and re-zip it, it produces a different result

```<code>> gunzip -n a.gz ;gzip -n a ; shasum a.gz

50f478a9ceb292a2d14f1460d7c584b7a856e4d9  a.gz
</code>```

How can I get it to match the original sha using /usr/bin/gzip and gunzip ?

答:
I think that the problem is likely to be the Gzip file header.

The Gzip format has provision for including a file name and file timestamp in the file headers.  (I see you are using the -n when uncompressing and recompressing ... which is probably correct here.)

The Gzip format also includes an "operating system id" in the header.  This is supposed to identify the source file system type; e.g. 0 for FAT, 3 for UNIX, and so on.

Either of these could lead to differences in the Gzip files and hence different hashes.

If I was going to solve this myself, I would start by using cmp to see where the compressed file differences start, and then od to identify what the differences are.  Refer to the Gzip file format spec to figure out what the differences mean:

RFC 1952 - GZIP file format specification version 4.3

Wikipedia's gzip page.

How can I get it to match the original SHA using gzip and gunzip ?

Assuming that the difference is the OS id, I don't think there is a practical way to solve this with the gzip and gunzip commands.

I looked at the source code for GZIPOutputStream in Java 11, and it is not promising.

It is hard-wiring the timestamp to zero.

It is hard-wiring the OS identifier to zero (which is supposed to mean FAT).

The hard-wiring is in a private method and would be next to impossible to "fix" by subclassing or reflection.  You could copy the code and fix it that way, but then you have to maintain your variant GZIPOutputStream class indefinitely.

(I would be looking at changing the application ... or whatever ... so that I didn't need the checksums to be identical.  You haven't said why you are doing this.  It is for testing purposes only, try looking for a different way to implement the tests.)

Title: Determining GZIPOutputStream behavior

Body:
The following code produces files which is deterministic (shasum is the same) for two strings.

    try(
            FileOutputStream fos = new FileOutputStream(saveLocation);
            GZIPOutputStream zip = new GZIPOutputStream(fos, GZIP_BUFFER_SIZE);
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(zip, StandardCharsets.UTF_8));
            ){
        writer.append(str);
    }

Produces:

a.gz f0200d53f7f9b35647b5dece0146d72cd1c17949

However, if I take the file on the command line and re-zip it, it produces a different result

> gunzip -n a.gz ;gzip -n a ; shasum a.gz

50f478a9ceb292a2d14f1460d7c584b7a856e4d9  a.gz

How can I get it to match the original sha using /usr/bin/gzip and gunzip ?


问:
How do I assign values based on multiple conditions for existing columns?
I would like to create a new column with a numerical value based on the following conditions:

a. if gender is male & pet1==pet2, points = 5

b. if gender is female & (pet1 is 'cat' or pet1 is 'dog'), points = 5

c. all other combinations, points = 0

    gender    pet1      pet2
0   male      dog       dog
1   male      cat       cat
2   male      dog       cat
3   female    cat       squirrel
4   female    dog       dog
5   female    squirrel  cat
6   squirrel  dog       cat
```
<p>I would like the end result to be as follows:</p>
<pre class="lang-none prettyprint-override"><code>    gender    pet1      pet2      points
0   male      dog       dog       5
1   male      cat       cat       5
2   male      dog       cat       0
3   female    cat       squirrel  5
4   female    dog       dog       5
5   female    squirrel  cat       0
6   squirrel  dog       cat       0
</code>```

How do I accomplish this?

答:
numpy.select

This is a perfect case for np.select where we can create a column based on multiple conditions and it's a readable method when there are more conditions:

```<code>conditions = [
    df['gender'].eq('male') & df['pet1'].eq(df['pet2']),
    df['gender'].eq('female') & df['pet1'].isin(['cat', 'dog'])
]

choices = [5,5]

df['points'] = np.select(conditions, choices, default=0)

print(df)
     gender      pet1      pet2  points
0      male       dog       dog       5
1      male       cat       cat       5
2      male       dog       cat       0
3    female       cat  squirrel       5
4    female       dog       dog       5
5    female  squirrel       cat       0
6  squirrel       dog       cat       0
</code>```

Body:
I would like to create a new column with a numerical value based on the following conditions:

a. if gender is male & pet1==pet2, points = 5

b. if gender is female & (pet1 is 'cat' or pet1 is 'dog'), points = 5

c. all other combinations, points = 0

    gender    pet1      pet2
0   male      dog       dog
1   male      cat       cat
2   male      dog       cat
3   female    cat       squirrel
4   female    dog       dog
5   female    squirrel  cat
6   squirrel  dog       cat

I would like the end result to be as follows:

    gender    pet1      pet2      points
0   male      dog       dog       5
1   male      cat       cat       5
2   male      dog       cat       0
3   female    cat       squirrel  5
4   female    dog       dog       5
5   female    squirrel  cat       0
6   squirrel  dog       cat       0

How do I accomplish this?

Body:
numpy.select

This is a perfect case for np.select where we can create a column based on multiple conditions and it's a readable method when there are more conditions:

conditions = [
    df['gender'].eq('male') & df['pet1'].eq(df['pet2']),
    df['gender'].eq('female') & df['pet1'].isin(['cat', 'dog'])
]

choices = [5,5]

df['points'] = np.select(conditions, choices, default=0)

print(df)
     gender      pet1      pet2  points
0      male       dog       dog       5
1      male       cat       cat       5
2      male       dog       cat       0
3    female       cat  squirrel       5
4    female       dog       dog       5
5    female  squirrel       cat       0
6  squirrel       dog       cat       0


问:
Abstract classes and Polymorphism - how are additional methods and properties usually handled?
Imagine a rental company that has cars for the company to use internally and trucks to rent. The cars use gas and the trucks use diesel. The trucks have additional things that they do that cars do not - they are rented. So I have the following code:

```<code>abstract class Vehicle
{
    public abstract FuelType Fuel();
}

class Car : Vehicle
{
    public override FuelType Fuel()
    {
        return FuelType.Gas;
    }
}

class Truck : Vehicle
{
    public override FuelType Fuel()
    {
        return FuelType.Diesel;
    }

    //Not in base class or Car class
    public List<Rental> Rentals()
    {
        return new List<Rental>();
    }
}

class Rental
{
      //...some stuff here
}

enum FuelType
{
    Gas,
    Diesel
}
</code>```

What is normally done when the child classes have additional methods and properties? Example:

```<code>        List<Vehicle> vehicles = new List<Vehicle>() { };

        vehicles.Add(new Car());
        vehicles.Add(new Truck());

        foreach (var vehicle in vehicles)
        {
            Console.WriteLine(vehicle.Fuel().ToString());

            //Pseudocode here:
            if(vehicle.GetType() is Truck)
            {
                //Provide rental information
                Truck truck = (Truck)vehicle;
                truck.ProvideSomeInfo();
            }
        }
</code>```

I get how polymorphism works when you have classes that have all the same methods, properties, fields, etc. What is normally done when you need to work with the base class AND you need to work with additional methods, fields, properties that all the children do not share?

All the abstract tutorials that I have found just show the simpler case when all the children have the same sets of methods, properties, fields.

答:
The good practice is to use interfaces.

```<code>class Truck : IVehicle, IRentable, ITrackable    //you can also inherit from abstract VehicleBase class
</code>```

Then:

```<code>foreach (var vehicle in vehicles)
    {
        Console.WriteLine(vehicle.Fuel().ToString());

        if(vehicle.GetType() is IRentable)
        {
            //Provide renting status
            Console.WriteLine((vehicle as IRentable)?.IsRented); //note I didn't cast for Truck directly
        }

        if(vehicle.GetType() is ITrackable)
        {
            //Provide position
            Console.WriteLine((vehicle as ITrackable)?.Position);
        }
    }
</code>```

Edit:

Another good practice if you create one big vehicle class with a lot of functionality:

Size

MainType with an enum { Truck, PassengerCar }

WheelBase (8, 4, etc)

CanHaveMoreThan1Engine

FuelType with an enum { Electric, Kerosene }

List<KeyValuePair<string, string> Engines (e.g. <"CommonRail4", "Diesel">)

CanProvideTrackingInfo

GetTrackingInfo()

Body:
Imagine a rental company that has cars for the company to use internally and trucks to rent. The cars use gas and the trucks use diesel. The trucks have additional things that they do that cars do not - they are rented. So I have the following code:

abstract class Vehicle
{
    public abstract FuelType Fuel();
}

class Car : Vehicle
{
    public override FuelType Fuel()
    {
        return FuelType.Gas;
    }
}

class Truck : Vehicle
{
    public override FuelType Fuel()
    {
        return FuelType.Diesel;
    }

    //Not in base class or Car class
    public List<Rental> Rentals()
    {
        return new List<Rental>();
    }
}

class Rental
{
      //...some stuff here
}

enum FuelType
{
    Gas,
    Diesel
}

What is normally done when the child classes have additional methods and properties? Example:

        List<Vehicle> vehicles = new List<Vehicle>() { };

        vehicles.Add(new Car());
        vehicles.Add(new Truck());

        foreach (var vehicle in vehicles)
        {
            Console.WriteLine(vehicle.Fuel().ToString());

            //Pseudocode here:
            if(vehicle.GetType() is Truck)
            {
                //Provide rental information
                Truck truck = (Truck)vehicle;
                truck.ProvideSomeInfo();
            }
        }

I get how polymorphism works when you have classes that have all the same methods, properties, fields, etc. What is normally done when you need to work with the base class AND you need to work with additional methods, fields, properties that all the children do not share?

All the abstract tutorials that I have found just show the simpler case when all the children have the same sets of methods, properties, fields.

Body:
The good practice is to use interfaces.

class Truck : IVehicle, IRentable, ITrackable    //you can also inherit from abstract VehicleBase class

Then:

foreach (var vehicle in vehicles)
    {
        Console.WriteLine(vehicle.Fuel().ToString());

        if(vehicle.GetType() is IRentable)
        {
            //Provide renting status
            Console.WriteLine((vehicle as IRentable)?.IsRented); //note I didn't cast for Truck directly
        }

        if(vehicle.GetType() is ITrackable)
        {
            //Provide position
            Console.WriteLine((vehicle as ITrackable)?.Position);
        }
    }

Edit:

Another good practice if you create one big vehicle class with a lot of functionality:

Size

MainType with an enum { Truck, PassengerCar }

WheelBase (8, 4, etc)

CanHaveMoreThan1Engine

FuelType with an enum { Electric, Kerosene }

List<KeyValuePair<string, string> Engines (e.g. <"CommonRail4", "Diesel">)

CanProvideTrackingInfo

GetTrackingInfo()


问:
Styling SideCommand in codename one gives different results on IOS and Android
I have a Side Menu style via CSS, on Android, desired result is achieved, but the same style breaks on IOS. Looks like I need to access the button inside the SideCommand to achieve this, however, I am stuck on this one. bellow is the CSS and the codename one code.

SideCommand{
        background-color: #018de5;
        padding: 2mm;
        color: white;
        font-size: 3mm;
        border-width: 0mm;
        margin: 0.2mm 0mm 0mm 0mm;
    }```
</div>
</div>
</p>

```mainToolbar.addComponentToSideMenu(avatarBox);
    mainToolbar.addMaterialCommandToSideMenu("Home", FontImage.MATERIAL_HOME, e -> {
        try {
            Home();
        } catch (JSONException ex) {
            System.err.println("there is error");
        }
    });
    mainToolbar.addMaterialCommandToSideMenu("Credit", FontImage.MATERIAL_CREDIT_CARD, e -> {
        credithome.Home(this);
    });

    mainToolbar.addMaterialCommandToSideMenu("Clients", FontImage.MATERIAL_PEOPLE, e -> {
        clienthome.Home(this);
    });

    mainToolbar.addMaterialCommandToSideMenu("Accounting", FontImage.MATERIAL_BOOK, e -> {

        accountinghome.Home(this);
    });
```

The result on IOS is

And android is fine

答:
You need to override the border property too with an empty border as the default theme on iOS contains a border for the side command. It's something we'd like to fix in the future but for now it's there.

E.g.

SideCommand{
  background-color: #018de5;
  padding: 2mm;
  color: white;
  font-size: 3mm;
  border: none;
  margin: 0.2mm 0mm 0mm 0mm;
}
```

Body:
I have a Side Menu style via CSS, on Android, desired result is achieved, but the same style breaks on IOS. Looks like I need to access the button inside the SideCommand to achieve this, however, I am stuck on this one. bellow is the CSS and the codename one code.

SideCommand{
        background-color: #018de5;
        padding: 2mm;
        color: white;
        font-size: 3mm;
        border-width: 0mm;
        margin: 0.2mm 0mm 0mm 0mm;
    }

mainToolbar.addComponentToSideMenu(avatarBox);
    mainToolbar.addMaterialCommandToSideMenu("Home", FontImage.MATERIAL_HOME, e -> {
        try {
            Home();
        } catch (JSONException ex) {
            System.err.println("there is error");
        }
    });
    mainToolbar.addMaterialCommandToSideMenu("Credit", FontImage.MATERIAL_CREDIT_CARD, e -> {
        credithome.Home(this);
    });

    mainToolbar.addMaterialCommandToSideMenu("Clients", FontImage.MATERIAL_PEOPLE, e -> {
        clienthome.Home(this);
    });

    mainToolbar.addMaterialCommandToSideMenu("Accounting", FontImage.MATERIAL_BOOK, e -> {

        accountinghome.Home(this);
    });

The result on IOS is

And android is fine


问:
Fastest way to find an element in database
I am not sure if this is an appropriate question for this site. But I didn't find any place to ask such question .

Once in an interview I was asked that, there are more than 2 million products in a database for an apparel store, those products has no tag , no category or anything else, just product name . How can I search an product in that database in most efficient way ?

I answered Linear Search . But the interviewer wasn't satisfied.

答:
hashtables
just create the hash function which would convert a name of an item in a database to a number and then just find the element by its index</p>

```<code>function hash(name){
    /*convert a name into a number eg by converting each letter into a corresponding ascii number and multiplying it by a random number(to avoid collisions however there are many more efficient ways to avoid collisions and reducing memory requirements*/
    return name //which will be hashed
}

database[hash(name)]
</code>```

Body:
hashtables
just create the hash function which would convert a name of an item in a database to a number and then just find the element by its index

function hash(name){
    /*convert a name into a number eg by converting each letter into a corresponding ascii number and multiplying it by a random number(to avoid collisions however there are many more efficient ways to avoid collisions and reducing memory requirements*/
    return name //which will be hashed
}

database[hash(name)]


问:
How to match different groups in regex
I have the following string:

```<code>"Josua de Grave* (1643-1712)"
</code>```

Everything before the * is the person's name, the first date 1634 is his birth date, 1712 is the date of his death.

Following this logic I'd like to have 3 match groups for each one of the item. I tried

```<code>([a-zA-Z|\s]*)\* (\d{3,4})-(\d{3,4})
</code>```

```<code>"Josua de Grave* (1643-1712)".match(/([a-zA-Z|\s]*)\* (\d{3,4})-(\d{3,4})/)
</code>```

but that returns nil.

Why is my logic wrong, and what should I do to get the 3 intended match groups.

答:
While you can use a pattern, the problem of splitting this into its parts can also be easily done using other Ruby methods:

Using split:

```<code>s = "Josua de Grave* (1643-1712)"
name, dates = s.split('*') # => ["Josua de Grave", " (1643-1712)"]
birth, death = dates[2..-2].split('-') # => ["1643", "1712"]
</code>```

Or, using scan:

```<code>*name, birth, death = s.scan(/[[:alnum:]]+/) # => ["Josua", "de", "Grave", "1643", "1712"]
name.join(' ')  # => "Josua de Grave"
birth # => "1643"
death # => "1712"
</code>```

If I was using a pattern, I'd use this:

```<code>name, birth, death = /^([^*]+).+?(\d+)-(\d+)/.match(s)[1..3] # => ["Josua de Grave", "1643", "1712"]
name # => "Josua de Grave"
birth # => "1643"
death # => "1712"
</code>```

/(^[^*]+).+?(\d+)-(\d+)/ means:

^ start at the beginning of the buffer

([^*]+) capture everything not *, where it'll stop capturing

.+? skip the minimum until...

(\d+) the year is matched and captured

- match but don't capture

(\d+) the year is matched and captured

Regexper helps explain it as does Rubular.

Title: How to match different groups in regex

Body:
I have the following string:

"Josua de Grave* (1643-1712)"

Everything before the * is the person's name, the first date 1634 is his birth date, 1712 is the date of his death.

Following this logic I'd like to have 3 match groups for each one of the item. I tried

([a-zA-Z|\s]*)\* (\d{3,4})-(\d{3,4})

"Josua de Grave* (1643-1712)".match(/([a-zA-Z|\s]*)\* (\d{3,4})-(\d{3,4})/)

but that returns nil.

Why is my logic wrong, and what should I do to get the 3 intended match groups.

Body:
While you can use a pattern, the problem of splitting this into its parts can also be easily done using other Ruby methods:

Using split:

s = "Josua de Grave* (1643-1712)"
name, dates = s.split('*') # => ["Josua de Grave", " (1643-1712)"]
birth, death = dates[2..-2].split('-') # => ["1643", "1712"]

Or, using scan:

*name, birth, death = s.scan(/[[:alnum:]]+/) # => ["Josua", "de", "Grave", "1643", "1712"]
name.join(' ')  # => "Josua de Grave"
birth # => "1643"
death # => "1712"

If I was using a pattern, I'd use this:

name, birth, death = /^([^*]+).+?(\d+)-(\d+)/.match(s)[1..3] # => ["Josua de Grave", "1643", "1712"]
name # => "Josua de Grave"
birth # => "1643"
death # => "1712"

/(^[^*]+).+?(\d+)-(\d+)/ means:

^ start at the beginning of the buffer

([^*]+) capture everything not *, where it'll stop capturing

.+? skip the minimum until...

(\d+) the year is matched and captured

- match but don't capture

(\d+) the year is matched and captured

Regexper helps explain it as does Rubular.


问:
Advice on streaming application for Android via WebRTC
I have to build an application for android to stream video and audio to a desktop application through a server. Latency is important. I also have to make sure that android streaming can be controlled from pc (user should be able to switch the camera or turn off the microphone).

I thought to use the WebRTC protocol for communication but it seems I'm gonna have to write signalling server myself to support that requirement mentioned above.

Is there a better way to implement this whole thing? Also, I can't find any good docs or libraries for android streaming (no retrofit analogies obviously).

P.S. I'm thinking about using Javafx via Tornadofx for a desktop application.

答: You certainly don't need to create your own signaling server.  I would suggest using something like Kurento Streaming Server or a derivation of Kurento like OpenVidu.  It's open source and free and has lot's of great and active support via google groups.  Depending on how much specific customization you may need one or the other might be better for you.  OpenVidu allows for less customization since most of the stuff under the hood is already done for you, whereas Kurento allows you to modify and customize almost everything under the hood and on the front end using examples that can be changed at the code level.  I have used it extensive on projects on the past and would think it meets most, if not all of your requirements.  Scaling can be a bit challenging, but is still mush easier than just P2P webRTC since everything is relayed through a central server and most certainly doable depending on your requirements and implementation.  Additionally you can record, process and transcode video server side.</p>


问:
passing data into a function
Okay So I know this is super basic and I should know how to do this but I'm blanking and having trouble finding the answer in Google. I have an include that has an array of variables for example

```<code> $phrases["text"][1] = "How much wood would a woodchuck chuck if a woodchuck could chuck wood?";
 $phrases["mp3"][1] = "http://example.com/file.mp3";
</code>```

Then a function that gets the varibles:

```<code>function return_phrase($phrase_name="", $fallback="",$default ="text"){
    $next= (isset($default) && $default =="mp3") ? 'text' : 'mp3';
    if(isset($tts_phrases[$default][$phrase_name])){
        return $phrases[$default][$phrase_name]);
    }
    else if(isset($tts_phrases[$next][$phrase_name])){
        return $phrases[$next][$phrase_name]);
    }

    else{
        return $fallback;
    }
}
</code>```

The problem is that the $phrases arrays aren't being sent to the function I can include the file in the function itself but I know that's the wrong way to do it. I think I need to use $global just not sure how.

答:
Method 1: Pass $phrases, $tts_phrases as parameters

```<code>function return_phrase(array $phrases, array $ttphrases, $phrase_name="", $fallback="",$default ="text"){
    $next= (isset($default) && $default =="mp3") ? 'text' : 'mp3';
    if(isset($tts_phrases[$default][$phrase_name])){
        return $phrases[$default][$phrase_name]);
    }
    else if(isset($tts_phrases[$next][$phrase_name])){
        return $phrases[$next][$phrase_name]);
    }

    else{
        return $fallback;
    }
}
</code>```

Method 2: Make $phrases, $tts_phrases global (bad!)

```<code>function return_phrase($phrase_name="", $fallback="",$default ="text"){
    global $phrases, $tts_phrases;
    $next= (isset($default) && $default =="mp3") ? 'text' : 'mp3';
    if(isset($tts_phrases[$default][$phrase_name])){
        return $phrases[$default][$phrase_name]);
    }
    else if(isset($tts_phrases[$next][$phrase_name])){
        return $phrases[$next][$phrase_name]);
    }

    else{
        return $fallback;
    }
}
</code>```

Using global variables is a quick and easy fix, but once your application gets larger they become very hard to keep track of. For example, take this legacy code snippet that I have to deal with at work:

```<code>function foo() {
     global $mysqldsn, $ldapdsn, $autologout_timer, $isMobileDevice, logout_fail_limit, $logout_fail_window, $lang, $project_contact_email, $project_contact_name ... (50 or 60 more global variables following)
     ...
 }
</code>```

Any time I am looking at one of the pages that just pulls one of those variables out of thin air, I have to Ctrl+F the whole project and make sure that every little change hasn't messed up the whole app. When you keep your variables in local scope, you know exactly what you are changing.

Title: passing data into a function

Body:
Okay So I know this is super basic and I should know how to do this but I'm blanking and having trouble finding the answer in Google. I have an include that has an array of variables for example

 $phrases["text"][1] = "How much wood would a woodchuck chuck if a woodchuck could chuck wood?";
 $phrases["mp3"][1] = "http://example.com/file.mp3";

Then a function that gets the varibles:

function return_phrase($phrase_name="", $fallback="",$default ="text"){
    $next= (isset($default) && $default =="mp3") ? 'text' : 'mp3';
    if(isset($tts_phrases[$default][$phrase_name])){
        return $phrases[$default][$phrase_name]);
    }
    else if(isset($tts_phrases[$next][$phrase_name])){
        return $phrases[$next][$phrase_name]);
    }

    else{
        return $fallback;
    }
}

The problem is that the $phrases arrays aren't being sent to the function I can include the file in the function itself but I know that's the wrong way to do it. I think I need to use $global just not sure how.

Body:
Method 1: Pass $phrases, $tts_phrases as parameters

function return_phrase(array $phrases, array $ttphrases, $phrase_name="", $fallback="",$default ="text"){
    $next= (isset($default) && $default =="mp3") ? 'text' : 'mp3';
    if(isset($tts_phrases[$default][$phrase_name])){
        return $phrases[$default][$phrase_name]);
    }
    else if(isset($tts_phrases[$next][$phrase_name])){
        return $phrases[$next][$phrase_name]);
    }

    else{
        return $fallback;
    }
}

Method 2: Make $phrases, $tts_phrases global (bad!)

function return_phrase($phrase_name="", $fallback="",$default ="text"){
    global $phrases, $tts_phrases;
    $next= (isset($default) && $default =="mp3") ? 'text' : 'mp3';
    if(isset($tts_phrases[$default][$phrase_name])){
        return $phrases[$default][$phrase_name]);
    }
    else if(isset($tts_phrases[$next][$phrase_name])){
        return $phrases[$next][$phrase_name]);
    }

    else{
        return $fallback;
    }
}

Using global variables is a quick and easy fix, but once your application gets larger they become very hard to keep track of. For example, take this legacy code snippet that I have to deal with at work:

function foo() {
     global $mysqldsn, $ldapdsn, $autologout_timer, $isMobileDevice, logout_fail_limit, $logout_fail_window, $lang, $project_contact_email, $project_contact_name ... (50 or 60 more global variables following)
     ...
 }

Any time I am looking at one of the pages that just pulls one of those variables out of thin air, I have to Ctrl+F the whole project and make sure that every little change hasn't messed up the whole app. When you keep your variables in local scope, you know exactly what you are changing.


问:
how do you specifiy how many items are shown (height) in a listbox
I have this and it shows all of the items in the listbox but there are alot of them

```<code>    <label for=”Application”>Application:</label>
    <%= Html.ListBox("SelectedCategories", Model.Applications)%>
</code>```

is there a way to show just show 5 items and add a scrollbar (compared to increasing the height of the listbox)

答:
In case you use MVC5.2 +, try this:

@Html.ListBoxFor(model => model.selected_categories,Model.categories,new { size = 5})

ContentLicense: CC BY-SA 2.5

Body:
I have this and it shows all of the items in the listbox but there are alot of them

    Application:
    <%= Html.ListBox("SelectedCategories", Model.Applications)%>

is there a way to show just show 5 items and add a scrollbar (compared to increasing the height of the listbox)


问:
Encrypt string in Python
I need to encrypt a small string in Python. Is it possible to use a secret key to encrypt the string? Is there a good way to do this and achieve a reasonable encryption level using only Python libraries? Could you show me how to do this?

My knowledge about cryptography is quite basic.

答:
Here's my code:

```<code>from cryptography.fernet import Fernet
import pyperclip

print("For this program to work, please send the file named 'pwkey' and the encrypted code to the other user.")
key = Fernet.generate_key()
file = open('pwkey', 'wb')
file.write(key)
file.close()
print('File Generated')
original = input('Enter message>>>')
message = original.encode()
f = Fernet(key)
encrypted = f.encrypt(message)
encrypted = encrypted.decode("ascii")
print('Encrypted:', encrypted)
pyperclip.copy(encrypted)
print('Please tell the other user to input the encrypted code in the Decrypt program')
print('(Code copied to Clipboard)')
print("Note: Please delete the 'pwkey' file after sending it to the other user. It
    is for one-time use only.")
</code>```

And decrypting

```<code># Decrypt
from cryptography.fernet import Fernet

print("For this program to work, make sure you have the file named 'pwkey' in your Python folder and the encrypted "
        "code.")
file = open('pwkey', 'rb')
key = file.read()
file.close()
print('Key Retrieved')
encrypted = input('Please input your encrypted code>>>')
encrypted = bytes(encrypted, 'utf-8')
f = Fernet(key)
decrypted = f.decrypt(encrypted)
decrypted = decrypted.decode()
print('Decrypted Message:')
print(decrypted)
print("Note: Please delete the 'pwkey' file after getting the decrypted message. It is for one-time use only.")
</code>```

Title: Encrypt string in Python

Body:
Here's my code:

from cryptography.fernet import Fernet
import pyperclip

print("For this program to work, please send the file named 'pwkey' and the encrypted code to the other user.")
key = Fernet.generate_key()
file = open('pwkey', 'wb')
file.write(key)
file.close()
print('File Generated')
original = input('Enter message>>>')
message = original.encode()
f = Fernet(key)
encrypted = f.encrypt(message)
encrypted = encrypted.decode("ascii")
print('Encrypted:', encrypted)
pyperclip.copy(encrypted)
print('Please tell the other user to input the encrypted code in the Decrypt program')
print('(Code copied to Clipboard)')
print("Note: Please delete the 'pwkey' file after sending it to the other user. It
    is for one-time use only.")

And decrypting

# Decrypt
from cryptography.fernet import Fernet

print("For this program to work, make sure you have the file named 'pwkey' in your Python folder and the encrypted "
        "code.")
file = open('pwkey', 'rb')
key = file.read()
file.close()
print('Key Retrieved')
encrypted = input('Please input your encrypted code>>>')
encrypted = bytes(encrypted, 'utf-8')
f = Fernet(key)
decrypted = f.decrypt(encrypted)
decrypted = decrypted.decode()
print('Decrypted Message:')
print(decrypted)
print("Note: Please delete the 'pwkey' file after getting the decrypted message. It is for one-time use only.")


问:
How to interpret Tortoise Git Revision Graph?
I have a very small development effort as shown in the attached revision graph.  At the top (end) of the graph are three branches (master FrontDist, and DRV8871), but they are all in the same block.

I have used the 'browse references' utility to compare 'master' with each of the other branches, and TG tells me there were no differences found.  I know in the past I have merged development branches back into 'master', but I've never subsequently looked at the revision graph.  Is this depiction trying to tell me that both 'FrontDist' and 'DRV8871' have already been merged back into 'master' but I currently have the 'FrontDist' branch checked out?

TIA,

Frank

答:
Those three branches are referencing the same commit.

If there was any merge, it was from the "fast-forward" variety: the merged branch simply moved its HEAD, since there is no commit with two parent (actual merge)

You can see in TortoiseGit Colour Settings 2 that:

green means "local branch"

red means "current branch"


问:
Create a chart using worksheet data in an array variable
Code to create a chart using data in worksheet.

Basically create a scatter line graph with X axis values in array "TimeArr" and Y axis values in array "TempArr".

Run time error is thrown while assigning values.

```<code>Sub Chart1()
Dim LupCol, LupRow, LastCol, LastRow As Integer
LupCol = 2
LupRow = 2
LastCol = lCol
rcount = 92
LastRow = rcount - 1

Worksheets("Process_Data").Activate
Dim TimeArr(), TempArr() As Variant
Dim SXvalues, SYvalues As Series
TimeArr = Range(Cells(LupRow, LupCol), Cells(LastRow, LupCol))
TempArr = Range(Cells(LupRow, LupCol + 1), Cells(LastRow, LupCol + 1))

Dim ChartSheet1 As Chart
Set ChartSheet1 = Charts.Add
ActiveChart.ChartArea.Clear

With ChartSheet1
    .ChartType = xlXYScatterLinesNoMarkers
    .HasTitle = True
    .ChartTitle.Text = "Air Side Temperatures"
    .Axes(xlCategory, xlPrimary).HasTitle = True
    .Axes(xlCategory, xlPrimary).AxisTitle.Characters.Text = "Time"
    .Axes(xlValue, xlPrimary).HasTitle = True
    .Axes(xlValue, xlPrimary).AxisTitle.Characters.Text = "Temperature in degC"
    .Axes(xlValue, xlPrimary).MinimumScale = 0
    .FullSeriesCollection(1).XValues = TimeArr 'RUN TIME ERROR of invalid parameter
    .FullSeriesCollection(1).Values = TempArr
End With

End Sub
</code>```

答:
I've modified your code a bit, and it runs just fine, and I've added a few friendly notes to help with your programming:

```<code>Sub Chart1()
  Dim LupCol As Long, LupRow As Long, LastRow As Long
  ' note: use Long not Integer, long story, but it's better with no drawbacks
  ' also, need to dim each variable as a type, or they'll be variants
  Dim rCount As Long
  LupCol = 2
  LupRow = 2
  rCount = 92
  LastRow = rCount - 1

  Dim TimeArr As Variant, TempArr As Variant
  With Worksheets("Process_Data")
    ' don't need to activate the sheet, just reference it
    ' also, use .Value to populate the arrays
    TimeArr = .Range(.Cells(LupRow, LupCol), .Cells(LastRow, LupCol)).Value
    TempArr = .Range(.Cells(LupRow, LupCol + 1), .Cells(LastRow, LupCol + 1)).Value
  End With

  Dim ChartSheet1 As Chart
  Set ChartSheet1 = Charts.Add
  ActiveChart.ChartArea.Clear

  With ChartSheet1
    .ChartType = xlXYScatterLinesNoMarkers
    With .SeriesCollection.NewSeries
      ' need to add series before you populate it
      .XValues = TimeArr
      .Values = TempArr
    End With
    .HasTitle = True
    .ChartTitle.Text = "Air Side Temperatures"
    .Axes(xlCategory, xlPrimary).HasTitle = True
    .Axes(xlCategory, xlPrimary).AxisTitle.Characters.Text = "Time"
    .Axes(xlValue, xlPrimary).HasTitle = True
    .Axes(xlValue, xlPrimary).AxisTitle.Characters.Text = "Temperature in degC"
    .Axes(xlValue, xlPrimary).MinimumScale = 0
  End With
End Sub
</code>```

Any reason you want to use hard-coded arrays rather than worksheet ranges as chart data?

To use the ranges:

```<code>Sub Chart2()
  Dim LupCol As Long, LupRow As Long, LastRow As Long
  Dim rCount As Long
  LupCol = 2
  LupRow = 2
  rCount = 92
  LastRow = rCount - 1

  Dim TimeArr As Range, TempArr As Range
  With Worksheets("Process_Data")
    Set TimeArr = .Range(.Cells(LupRow, LupCol), .Cells(LastRow, LupCol))
    Set TempArr = .Range(.Cells(LupRow, LupCol + 1), .Cells(LastRow, LupCol + 1))
  End With

  Dim ChartSheet1 As Chart
  Set ChartSheet1 = Charts.Add
  ActiveChart.ChartArea.Clear

  With ChartSheet1
    .ChartType = xlXYScatterLinesNoMarkers
    With .SeriesCollection.NewSeries
      .XValues = TimeArr  'RUN TIME ERROR of invalid parameter
      .Values = TempArr
    End With
    .HasTitle = True
    .ChartTitle.Text = "Air Side Temperatures"
    .Axes(xlCategory, xlPrimary).HasTitle = True
    .Axes(xlCategory, xlPrimary).AxisTitle.Characters.Text = "Time"
    .Axes(xlValue, xlPrimary).HasTitle = True
    .Axes(xlValue, xlPrimary).AxisTitle.Characters.Text = "Temperature in degC"
    .Axes(xlValue, xlPrimary).MinimumScale = 0
  End With
End Sub
</code>```

Body:
Code to create a chart using data in worksheet.

Basically create a scatter line graph with X axis values in array "TimeArr" and Y axis values in array "TempArr".

Run time error is thrown while assigning values.

Sub Chart1()
Dim LupCol, LupRow, LastCol, LastRow As Integer
LupCol = 2
LupRow = 2
LastCol = lCol
rcount = 92
LastRow = rcount - 1

Worksheets("Process_Data").Activate
Dim TimeArr(), TempArr() As Variant
Dim SXvalues, SYvalues As Series
TimeArr = Range(Cells(LupRow, LupCol), Cells(LastRow, LupCol))
TempArr = Range(Cells(LupRow, LupCol + 1), Cells(LastRow, LupCol + 1))

Dim ChartSheet1 As Chart
Set ChartSheet1 = Charts.Add
ActiveChart.ChartArea.Clear

With ChartSheet1
    .ChartType = xlXYScatterLinesNoMarkers
    .HasTitle = True
    .ChartTitle.Text = "Air Side Temperatures"
    .Axes(xlCategory, xlPrimary).HasTitle = True
    .Axes(xlCategory, xlPrimary).AxisTitle.Characters.Text = "Time"
    .Axes(xlValue, xlPrimary).HasTitle = True
    .Axes(xlValue, xlPrimary).AxisTitle.Characters.Text = "Temperature in degC"
    .Axes(xlValue, xlPrimary).MinimumScale = 0
    .FullSeriesCollection(1).XValues = TimeArr 'RUN TIME ERROR of invalid parameter
    .FullSeriesCollection(1).Values = TempArr
End With

End Sub

Body:
I've modified your code a bit, and it runs just fine, and I've added a few friendly notes to help with your programming:

Sub Chart1()
  Dim LupCol As Long, LupRow As Long, LastRow As Long
  ' note: use Long not Integer, long story, but it's better with no drawbacks
  ' also, need to dim each variable as a type, or they'll be variants
  Dim rCount As Long
  LupCol = 2
  LupRow = 2
  rCount = 92
  LastRow = rCount - 1

  Dim TimeArr As Variant, TempArr As Variant
  With Worksheets("Process_Data")
    ' don't need to activate the sheet, just reference it
    ' also, use .Value to populate the arrays
    TimeArr = .Range(.Cells(LupRow, LupCol), .Cells(LastRow, LupCol)).Value
    TempArr = .Range(.Cells(LupRow, LupCol + 1), .Cells(LastRow, LupCol + 1)).Value
  End With

  Dim ChartSheet1 As Chart
  Set ChartSheet1 = Charts.Add
  ActiveChart.ChartArea.Clear

  With ChartSheet1
    .ChartType = xlXYScatterLinesNoMarkers
    With .SeriesCollection.NewSeries
      ' need to add series before you populate it
      .XValues = TimeArr
      .Values = TempArr
    End With
    .HasTitle = True
    .ChartTitle.Text = "Air Side Temperatures"
    .Axes(xlCategory, xlPrimary).HasTitle = True
    .Axes(xlCategory, xlPrimary).AxisTitle.Characters.Text = "Time"
    .Axes(xlValue, xlPrimary).HasTitle = True
    .Axes(xlValue, xlPrimary).AxisTitle.Characters.Text = "Temperature in degC"
    .Axes(xlValue, xlPrimary).MinimumScale = 0
  End With
End Sub

Any reason you want to use hard-coded arrays rather than worksheet ranges as chart data?

To use the ranges:

Sub Chart2()
  Dim LupCol As Long, LupRow As Long, LastRow As Long
  Dim rCount As Long
  LupCol = 2
  LupRow = 2
  rCount = 92
  LastRow = rCount - 1

  Dim TimeArr As Range, TempArr As Range
  With Worksheets("Process_Data")
    Set TimeArr = .Range(.Cells(LupRow, LupCol), .Cells(LastRow, LupCol))
    Set TempArr = .Range(.Cells(LupRow, LupCol + 1), .Cells(LastRow, LupCol + 1))
  End With

  Dim ChartSheet1 As Chart
  Set ChartSheet1 = Charts.Add
  ActiveChart.ChartArea.Clear

  With ChartSheet1
    .ChartType = xlXYScatterLinesNoMarkers
    With .SeriesCollection.NewSeries
      .XValues = TimeArr  'RUN TIME ERROR of invalid parameter
      .Values = TempArr
    End With
    .HasTitle = True
    .ChartTitle.Text = "Air Side Temperatures"
    .Axes(xlCategory, xlPrimary).HasTitle = True
    .Axes(xlCategory, xlPrimary).AxisTitle.Characters.Text = "Time"
    .Axes(xlValue, xlPrimary).HasTitle = True
    .Axes(xlValue, xlPrimary).AxisTitle.Characters.Text = "Temperature in degC"
    .Axes(xlValue, xlPrimary).MinimumScale = 0
  End With
End Sub


问:
Creating a new dataframe based on a condition between two columns of original dataframe
I have a dataframe with 3 columns as below :

```<code>X Y Z
1 4 2
2 3 3
3 1 4
</code>```

I want to create a data frame where the third column is substituted with values of the first column if it matches with the second column. As I have shown with an example output below :

```<code>X Y Z=(X+1)
1 4 NA
2 3 2
3 1 NA
</code>```

The code I have tried is as follows :

```<code>library(dplyr)
chk4 %>% chk5
chk4 %>% if(X == Z)
mutate(# Z value to Y where X = Y)
</code>```

答:
If you want to substitute values in column Z with values from X if Y values equals Z or with NA if not then do:

```<code>df$Z = ifelse( df$Z == df$Y, df$X, NA)
</code>```

where df is your data frame.

Example:

```<code>df = data.frame(X = c(1,2,3), Y = c(4,3,1), Z = c(2,3,4))
df$Z = ifelse( df$Z == df$Y, df$X, NA)

df
  X Y  Z
1 1 4 NA
2 2 3  2
3 3 1 NA
</code>```

Body:
I have a dataframe with 3 columns as below :

X Y Z
1 4 2
2 3 3
3 1 4

I want to create a data frame where the third column is substituted with values of the first column if it matches with the second column. As I have shown with an example output below :

X Y Z=(X+1)
1 4 NA
2 3 2
3 1 NA

The code I have tried is as follows :

library(dplyr)
chk4 %>% chk5
chk4 %>% if(X == Z)
mutate(# Z value to Y where X = Y)

Body:
If you want to substitute values in column Z with values from X if Y values equals Z or with NA if not then do:

df$Z = ifelse( df$Z == df$Y, df$X, NA)

where df is your data frame.

Example:

df = data.frame(X = c(1,2,3), Y = c(4,3,1), Z = c(2,3,4))
df$Z = ifelse( df$Z == df$Y, df$X, NA)

df
  X Y  Z
1 1 4 NA
2 2 3  2
3 3 1 NA


问:
GtkTreeView alternate row color
I can't set the alternate row color of a TreeView, I don't know why doesn't works.

This the code

```<code>MainWindow::MainWindow(BaseObjectType* cobject, const Glib::RefPtr<Gtk::Builder>& refGlade) :
    Gtk::ApplicationWindow(cobject), refBuilder(refGlade){

    Glib::RefPtr<Gtk::CssProvider> cssProvider = Gtk::CssProvider::create();
    cssProvider->load_from_path("style.css");
    Glib::RefPtr<Gtk::StyleContext> styleContext = Gtk::StyleContext::create();
    Glib::RefPtr<Gdk::Screen> screen = Gdk::Screen::get_default();
    styleContext->add_provider_for_screen(screen, cssProvider, GTK_STYLE_PROVIDER_PRIORITY_APPLICATION);

    const char* user = "user";
    const char* passwd = "passwd";
    const char* database = "dbname";
    const char* dbhost = "192.168.1.5";

    connection = mysql_init(NULL);

    mysql_real_connect(connection, dbhost, user, passwd, database, 3307, NULL, 0);

    refBuilder->get_widget("m_TreeView1", m_TreeView1);

    m_refTreeModel = Gtk::ListStore::create(m_Columns);
    m_TreeView1->set_model(m_refTreeModel);

    /*Glib::RefPtr<Gtk::StyleContext> context = m_TreeView1->get_style_context();
context->add_class("treeview");
*/

    Affitto* affitti = new Affitto(connection);
    MYSQL_RES* res = affitti->getAll();
    MYSQL_ROW riga;
    Gtk::TreeModel::Row row;

    while ((riga = mysql_fetch_row(res)))
    {

        row = *(m_refTreeModel->append());
        row[m_Columns.m_col_inqid] = std::stoi(riga[0]);
        row[m_Columns.m_col_cognomenome] = riga[1];
        row[m_Columns.m_col_stabile] = riga[2];
        row[m_Columns.m_col_mese] = std::stoi(riga[3]);
        row[m_Columns.m_col_anno] = std::stoi(riga[4]);
        row[m_Columns.m_col_posteggiopagato] = std::stod(riga[5]);
        row[m_Columns.m_col_affittopagato] = std::stod(riga[6]);
        row[m_Columns.m_col_riscaldamentopagato] = std::stod(riga[7]);
        row[m_Columns.m_col_pagatoil] = riga[8];
        row[m_Columns.m_col_stato] = riga[9];
        row[m_Columns.m_col_osservazioni] = riga[10];
        row[m_Columns.m_col_traslocato] = riga[11];
        row[m_Columns.m_col_diversi] = std::stod(riga[12]);
        row[m_Columns.m_col_affitto] = std::stod(riga[13]);
        row[m_Columns.m_col_posteggio] = std::stod(riga[14]);
        row[m_Columns.m_col_riscaldamento] = std::stod(riga[15]);

    }

    m_TreeView1->append_column("InqID", m_Columns.m_col_inqid);
    m_TreeView1->append_column("Cognome e nome", m_Columns.m_col_cognomenome);
    //m_TreeView1->get_column(1)->set_expand(true);
    m_TreeView1->append_column("Stabile", m_Columns.m_col_stabile);
    m_TreeView1->append_column("Mese", m_Columns.m_col_mese);
    m_TreeView1->append_column("Anno", m_Columns.m_col_anno);
    m_TreeView1->append_column("Posteggio pagato", m_Columns.m_col_posteggiopagato);
    m_TreeView1->append_column("Affitto pagato", m_Columns.m_col_affittopagato);
    m_TreeView1->append_column("Riscaldamento pagato", m_Columns.m_col_riscaldamentopagato);
    m_TreeView1->append_column("Pagato il", m_Columns.m_col_pagatoil);
    m_TreeView1->append_column("Stato", m_Columns.m_col_stato);
    m_TreeView1->append_column("Osservazioni", m_Columns.m_col_osservazioni);
    m_TreeView1->append_column("Traslocato", m_Columns.m_col_traslocato);
    m_TreeView1->append_column("Diversi", m_Columns.m_col_diversi);
    m_TreeView1->append_column("Affitto", m_Columns.m_col_affitto);
    m_TreeView1->append_column("Posteggio", m_Columns.m_col_posteggio);
    m_TreeView1->append_column("Riscaldamento", m_Columns.m_col_riscaldamento);

    mysql_free_result(res);
    mysql_close(connection);

}
</code>```

And this the css, that is correctly loaded. I set the style class of the TreeView (treeview) in glade file.

```<code>.treeview row:nth-child(even)
{
    background-color: #ff0000;
}
.treeview row:nth-child(odd)
{
    background-color: #000000;
}
</code>```

What's wrong? I tried too to set the style class by code (commented rows) but does't change.
Thanks in advance for an help!

update

I put my updated code, what's I'm wrong?

```<code>Gtk::CellRendererText* textRenderer = manage(new Gtk::CellRendererText());
    textRenderer->property_editable() = false;
    Gtk::TreeViewColumn *col = manage(new Gtk::TreeViewColumn("InqId", *textRenderer));
    col->add_attribute(*textRenderer, "cell-background-rgba", m_Columns.m_col_inqid);
    m_TreeView1->append_column(*col);
while ((riga = mysql_fetch_row(res)))
    {

        row = *(m_refTreeModel->append());
        row[m_Columns.m_col_inqid] = std::stoi(riga[0]);

        row[m_Columns.m_col_inqid] = Gdk::Color("#CCCCCC");

    }
</code>```

thanks in advance!

答:
Somebody else had already the same problem:

Probably you could do your a function where you grab each cell of a row and use
the already mentioned function or do it on cell creation as here:

Row Background Color GtkTreeView Widget

Watch out, he just used the wrong function for the color:

Thanks @ivo s, I was using the wrong property, I needed
  "cell-background-gdk" and not "background-gdk". Thanks for the help.

Use cell-background-rgba function instead of before mentioned cell-background-gdk cause it is deprecated and will be removed sooner or later.

Title: GtkTreeView alternate row color

Body:
I can't set the alternate row color of a TreeView, I don't know why doesn't works.

This the code

MainWindow::MainWindow(BaseObjectType* cobject, const Glib::RefPtr<Gtk::Builder>& refGlade) :
    Gtk::ApplicationWindow(cobject), refBuilder(refGlade){

    Glib::RefPtr<Gtk::CssProvider> cssProvider = Gtk::CssProvider::create();
    cssProvider->load_from_path("style.css");
    Glib::RefPtr<Gtk::StyleContext> styleContext = Gtk::StyleContext::create();
    Glib::RefPtr<Gdk::Screen> screen = Gdk::Screen::get_default();
    styleContext->add_provider_for_screen(screen, cssProvider, GTK_STYLE_PROVIDER_PRIORITY_APPLICATION);

    const char* user = "user";
    const char* passwd = "passwd";
    const char* database = "dbname";
    const char* dbhost = "192.168.1.5";

    connection = mysql_init(NULL);

    mysql_real_connect(connection, dbhost, user, passwd, database, 3307, NULL, 0);

    refBuilder->get_widget("m_TreeView1", m_TreeView1);

    m_refTreeModel = Gtk::ListStore::create(m_Columns);
    m_TreeView1->set_model(m_refTreeModel);

    /*Glib::RefPtr<Gtk::StyleContext> context = m_TreeView1->get_style_context();
context->add_class("treeview");
*/

    Affitto* affitti = new Affitto(connection);
    MYSQL_RES* res = affitti->getAll();
    MYSQL_ROW riga;
    Gtk::TreeModel::Row row;

    while ((riga = mysql_fetch_row(res)))
    {

        row = *(m_refTreeModel->append());
        row[m_Columns.m_col_inqid] = std::stoi(riga[0]);
        row[m_Columns.m_col_cognomenome] = riga[1];
        row[m_Columns.m_col_stabile] = riga[2];
        row[m_Columns.m_col_mese] = std::stoi(riga[3]);
        row[m_Columns.m_col_anno] = std::stoi(riga[4]);
        row[m_Columns.m_col_posteggiopagato] = std::stod(riga[5]);
        row[m_Columns.m_col_affittopagato] = std::stod(riga[6]);
        row[m_Columns.m_col_riscaldamentopagato] = std::stod(riga[7]);
        row[m_Columns.m_col_pagatoil] = riga[8];
        row[m_Columns.m_col_stato] = riga[9];
        row[m_Columns.m_col_osservazioni] = riga[10];
        row[m_Columns.m_col_traslocato] = riga[11];
        row[m_Columns.m_col_diversi] = std::stod(riga[12]);
        row[m_Columns.m_col_affitto] = std::stod(riga[13]);
        row[m_Columns.m_col_posteggio] = std::stod(riga[14]);
        row[m_Columns.m_col_riscaldamento] = std::stod(riga[15]);

    }

    m_TreeView1->append_column("InqID", m_Columns.m_col_inqid);
    m_TreeView1->append_column("Cognome e nome", m_Columns.m_col_cognomenome);
    //m_TreeView1->get_column(1)->set_expand(true);
    m_TreeView1->append_column("Stabile", m_Columns.m_col_stabile);
    m_TreeView1->append_column("Mese", m_Columns.m_col_mese);
    m_TreeView1->append_column("Anno", m_Columns.m_col_anno);
    m_TreeView1->append_column("Posteggio pagato", m_Columns.m_col_posteggiopagato);
    m_TreeView1->append_column("Affitto pagato", m_Columns.m_col_affittopagato);
    m_TreeView1->append_column("Riscaldamento pagato", m_Columns.m_col_riscaldamentopagato);
    m_TreeView1->append_column("Pagato il", m_Columns.m_col_pagatoil);
    m_TreeView1->append_column("Stato", m_Columns.m_col_stato);
    m_TreeView1->append_column("Osservazioni", m_Columns.m_col_osservazioni);
    m_TreeView1->append_column("Traslocato", m_Columns.m_col_traslocato);
    m_TreeView1->append_column("Diversi", m_Columns.m_col_diversi);
    m_TreeView1->append_column("Affitto", m_Columns.m_col_affitto);
    m_TreeView1->append_column("Posteggio", m_Columns.m_col_posteggio);
    m_TreeView1->append_column("Riscaldamento", m_Columns.m_col_riscaldamento);

    mysql_free_result(res);
    mysql_close(connection);

}

And this the css, that is correctly loaded. I set the style class of the TreeView (treeview) in glade file.

.treeview row:nth-child(even)
{
    background-color: #ff0000;
}
.treeview row:nth-child(odd)
{
    background-color: #000000;
}

What's wrong? I tried too to set the style class by code (commented rows) but does't change.
Thanks in advance for an help!

update

I put my updated code, what's I'm wrong?

Gtk::CellRendererText* textRenderer = manage(new Gtk::CellRendererText());
    textRenderer->property_editable() = false;
    Gtk::TreeViewColumn *col = manage(new Gtk::TreeViewColumn("InqId", *textRenderer));
    col->add_attribute(*textRenderer, "cell-background-rgba", m_Columns.m_col_inqid);
    m_TreeView1->append_column(*col);
while ((riga = mysql_fetch_row(res)))
    {

        row = *(m_refTreeModel->append());
        row[m_Columns.m_col_inqid] = std::stoi(riga[0]);

        row[m_Columns.m_col_inqid] = Gdk::Color("#CCCCCC");

    }

thanks in advance!


问:
how to design this below UI interface in codename1
/home/benjaminz/Pictures/Screenshot from 2020-02-15 10-01-31.png</p>

答:
That's a really trivial UI.

It can be implemented in multiple ways. E.g. the top line can be tabs with tabs on TOP mode. This will implicitly swap all the lower content for you.

You can place the tabs in the center, add four tabs and the content for each one. In that case you will need a new banner for each page (indicating the sale). Below that you just have a scrollable grid layout that's trivial.

Alternatively the top can be a row of buttons either with grid layout or BoxLayout.X_AXIS.

The page in that case would be a box layout on the Y axis.

The present is a FloatingActionButton style component.

The content would be a grid either way.

Each element would be a lead component. With a parent container in a layered layout containing two children One is a border layout containing the image layout in the center and a box y in the south containing both labels. The second one is a top/right aligned flow layout with the discount label.


问:
String manipulation in jQuery
I have a div which collapses clicking on a text header. I want to change the header from "+ filters" to "- filters" accordingly (when the div is collapsed or expanded)

How can I perform this with jQuery?

```<code>if (headerDiv.text() starts with "+")
    replace "+" with "-"
else
    replace "-" with "+"
</code>```

答:
I would do:

```<code>var plus_string = "<span class=/"plus/">+</span>";
var minus_string = "<span class=/"minus/">-</span>";

if($("div.header").hasClass("plus")){
    $("div.header").removeClass("plus");
    $("div.header").addClass("minus");
    $("div.header").append(plus_string);
    $("span.plus").remove();
 } else (... the reverse of the above...)
</code>```

This because i would use the class plus and minus to handle a bit of css to change the appearance of the header div. As you're probably already doing that, you can play a bit with it like this :)

OwnerDisplayName: Juan Manuel

Title: String manipulation in jQuery

Body:
I have a div which collapses clicking on a text header. I want to change the header from "+ filters" to "- filters" accordingly (when the div is collapsed or expanded)

How can I perform this with jQuery?

if (headerDiv.text() starts with "+")
    replace "+" with "-"
else
    replace "-" with "+"

Body:
I would do:

var plus_string = "<span class=/"plus/">+</span>";
var minus_string = "<span class=/"minus/">-</span>";

if($("div.header").hasClass("plus")){
    $("div.header").removeClass("plus");
    $("div.header").addClass("minus");
    $("div.header").append(plus_string);
    $("span.plus").remove();
 } else (... the reverse of the above...)

This because i would use the class plus and minus to handle a bit of css to change the appearance of the header div. As you're probably already doing that, you can play a bit with it like this :)

OwnerDisplayName: fmsf

LastEditorDisplayName: fmsf


问:
SessionStorage and json objects
```<code>user: {firstName: "loki", lastName: "ch"}
</code>```

I am storing this user in session storage.

```<code>$window.sessionStorage.user = user;
</code>```

when i retrieved it back using
 $window.sessionStorage.user, i got:

```<code>[object Object]
</code>```

I want in JSON.
Any suggestions?

答:
Set the item

```<code>sessionStorage.setItem('user', user)
</code>```

Get the item

```<code>var item = sessionStorage.getItem('user')
var user = item ? JSON.stringify(item) : {}
</code>```

Title: SessionStorage and json objects

Body:
user: {firstName: "loki", lastName: "ch"}

I am storing this user in session storage.

$window.sessionStorage.user = user;

when i retrieved it back using
 $window.sessionStorage.user, i got:

[object Object]

I want in JSON.
Any suggestions?

Body:
Set the item

sessionStorage.setItem('user', user)

Get the item

var item = sessionStorage.getItem('user')
var user = item ? JSON.stringify(item) : {}


问:
"Add to Cart" functionality instead of "Select Options" button behavior for variable products
Woocommerce has two button types in the product loop

"add to cart" for adding simple products to cart

"select options" if a simple product becomes a variable one or a subscription option is added.

My setting:

All Woocommerce products are configured as simple products and subscription products at the same time using the following plugins

"Woocommerce Subscription"

"All Products for Woocommerce Subscription". Default is set to simple product.

Now the buttons on all products change from "add to cart" to “select options”. That is Woocommerce default behavior.

My Question:

How can I keep the "add to cart" button and its functionality of adding the simple product to cart despite having a variable product?

Logic behind it: Users are given the opportunity to make a choice on checkout and therefore add to cart functionality instead of redirect to single product page for making a choice is desired.

答:
```<code>function filter_woocommerce_loop_add_to_cart_link( $link, $product ) {

    if ( is_shop() && $product->product_type === 'simple' ) {
        $product_id = $product->get_id();
        $product_sku = $product->get_sku();

          $link = '<a rel="nofollow" href="?add-to-cart=' . $product_id . '" data-quantity="1" data-product_id="' . $product_id . '" data-product_sku="' . $product_sku . '" class="button product_type_simple add_to_cart_button ajax_add_to_cart add-to-cart" aria-label="Add to cart"><em>Add to cart</em></a>';

    }

    return $link;
}
add_filter( 'woocommerce_loop_add_to_cart_link', 'filter_woocommerce_loop_add_to_cart_link', 10, 2 );
</code>```


问:
How can I move an object around the screen by dragging in Android?
So in my layout I have this ball which I want to drag around the screen. I tried using the onTouch() method, and these are my results:

1)((Button)findViewById(R.id.ball)).setY(event.getY());

((Button)findViewById(R.id.ball)).setX(event.getX());

This one is very glitchy for some reason. I try to move the ball and it just quickly goes back and forth between two different places.

2) ((Button)findViewById(R.id.ball)).setY(event.getRawY());

((Button)findViewById(R.id.ball)).setX(event.getRawX());

This one works a bit smoother, but when  I start the movement the ball just teleports to some other place. It works fine except for that part where it "teleports"

What I want to achieve:

A normal drag movement of the ball where the ball is right beneath the finger (x and y coordinates of the ball match the x and y coordinates of the touch)

I can add screen recordings explaining the two cases above if needed

答:
First make your activity implement View.OnTouchListener and import the requested method:

```<code>public class MyActivity extends AppCompatActivity implements View.OnTouchListener {}
</code>```

Then change newly created onTouch method like below:

```<code>float dX, dY;

@Override
public boolean onTouch(View view, MotionEvent event) {

switch (event.getAction()) {

    case MotionEvent.ACTION_DOWN:

        dX = view.getX() - event.getRawX();
        dY = view.getY() - event.getRawY();
        break;

    case MotionEvent.ACTION_MOVE:

        view.animate()
                .x(event.getRawX() + dX)
                .y(event.getRawY() + dY)
                .setDuration(0)
                .start();
        break;
    default:
        return false;
}
return true;
}
</code>```

and finally set this onTouch method to your view:

```<code>ball.setOnTouchListener(this);
</code>```

Body:
First make your activity implement View.OnTouchListener and import the requested method:

public class MyActivity extends AppCompatActivity implements View.OnTouchListener {}

Then change newly created onTouch method like below:

float dX, dY;

@Override
public boolean onTouch(View view, MotionEvent event) {

switch (event.getAction()) {

    case MotionEvent.ACTION_DOWN:

        dX = view.getX() - event.getRawX();
        dY = view.getY() - event.getRawY();
        break;

    case MotionEvent.ACTION_MOVE:

        view.animate()
                .x(event.getRawX() + dX)
                .y(event.getRawY() + dY)
                .setDuration(0)
                .start();
        break;
    default:
        return false;
}
return true;
}

and finally set this onTouch method to your view:

ball.setOnTouchListener(this);


问:
Making a nested nameValuePairs
I want to make a nested nameValuePairs
something like this:

List nameValuePairs = new ArrayList(1);

    nameValuePairs.add(new BasicNameValuePair("key", new BasicNameValuePair("key2", "value").toString() ) );

I know this doesn't work, but what should I do to get this nesting right?

答:
I solved it!

the trick was to do it like this:

nameValuePairs.add(new
  BasicNameValuePair("[key][key2]",
  "value"));

Title: Making a nested nameValuePairs