问:
Active Record query for update between two ids in YII2 without using row query
I am noob in the YII2.
I am searching for an update query using Active Record in Yii2.
I need to update some record which are between two ids.

The Query:

```<code>UPDATE
table_name
SET status_name = 1
WHERE
id BETWEEN 1 AND 10;
</code>```

What I have tried in Active Record:

```<code>$command = Yii::$app->db->createCommand('UPDATE table_name SET status_name = 1 WHERE id BETWEEN 1 AND 10 ');
$command->execute();
</code>```

But I need Activerecord query without using row SQL queries.

答:
Like an another solution to question mentioned you can use Update counters:

Updating Counters
It is a common task to increment or decrement a column in a database table. We call these columns "counter columns". You can use updateCounters() to update one or multiple counter columns. For example,

```<code>$posts = TableName::find()->where(['between', 'id', "1", "10" ])->all();
$posts->updateCounters(['status_name' => 1]);
</code>```

Note: If you use yii\db\ActiveRecord::save() to update a counter
  column, you may end up with inaccurate result, because it is likely
  the same counter is being saved by multiple requests which read and
  write the same counter value.

Update:
Like mentioned in comments for Events like EVENT_AFTER_UPDATE to be occur You should do something like this:

```<code>$model = TableName::findOne()->where(['between', 'id', "1", "10" ])->all();
$model->status_name = new \yii\db\Expression('status_name + 1');
$model->save();
</code>```

This issue was discussed here: Event EVENT_AFTER_UPDATE does not occur when updateCounters

Body:
I am noob in the YII2.
I am searching for an update query using Active Record in Yii2.
I need to update some record which are between two ids.

The Query:

UPDATE
table_name
SET status_name = 1
WHERE
id BETWEEN 1 AND 10;

What I have tried in Active Record:

$command = Yii::$app->db->createCommand('UPDATE table_name SET status_name = 1 WHERE id BETWEEN 1 AND 10 ');
$command->execute();

But I need Activerecord query without using row SQL queries.

Body:
Like an another solution to question mentioned you can use Update counters:

Updating Counters
It is a common task to increment or decrement a column in a database table. We call these columns "counter columns". You can use updateCounters() to update one or multiple counter columns. For example,

$posts = TableName::find()->where(['between', 'id', "1", "10" ])->all();
$posts->updateCounters(['status_name' => 1]);

Note: If you use yii\db\ActiveRecord::save() to update a counter
  column, you may end up with inaccurate result, because it is likely
  the same counter is being saved by multiple requests which read and
  write the same counter value.

Update:
Like mentioned in comments for Events like EVENT_AFTER_UPDATE to be occur You should do something like this:

$model = TableName::findOne()->where(['between', 'id', "1", "10" ])->all();
$model->status_name = new \yii\db\Expression('status_name + 1');
$model->save();

This issue was discussed here: Event EVENT_AFTER_UPDATE does not occur when updateCounters


来源: stackexchange

问:
How to sum float numbers in the format hours and minutes?
How to sum float numbers in the format hours and minutes?

Those. if  calculate two such numbers 0.35+3.45 then it should be = 4.20, not 3.80

var arr = [0.15, 0.2, 3.45, 0.4, 2, 0.3, 5.2, 1, 1.4, 1.1, 2.4, 1, 3.4]

var sum = 0.0;

arr.forEach(function(item) {
  console.log(sum);
  sum += parseFloat(item);
});```
</div>
</div>
</p>

<p>The result should be like this:</p>

```0
0.15
0.35
4.20
5.0
7.0
7.30
12.50
13.50
15.30
16.40
19.20
20.20
```

答:
You need to convert everything either into hours or into minutes and then do the math.</p>

```<code>Example: 0.35 + 3.45
Convert 0.35 to Hours Number((35/60).toFixed(2))
= 0.58

Then convert 3hours 45 minutes into hours
= 3 + Number((45/60).toFixed(2))
= 3hours + 0.75 hours
= 3.75

Add the 2 conversions
= 0.58 + 3.75
= 4.33 hours

Convert the 0.33 back to minutes by multiplying by 60
= 4 hours 19.8 minutes ~ 20 mins

Hope that helps!
</code>```

ContentLicense: CC BY-SA 4.0

Body:
How to sum float numbers in the format hours and minutes?

Those. if  calculate two such numbers 0.35+3.45 then it should be = 4.20, not 3.80

var arr = [0.15, 0.2, 3.45, 0.4, 2, 0.3, 5.2, 1, 1.4, 1.1, 2.4, 1, 3.4]

var sum = 0.0;

arr.forEach(function(item) {
  console.log(sum);
  sum += parseFloat(item);
});

The result should be like this:

0
0.15
0.35
4.20
5.0
7.0
7.30
12.50
13.50
15.30
16.40
19.20
20.20

Body:
You need to convert everything either into hours or into minutes and then do the math.

Example: 0.35 + 3.45
Convert 0.35 to Hours Number((35/60).toFixed(2))
= 0.58

Then convert 3hours 45 minutes into hours
= 3 + Number((45/60).toFixed(2))
= 3hours + 0.75 hours
= 3.75

Add the 2 conversions
= 0.58 + 3.75
= 4.33 hours

Convert the 0.33 back to minutes by multiplying by 60
= 4 hours 19.8 minutes ~ 20 mins

Hope that helps!


问:
Workflow for Pact Testing in Feature Branches
I'm currently experimenting with Pact and stumbled over a problem with the workflow and can't find a satisfying solution. So hopefully someone can help me. :-)

First of all, that's my current workflow for changes on the consumer side:

The consumer changes are uploaded to Github in a feature branch

Pact tests are run on the CI system and the resulting pact is uploaded to the pact broker with the tags [feature-branch-name] and verify_feature (currently I only use the latter one)

The consumer waits for the verification (using the can-i-deploy tool)

The pact broker triggers the provider via webhook (trigger: contract_content_changed)

The provider runs pact-verify for the latest version tagged verify_feature and uploads the result

The consumer checks the result, if verification was successful the branch can be merged

So far so good. The problem arises when the consumer introduces breaking changes:

After the consumer uploads the changes to Github, the process described above is executed and the provider verification fails which in turn causes the consumer build to fail as expected.

Now the necessary changes are made on the provider side. The provider runs pact-verify against the consumer version of the testing stage and - if successful - the new version is then merged and deployed.

Now the new consumer version should be able to be merged as well. Alas, it does not work, because this version has not been verified again. And when I restart the CI job, the pact is re-uploaded to the pact broker, but since the pact content does not change no webhook is triggered. The consumer version is never verified.

So, what am I doing wrong?

答:
You need the new WIP pacts feature. It's currently under development, and could be available for beta testing in pact-js (and other languages that wrap the pact-ruby-standalone) within days if you wanted to try it out. If you're using pact-jvm, you'll have to wait a little longer, but we may be able to provide a work around. I've written a blog post on WIP pacts, but haven't published it yet because the feature is not ready for public release. You can find the post here http://blog.pact.io/p/51906e22-ccce-486b-9993-c21794e557d4/ I'd love to get your feedback on it.

Hop on to slack.pact.io and @ me if you'd like to chat further about this.


问:
Move the zoom-in/zoom-out to another place than upper-left corner
When using Vue2Leaflet and the "l-map" component, is there a way to move the zoom-in/zoom-out buttons to another place than upper-left corner?

https://vue-leaflet.github.io/Vue2Leaflet/#/components/l-map/?id=props

https://i.stack.imgur.com/ITRFr.png

答:
You need disable the default zoom controls first. Then add LControlZoom component with your preferred position. like-

```<code><l-control-zoom position="bottomleft"></l-control-zoom>
</code>```

HTML:

```<code><template>
 <l-map style="height: 350px" :zoom="zoom" :center="center" :options="{zoomControl: false}">
    <l-tile-layer :url="url"></l-tile-layer>
    <l-control-zoom position="bottomleft"></l-control-zoom>
 </l-map>
</code>```

in javaScript

```<code><script>
import {LMap, LTileLayer, LControlZoom} from 'vue2-leaflet';

export default {
  components: {
    LMap,
    LTileLayer,
    LControlZoom
  },
  data () {
    return {
      url: 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
      zoom: 8,
      center: [47.313220, -1.319482],
    };
  }
}
</script>
</code>```

Hope this helps. Read here vue2-leaflet documentation : https://vue2-leaflet.netlify.com/components/LControlZoom.html

Body:
You need disable the default zoom controls first. Then add LControlZoom component with your preferred position. like-

<l-control-zoom position="bottomleft"></l-control-zoom>

HTML:

<template>
 <l-map style="height: 350px" :zoom="zoom" :center="center" :options="{zoomControl: false}">
    <l-tile-layer :url="url"></l-tile-layer>
    <l-control-zoom position="bottomleft"></l-control-zoom>
 </l-map>

in javaScript

<script>
import {LMap, LTileLayer, LControlZoom} from 'vue2-leaflet';

export default {
  components: {
    LMap,
    LTileLayer,
    LControlZoom
  },
  data () {
    return {
      url: 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
      zoom: 8,
      center: [47.313220, -1.319482],
    };
  }
}
</script>

Hope this helps. Read here vue2-leaflet documentation : https://vue2-leaflet.netlify.com/components/LControlZoom.html


答:
You can try the below query.

You can get the details and learn from the link Aggregate Functions (Transact-SQL)
.

```<code>Select max(CREATED_DATE) as MaxCREATED_DATE
      , max(TASK_ID) as MaxTaskId
from yourtable
</code>```

You can also try the below one.

```<code>Select REFERENCE_NO, max(CREATED_DATE) as MaxCREATED_DATE
      , max(TASK_ID) as MaxTaskId
from yourtable
group by REFERENCE_NO
</code>```

Here is an implementation based on your sample data.

```<code>create table TestTable(REFERENCE_NO Varchar(10), TASK_ID int, CREATED_DATE Datetime)
insert into TestTable Values
('244038', 83102, '2020-01-14 09:23:21'),
('244038', 83114, '2020-01-14 09:23:21')

Select REFERENCE_NO, max(CREATED_DATE) as MaxCREATED_DATE
      , max(TASK_ID) as MaxTaskId
from TestTable
group by REFERENCE_NO
</code>```

The output is:

```<code>REFERENCE_NO    MaxCREATED_DATE            MaxTaskId
----------------------------------------------------
244038          2020-01-14 09:23:21.000    83114
</code>```

Live db<>fiddle Demo

It looks like as shown below.

Title: Select max TASK_ID and CREATED_DATE - already tried MAX and DISTINCT

Body:
I need to fetch only the second record and ignore the first one.
I have this data:

REFERENCE_NO       TASK_ID        CREATED_DATE
------------------------------------------------------------
244038             83102          2020-01-14 09:23:21:000000
244038             83114          2020-01-14 09:23:21:867000

Expected Output:

REFERENCE_NO       TASK_ID        CREATED_DATE
------------------------------------------------------------
244038             83114          2020-01-14 09:23:21:867000

Body:
You can try the below query.

You can get the details and learn from the link Aggregate Functions (Transact-SQL)
.

Select max(CREATED_DATE) as MaxCREATED_DATE
      , max(TASK_ID) as MaxTaskId
from yourtable

You can also try the below one.

Select REFERENCE_NO, max(CREATED_DATE) as MaxCREATED_DATE
      , max(TASK_ID) as MaxTaskId
from yourtable
group by REFERENCE_NO

Here is an implementation based on your sample data.

create table TestTable(REFERENCE_NO Varchar(10), TASK_ID int, CREATED_DATE Datetime)
insert into TestTable Values
('244038', 83102, '2020-01-14 09:23:21'),
('244038', 83114, '2020-01-14 09:23:21')

Select REFERENCE_NO, max(CREATED_DATE) as MaxCREATED_DATE
      , max(TASK_ID) as MaxTaskId
from TestTable
group by REFERENCE_NO

The output is:

REFERENCE_NO    MaxCREATED_DATE            MaxTaskId
----------------------------------------------------
244038          2020-01-14 09:23:21.000    83114

Live db<>fiddle Demo

It looks like as shown below.


问:
Create text input bar always pinned to bottom
I'm trying to create a Row widget that will be pinned to the bottom always like the below screenshot. I currently have a large container containing text (open to changing this to a card) followed by smaller cards which are scrollable. I would like to pin a bar to the bottom so a user can enter text and add a card. I'm not sure how to pin this to the bottom of the UI without interfering with the cards causing a pixel overflow. What is the best way to achieve this? I'd ideally like to achieve a bottom row that is similar to Facebook Messengers'

Code:

```<code>class TextBarAtBottom extends StatelessWidget {
  TextEditingController commentController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return
    Container(
              height: 20.0,
              padding: EdgeInsets.symmetric(vertical: 2.0),
              alignment: Alignment.bottomCenter,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  // First child is enter comment text input
                  TextFormField(
                                  controller: commentController,
                                  autocorrect: false,
                                  decoration: new InputDecoration(
                                    labelText: "Some Text",
                                    labelStyle:
                                        TextStyle(fontSize: 20.0, color: Colors.white),
                                    fillColor: Colors.blue,
                                    border: OutlineInputBorder(
                                        // borderRadius:
                                        //     BorderRadius.all(Radius.zero(5.0)),
                                        borderSide:
                                            BorderSide(color: Colors.purpleAccent)),
                                  ),
                    ),
                    // Second child is button
                  IconButton(
                    icon: Icon(Icons.send),
                    iconSize: 20.0,
                    onPressed: _onPressedSend(),
                  )
                ]
              )
              );
  }
}
</code>```

答:
Following is the sample code:

```<code>body: Stack(
        children: <Widget>[
          Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Text(
                  'You have pushed the button this many times:',
                ),
                Text(
                  '$_counter',
                  style: Theme.of(context).textTheme.display1,
                ),
              ],
            ),
          ),
//Following container with row will always stay bottom and if keyboard opens it will be right above the keyboard
          Container(
            width: MediaQuery.of(context).size.width,
            height: MediaQuery.of(context).size.height,
            alignment: Alignment.bottomCenter,
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.center,
              mainAxisSize: MainAxisSize.max,
              children: <Widget>[
                Text('text 1'),
                Text('text 2'),
              ],
            ),
          )
        ],
      ),
</code>```

Hope this helps.

Body:
I'm trying to create a Row widget that will be pinned to the bottom always like the below screenshot. I currently have a large container containing text (open to changing this to a card) followed by smaller cards which are scrollable. I would like to pin a bar to the bottom so a user can enter text and add a card. I'm not sure how to pin this to the bottom of the UI without interfering with the cards causing a pixel overflow. What is the best way to achieve this? I'd ideally like to achieve a bottom row that is similar to Facebook Messengers'

Code:

class TextBarAtBottom extends StatelessWidget {
  TextEditingController commentController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return
    Container(
              height: 20.0,
              padding: EdgeInsets.symmetric(vertical: 2.0),
              alignment: Alignment.bottomCenter,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  // First child is enter comment text input
                  TextFormField(
                                  controller: commentController,
                                  autocorrect: false,
                                  decoration: new InputDecoration(
                                    labelText: "Some Text",
                                    labelStyle:
                                        TextStyle(fontSize: 20.0, color: Colors.white),
                                    fillColor: Colors.blue,
                                    border: OutlineInputBorder(
                                        // borderRadius:
                                        //     BorderRadius.all(Radius.zero(5.0)),
                                        borderSide:
                                            BorderSide(color: Colors.purpleAccent)),
                                  ),
                    ),
                    // Second child is button
                  IconButton(
                    icon: Icon(Icons.send),
                    iconSize: 20.0,
                    onPressed: _onPressedSend(),
                  )
                ]
              )
              );
  }
}

Body:
Following is the sample code:

body: Stack(
        children: <Widget>[
          Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Text(
                  'You have pushed the button this many times:',
                ),
                Text(
                  '$_counter',
                  style: Theme.of(context).textTheme.display1,
                ),
              ],
            ),
          ),
//Following container with row will always stay bottom and if keyboard opens it will be right above the keyboard
          Container(
            width: MediaQuery.of(context).size.width,
            height: MediaQuery.of(context).size.height,
            alignment: Alignment.bottomCenter,
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.center,
              mainAxisSize: MainAxisSize.max,
              children: <Widget>[
                Text('text 1'),
                Text('text 2'),
              ],
            ),
          )
        ],
      ),

Hope this helps.


答:
I am waiting for my model to run, so here's an over-killed answer:

```<code>df = pd.DataFrame({
    'A':[['a','b','c'], ['c','b','e','a'],['a','b','c']],
    'B':[['a','b'],['b','e','a'],['a','b','d','e']]
})

(df['A'].explode().reset_index()
               .merge(df['B'].explode().reset_index(),
                      left_on=['index','A'],
                      right_on=['index','B'],
                      how='outer')
    .set_index('index')
    .assign(occur=lambda x: x.notna().sum(axis=1),
            value=lambda x: x.ffill(1)['B'])
    .assign(total=lambda x: x.groupby('index')['occur'].transform('count'))
    .assign(score=lambda x: x['occur']/x['total'])
    .drop(['A','B','occur','total'], axis=1)
    .groupby('index').apply(lambda x: x.set_index('value')['score'].to_dict())
)
</code>```

Output:

```<code>index
0    {'a': 0.6666666666666666, 'b': 0.6666666666666...
1            {'c': 0.25, 'b': 0.5, 'e': 0.5, 'a': 0.5}
2    {'a': 0.4, 'b': 0.4, 'c': 0.2, 'd': 0.2, 'e': ...
dtype: object
</code>```

Title: How to solve this obscure and excessively localised problem with pandas?

Body:
I have this data frame wherein I want to give a score to each of the element in a distinct values column.

+-------------------------------+-------------------------------+------------------------------+
|            A                  |             B                 |      Distinct Values         |
+-------------------------------+-------------------------------+------------------------------+
| ['a', 'b', 'c']               |   ['a', 'b']                  |  ['a', 'b', 'c']             |
| ['c', 'b', 'e', 'a']          |   ['b', 'e', 'a']             |  ['a', 'b', 'e', 'c']        |
| ['a', 'b', 'd', 'e']          |   ['a', 'b', 'c']             |  ['a', 'b', 'd', 'e', 'c']   |
| ['a', 'b', 'c']               |   ['a', 'd', 'c']             |  ['a', 'b', 'c', 'd']        |
|                               |                               |                              |
+-- ----------------------------+-------------------------------+------------------------------+

           ( NO. of times that element has occurred in A and B)
Scoring =  ----------------------------------------------------
               (Total number of elements(Distinct Values))

This is how it would look like after scoring:

+------------------------+--------------------+-----------------------------------------------+
|            A           |         B          |      Distinct_Values_with_scoring             |
+------------------------+--------------------+-----------------------------------------------+
| ['a', 'b', 'c']        |   ['a', 'b']       |['a':2/3, 'b':2/3, 'c':1/3]                    |
| ['c', 'b', 'e', 'a']   |   ['b', 'e', 'a']  |['a':2/4, 'b':2/4, 'e':2/4, 'c':1/4]           |
| ['a', 'b', 'd', 'e']   |   ['a', 'b', 'c']  |['a':2/5, 'b':2/5, 'd':1/5, 'e':1/5, 'c':1/5]  |
| ['a', 'b', 'c']        |   ['a', 'd', 'c']  |['a':2/4, 'b':1/4, 'c':2/4, 'd':1/4]           |
|                        |                    |                                               |
+-- ---------------------+--------------------+-----------------------------------------------+

How can I go about solving this problem in pandas?

d = {"A":[['a', 'b', 'c'], ['c', 'b', 'e', 'a'],
          ['a', 'b', 'd', 'e'], ['a', 'b', 'c']],
     "B": [['a', 'b'],['b', 'e', 'a'],['a', 'b', 'c'],
           ['a', 'd', 'c']],
     "Distinct Values": [['a', 'b', 'c'], ['a', 'b', 'e', 'c'],
           ['a', 'b', 'd', 'e', 'c'], ['a', 'b', 'c', 'd']]}
data = pd.DataFrame(d)

Body:
I am waiting for my model to run, so here's an over-killed answer:

df = pd.DataFrame({
    'A':[['a','b','c'], ['c','b','e','a'],['a','b','c']],
    'B':[['a','b'],['b','e','a'],['a','b','d','e']]
})

(df['A'].explode().reset_index()
               .merge(df['B'].explode().reset_index(),
                      left_on=['index','A'],
                      right_on=['index','B'],
                      how='outer')
    .set_index('index')
    .assign(occur=lambda x: x.notna().sum(axis=1),
            value=lambda x: x.ffill(1)['B'])
    .assign(total=lambda x: x.groupby('index')['occur'].transform('count'))
    .assign(score=lambda x: x['occur']/x['total'])
    .drop(['A','B','occur','total'], axis=1)
    .groupby('index').apply(lambda x: x.set_index('value')['score'].to_dict())
)

Output:

index
0    {'a': 0.6666666666666666, 'b': 0.6666666666666...
1            {'c': 0.25, 'b': 0.5, 'e': 0.5, 'a': 0.5}
2    {'a': 0.4, 'b': 0.4, 'c': 0.2, 'd': 0.2, 'e': ...
dtype: object


问:
ScrollView with Buttons inside, no response until second click on any button inside
I've been a couple of days trying to solve this thing but I can't figure it out. The problem is, simple activity, with simple layout, ScrollView -> LinearLayout -> and a lot of buttons inside the layout (within the scroll content). Everything works just fine, but one tricky thing. When I click a button, let's say at the top of the scroll content and immediately scroll down to the bottom of the content and click another button there, nothing happens until I click a second time and all comes to normal again. This can be reproduced anytime and it's code independent (I've tried more than 20 scenarios). I don't have much experience in Android yet, but looks like the scroll listener stops the onClick listener or something like that. Any help with this would be much appreciated. Thank you in advance.

PD. If I programmatically do a scrollTo(), instead of manual scroll with my fingers, everything works just fine and the click responds at first touch. It's simply overwhelming me.

答:
I've been able to fix this by overriding onScrollChanged, then sending the ScrollView a MotionEvent via OnTouchEvent when the bounds are reached to simulate a user touch.

It's the hackiest, dirtiest programming I can imagine, but it works ok in my application. This app is for phones running 2.2 only, and this bug needed to be fixed somehow.

If anyone has a better solution please let me know.

Edit: This problem is only in 2.2 btw, they've fixed it in 2.3, and it wasn't an issue in 2.1.

ContentLicense: CC BY-SA 3.0


问:
Set-text in text-input only from flat-list
How to set text in text-input only if user select any item from flat-list. i have a text-input filed labeled as city that show a list of available city(filter with text) while typing city name.
Issue is i want only the city available from list but there is a bug that if user proceed without selecting any item the input text is remains as city name.</p>

```<code><View style={styles.inputContainer}>
                <Text style={styles.labelText} children={"City"} />
                <TextInput
                  style={styles.textInput}
                  ref={"city"}
                  onChangeText={city =>
                    this.setState(
                      { showCities: city != "" && city != null },
                      () => {
                        this.searchCityFunction(city);
                      }
                    )
                  }
                  // onChangeText={val => this.setState({city: val})}
                  onSubmitEditing={() => this.refs.pincode.focus()}
                  defaultValue={this.state.city}
                  keyboardType="email-address"
                  returnKeyType="next"
                  placeholder="City"
                  placeholderTextColor={Colors.placeHolderColor}
                  selectionColor={Colors.notificationHeaderTextColor}
                  maxLength={25}
                />
                {this.state.showCities && (
                  <FlatList
                    numColumns={1}
                    keyboardShouldPersistTaps={"always"}
                    keyboardDismissMode={"on-drag"}
                    maxHeight={Dimens.twoHundred}
                    ItemSeparatorComponent={this._ItemSeparatorComponent}
                    data={cityArr}
                    nestedScrollEnabled={true}
                    extraData={cityArr}
                    disableVirtualization={false}
                    style={styles.listContainer}
                    renderItem={this._renderItems}
                    ListEmptyComponent={() => {
                      return (
                        <Text
                          style={{
                            flex: 1,
                            marginTop: "50%",
                            textAlign: "center",
                            fontFamily: Fonts.SourceSansProSemibolds,
                            fontSize: Dimens.twenty,
                            padding: Dimens.tweleve
                          }}
                          children={"No city available by this name"}
                        />
                      );
                    }}
                    getItemLayout={(data, index) => ({
                      length: 30,
                      offset: 30 * index,
                      index
                    })}
                    keyExtractor={(item, index) => {
                      (
                        index + Math.floor(Math.random() * Math.floor(3))
                      ).toString();
                    }}
                  />
                )}
              </View>
</code>```

答:
Use "value" prop of TextInput, It is used to show the default value of the textinput field.
As the user will click the flatlist item, then city will be set and your textinput will start showing selected city name.

like:

```<code><TextInput
    value={this.state.city}
    onChangeText = { (text) => { this.setState({ city: text}) } }
/>

renderItems= ({item}) =>{
//renterItem of Your Flatlist
return(
<TouchableOpacity onPress={() => this.setState({city : item.cityName})}>
  <Text>{item.cityName}</Text>
</TouchableOpacity>
)
}
</code>```

Body:
How to set text in text-input only if user select any item from flat-list. i have a text-input filed labeled as city that show a list of available city(filter with text) while typing city name.
Issue is i want only the city available from list but there is a bug that if user proceed without selecting any item the input text is remains as city name.

<View style={styles.inputContainer}>
                <Text style={styles.labelText} children={"City"} />
                <TextInput
                  style={styles.textInput}
                  ref={"city"}
                  onChangeText={city =>
                    this.setState(
                      { showCities: city != "" && city != null },
                      () => {
                        this.searchCityFunction(city);
                      }
                    )
                  }
                  // onChangeText={val => this.setState({city: val})}
                  onSubmitEditing={() => this.refs.pincode.focus()}
                  defaultValue={this.state.city}
                  keyboardType="email-address"
                  returnKeyType="next"
                  placeholder="City"
                  placeholderTextColor={Colors.placeHolderColor}
                  selectionColor={Colors.notificationHeaderTextColor}
                  maxLength={25}
                />
                {this.state.showCities && (
                  <FlatList
                    numColumns={1}
                    keyboardShouldPersistTaps={"always"}
                    keyboardDismissMode={"on-drag"}
                    maxHeight={Dimens.twoHundred}
                    ItemSeparatorComponent={this._ItemSeparatorComponent}
                    data={cityArr}
                    nestedScrollEnabled={true}
                    extraData={cityArr}
                    disableVirtualization={false}
                    style={styles.listContainer}
                    renderItem={this._renderItems}
                    ListEmptyComponent={() => {
                      return (
                        <Text
                          style={{
                            flex: 1,
                            marginTop: "50%",
                            textAlign: "center",
                            fontFamily: Fonts.SourceSansProSemibolds,
                            fontSize: Dimens.twenty,
                            padding: Dimens.tweleve
                          }}
                          children={"No city available by this name"}
                        />
                      );
                    }}
                    getItemLayout={(data, index) => ({
                      length: 30,
                      offset: 30 * index,
                      index
                    })}
                    keyExtractor={(item, index) => {
                      (
                        index + Math.floor(Math.random() * Math.floor(3))
                      ).toString();
                    }}
                  />
                )}
              </View>

Body:
Use "value" prop of TextInput, It is used to show the default value of the textinput field.
As the user will click the flatlist item, then city will be set and your textinput will start showing selected city name.

like:

<TextInput
    value={this.state.city}
    onChangeText = { (text) => { this.setState({ city: text}) } }
/>

renderItems= ({item}) =>{
//renterItem of Your Flatlist
return(
<TouchableOpacity onPress={() => this.setState({city : item.cityName})}>
  <Text>{item.cityName}</Text>
</TouchableOpacity>
)
}


问:
Dice Simulator project in Python 3
My code works to quit the program for my 'elif' and 'else' statements, but when I input 'yes', I'm stuck in this input loop where anything I input still rolls the dice. How can I get out of the program by inputting 'no', once I've already inputted 'yes' and entered the loop? </p>

<hr>

```<code>import random

min = 1
max = 6

prompt = "Roll dice? Type yes or no. "
roll_dice = input(prompt)

while roll_dice:

    if roll_dice == "yes":
        print ("you rolled", random.randint(min, max), random.randint(min, max))
        input(prompt)

    elif roll_dice == "no":
        print ("see you later!")
        break

    else:
        print ("invalid answer")
        break
</code>```

答:
Instead of just doing:

```<code>input(prompt)
</code>```

Which does nothing with the given input which means
roll_dice will always be equal to yes and you will be stuck in an infinite loop.

You should use:

```<code>roll_dice = input(prompt)
</code>```

which sets roll_dice to the new value, and hence lets you exit out of the loop.

Title: Dice Simulator project in Python 3

Body:
My code works to quit the program for my 'elif' and 'else' statements, but when I input 'yes', I'm stuck in this input loop where anything I input still rolls the dice. How can I get out of the program by inputting 'no', once I've already inputted 'yes' and entered the loop?

import random

min = 1
max = 6

prompt = "Roll dice? Type yes or no. "
roll_dice = input(prompt)

while roll_dice:

    if roll_dice == "yes":
        print ("you rolled", random.randint(min, max), random.randint(min, max))
        input(prompt)

    elif roll_dice == "no":
        print ("see you later!")
        break

    else:
        print ("invalid answer")
        break

Body:
Instead of just doing:

input(prompt)

Which does nothing with the given input which means
roll_dice will always be equal to yes and you will be stuck in an infinite loop.

You should use:

roll_dice = input(prompt)

which sets roll_dice to the new value, and hence lets you exit out of the loop.


问:
Figure out a way to convert a var implementation to val
I'm using the following interface from a Java library:

```<code>// This is a Java class from a library I'm using
public interface Listener {
  void receiveConfigInfo(final String configInfo);
}
</code>```

And I'm extending it as follows, in Scala:

```<code>//MyClass needs to extends the Listener interface
final class MyClass extends Listener {
  private var config = Option.empty

  // Implement the the Listener interface
  override def receiveConfigInfo(configInfo: String): Unit = {
    try {
      config  = decode[Map[String, String]](configInfo) match {
        case Right(config) => Some(config)
        case Left(_) => None
      }
    } catch {
      case _: Throwable => nacosConfig = None
    }
  }

  override def getConfig():Option[Map[String, String]] = nacosConfig
}
</code>```

receiveConfigInfo will be called in automatically whenever relevant.

getConfig returns the latest value of configuration.

Is there a way to make config into a val, rather than a mutable var? I cannot change the signature of receiveConfigInfo, as it needs to respect the signature of parent class.

The objective is whenever I call getConfig, I should get latest config value. However my current implementation has a var which is not good, is there any way to change this code to make it val or another way if possible?

答:
If you really want to use a val, you can use one of the mutable structures in collection.mutable. However, it would be more roundabout, possibly prone to error, and behind the scenes, actually using var, so you might as well directly use var (the way your code already is).

// in class structure
val config = collection.mutable.IndexedSeq[Option[Map[String, String]]](None)
...
// in receiveConfigInfo
config(0) = decode ...

// in getConfig
config(0)
```

Body:
I'm using the following interface from a Java library:

// This is a Java class from a library I'm using
public interface Listener {
  void receiveConfigInfo(final String configInfo);
}

And I'm extending it as follows, in Scala:

//MyClass needs to extends the Listener interface
final class MyClass extends Listener {
  private var config = Option.empty

  // Implement the the Listener interface
  override def receiveConfigInfo(configInfo: String): Unit = {
    try {
      config  = decode[Map[String, String]](configInfo) match {
        case Right(config) => Some(config)
        case Left(_) => None
      }
    } catch {
      case _: Throwable => nacosConfig = None
    }
  }

  override def getConfig():Option[Map[String, String]] = nacosConfig
}

receiveConfigInfo will be called in automatically whenever relevant.

getConfig returns the latest value of configuration.

Is there a way to make config into a val, rather than a mutable var? I cannot change the signature of receiveConfigInfo, as it needs to respect the signature of parent class.

The objective is whenever I call getConfig, I should get latest config value. However my current implementation has a var which is not good, is there any way to change this code to make it val or another way if possible?


问:
React ref undefined
so I'm having a little trouble using ref's with React.

All I'm trying to do is print the text content of an element using ref's like this:

```<code>export default class SomeClass extends Component {
  constructor(props) {
    super(props);
    this.intro = React.createRef();
    console.log(this.intro.textContent);
  }

  render() {
    return (
      <div ref={this.intro}>Hi</div>
    )
  }
}
</code>```

However, this always prints null or undefined instead of "Hi" which is what I want.

答:
You are console logging in the constructor before Dom is actually rendered.
Try console logging in an onClick handler instead.

```<code>export default class SomeClass extends Component {
 constructor(props) {
  super(props);
  this.intro = React.createRef();
 }
 print = () => {
   console.log(this.intro.textContent);
 }
 render() {
   return (
     <div>
       <div ref={this.intro}>Hi</div>
       <button onClick={this.print}>Print</div>
     </div>
   )
 }
</code>```

}

Title: React ref undefined

Body:
so I'm having a little trouble using ref's with React.

All I'm trying to do is print the text content of an element using ref's like this:

export default class SomeClass extends Component {
  constructor(props) {
    super(props);
    this.intro = React.createRef();
    console.log(this.intro.textContent);
  }

  render() {
    return (

Hi

    )
  }
}

However, this always prints null or undefined instead of "Hi" which is what I want.

Body:
You are console logging in the constructor before Dom is actually rendered.
Try console logging in an onClick handler instead.

export default class SomeClass extends Component {
 constructor(props) {
  super(props);
  this.intro = React.createRef();
 }
 print = () => {
   console.log(this.intro.textContent);
 }
 render() {
   return (
     <div>
       <div ref={this.intro}>Hi</div>
       <button onClick={this.print}>Print</div>
     </div>
   )
 }

}


问:
Inner Join with similar IDs
I have two tables, say:

```<code>Table 1

id, name, place
1, a, b
2, c, d
3, e, f

Table 2

id,text
1, hello
1, bye
1, what
2, tired
</code>```

Desired Output

```<code>id, name, place, text
1, a, b, hello or bye or what (any one of the three)
2, c, d, tired
</code>```

I have seen a lot of posts but I couldn't find anything similar. I am new to SQL/Postgresql. I am doing it in PostgreSQL.

答:
You can aggregate multiple values in an array and pick a random value (postgres syntax):

```<code>select t1.id, (array_agg(t2.text))[floor(random() * count(t2.text) + 1)::int]
from table1 t1
inner join table2 t2 on t1.id = t2.id
group by t1.id
</code>```

Or a bit faster, but will pick first value only:

```<code>select t1.id, (array_agg(t2.text))[1]
from table1 t1
inner join table2 t2 on t1.id = t2.id
group by t1.id
</code>```

Title: Inner Join with similar IDs

Body:
I have two tables, say:

Table 1

id, name, place
1, a, b
2, c, d
3, e, f

Table 2

id,text
1, hello
1, bye
1, what
2, tired

Desired Output

id, name, place, text
1, a, b, hello or bye or what (any one of the three)
2, c, d, tired

I have seen a lot of posts but I couldn't find anything similar. I am new to SQL/Postgresql. I am doing it in PostgreSQL.

Body:
You can aggregate multiple values in an array and pick a random value (postgres syntax):

select t1.id, (array_agg(t2.text))[floor(random() * count(t2.text) + 1)::int]
from table1 t1
inner join table2 t2 on t1.id = t2.id
group by t1.id

Or a bit faster, but will pick first value only:

select t1.id, (array_agg(t2.text))[1]
from table1 t1
inner join table2 t2 on t1.id = t2.id
group by t1.id


问:
How to make greedy regex for heading text? [as against tailing text]
Consider the following text:

```<code><bla><bla text><bla>
</code>```

I want to get the regex to match exactly the middle <bla text>. I tried \<.*?text.*?\> but it is capturing the string right from the start, since it starts with '<'.

Thanks a lot.

答:
This regex matches the central <bla text> and captures it as the first match (brackets included):

```<code>(\<\w+? \w+?\>)
</code>```

Explained, it matches:

a <

then, any non-empty sequence of word characters (\w is the shorthand for [a-zA-z_])

then exactly one space

then another "greedy" sequence of word chars

a final >

That is, it matches exactly two words separated by exactly one space, all enclosed in <..>.

This one:

```<code>(\<\w+?\s+\w+?\>)
</code>```

also matches any number of spaces between the two words.

Finally, this one:

```<code><\w+?>(\<\w+? \w+\>)<\w+?>
</code>```

matches all the string, but captures the content of the central block, so that, if you want to replace the <bla><bla text><bla> string, you may refer to the central block using $1 or \1 in your replacement string.

Body:
Consider the following text:

<bla><bla text><bla>

I want to get the regex to match exactly the middle <bla text>. I tried \<.*?text.*?\> but it is capturing the string right from the start, since it starts with '<'.

Thanks a lot.

Body:
This regex matches the central <bla text> and captures it as the first match (brackets included):

(\<\w+? \w+?\>)

Explained, it matches:

a <

then, any non-empty sequence of word characters (\w is the shorthand for [a-zA-z_])

then exactly one space

then another "greedy" sequence of word chars

a final >

That is, it matches exactly two words separated by exactly one space, all enclosed in <..>.

This one:

(\<\w+?\s+\w+?\>)

also matches any number of spaces between the two words.

Finally, this one:

<\w+?>(\<\w+? \w+\>)<\w+?>

matches all the string, but captures the content of the central block, so that, if you want to replace the <bla><bla text><bla> string, you may refer to the central block using $1 or \1 in your replacement string.


问:
use jquery datetime picker inside an asp.net content page and repeater control
I need to add java script tag in content page of asp.net application. The script works fine with html tags but in content it is not working here is the code.
This is my code to display datetime picker :

```<code><asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <link  rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css"/>
    <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery.ui.min.js"></script>
    <script type="text/javascript" >
        $(function dtTimePicker()
        {
            $("txtDate").datepicker({
                dateFormat: 'dd-MM-yyyy',
                changeMonth: true,
                changeYear:true

            });
        });
    </script>
    <hr />
    <asp:TextBox runat="server" ID="txtDate"></asp:TextBox>
    <asp:Button runat="server" ID="btnDate" Text="Search" OnClick="btnDate_Click"></asp:Button>
    <hr />
    <div class="container">
        <div class="form-horizontal">
            <div class="form-group">
                <div class="col-md-2"></div>
            </div>
        </div>
        <h1>MANHOUR</h1>
        <hr />
        <div class="panel panel-default">
            <!-- Default panel contents -->
            <div class="panel-heading">DAILYDATAWH</div>
            <asp:Repeater ID="rptrDAILYDATAWH" runat="server">
                <HeaderTemplate>

                    <table class="table">
                        <thead>
                            <tr>
                                <th>STATUSIN</th>
                                <th>NIP</th>
                            </tr>
                        </thead>
                        <tbody>
                </HeaderTemplate>
                <ItemTemplate>
                    <tr>
                        <th><%# Eval("STATUSIN") %></th>
                        <th><%# Eval("NIP") %></th>
                    </tr>
                </ItemTemplate>
                <FooterTemplate>
                    <asp:Label ID="defaultItem" runat="server"
                        Visible='<%# rptrDAILYDATAWH.Items.Count == 0 %>' Text="No items found" />
                        </tbody>
                    </table>
                </FooterTemplate>
            </asp:Repeater>
        </div>
    </div>
</asp:Content>
</code>```

and this is my code on backend :

```<code> protected void btnDate_Click(object sender, EventArgs e)
        {
            HtmlGenericControl body = (HtmlGenericControl)Page.Master.FindControl("pagebody");
            body.Attributes.Add("onload", "dtTimePicker();");
            String CS = ConfigurationManager.ConnectionStrings["MANHOURConnectionString"].ConnectionString;
            SqlConnection con = new SqlConnection(CS);
            con.Open();
            SqlCommand cmd = new SqlCommand("SELECT * FROM [dbo].[DAILYDATAWH] WHERE STATUSIN=@STATUSIN", con);
            cmd.Parameters.AddWithValue("@STATUSIN", txtDate.Text);
            DataTable dtDaily = new DataTable();
            SqlDataAdapter sda = new SqlDataAdapter(cmd);
            sda.Fill(dtDaily);

            rptrDAILYDATAWH.DataSource = dtDaily;
            rptrDAILYDATAWH.DataBind();
        }
</code>```

I want to filter datetime in STATUSIN and get the records from database with selected date. How to place jquery datetime picker inside content page with repeater control?

答:
By "doesn't work" I presume you mean the datepicker doesn't render correctly ?

Firstly, $("txtDate").datepicker({ - you haven't included an ID selector, so it would be $("#txtDate").datepicker({

However inside a repeater, $("txtDate").datepicker({ is not going to work for your <asp:TextBox runat="server" ID="txtDate"> because each instance of the textbox inside your repeater is not going to have 'txtDate' as its ID; it will have a generated ID that the naming container (the repeater) will generate. If you inspect the HTML using browser debug tools you can confirm this.

If all you need to do is render the textbox as a jQuery datepicker, use a Class selector instead, i.e.

<asp:TextBox runat="server" ID="txtDate" CssClass="datepick">

and change your jQuery to

$(".datepick").datepicker({

Body:
I need to add java script tag in content page of asp.net application. The script works fine with html tags but in content it is not working here is the code.
This is my code to display datetime picker :

<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">

    <link  rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css"/>

    <asp:TextBox runat="server" ID="txtDate"></asp:TextBox>
    <asp:Button runat="server" ID="btnDate" Text="Search" OnClick="btnDate_Click"></asp:Button>

MANHOUR

DAILYDATAWH

            <asp:Repeater ID="rptrDAILYDATAWH" runat="server">
                <HeaderTemplate>

                                STATUSIN
                                NIP

                </HeaderTemplate>
                <ItemTemplate>

                        <%# Eval("STATUSIN") %>
                        <%# Eval("NIP") %>

                </ItemTemplate>
                <FooterTemplate>
                    <asp:Label ID="defaultItem" runat="server"
                        Visible='<%# rptrDAILYDATAWH.Items.Count == 0 %>' Text="No items found" />

                </FooterTemplate>
            </asp:Repeater>

</asp:Content>

and this is my code on backend :

 protected void btnDate_Click(object sender, EventArgs e)
        {
            HtmlGenericControl body = (HtmlGenericControl)Page.Master.FindControl("pagebody");
            body.Attributes.Add("onload", "dtTimePicker();");
            String CS = ConfigurationManager.ConnectionStrings["MANHOURConnectionString"].ConnectionString;
            SqlConnection con = new SqlConnection(CS);
            con.Open();
            SqlCommand cmd = new SqlCommand("SELECT * FROM [dbo].[DAILYDATAWH] WHERE STATUSIN=@STATUSIN", con);
            cmd.Parameters.AddWithValue("@STATUSIN", txtDate.Text);
            DataTable dtDaily = new DataTable();
            SqlDataAdapter sda = new SqlDataAdapter(cmd);
            sda.Fill(dtDaily);

            rptrDAILYDATAWH.DataSource = dtDaily;
            rptrDAILYDATAWH.DataBind();
        }

I want to filter datetime in STATUSIN and get the records from database with selected date. How to place jquery datetime picker inside content page with repeater control?


问:
attribute binding with Template literals doesn't work in vuejs components?
```<code><html>
<head>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<script type="text/x-template" id="permissions">
    <div>
        <h3 v-bind:data=`haha-${title}` >{{ title }}</h3>
    </div>
</script>

<div id="app">
    <blog-post title="My journey with Vue"></blog-post>
</div>

<script>
    Vue.component('blog-post', {
        props: ['title'],
        template: '#permissions'
    })
</script>
<script>
    new Vue({
        el: "#app"
    });
</script>
</body>
</html>
</code>```

This is my code. I bind the data attribute on h3 to "haha"+ title.

This technique works on regular vue elements, but it doesn't work on vue component. The result is

Why does it happen? How to fix it?

答:
I believe you're looking for this:

<h3 v-bind:data="`haha-${title}`">{{ title }}

```

Attribute values need to be delimited with either " or '. The v-bind: prefix causes Vue to treat the value of the attribute as a JavaScript expression. Within that expression the backticks will be interpreted as you're expecting. You can't just merge the two sets of quotes, they serve different purposes.

Body:
    <blog-post title="My journey with Vue"></blog-post>

This is my code. I bind the data attribute on h3 to "haha"+ title.

This technique works on regular vue elements, but it doesn't work on vue component. The result is

Why does it happen? How to fix it?

Body:
I believe you're looking for this:

<h3 v-bind:data="`haha-${title}`">{{ title }}</h3>

Attribute values need to be delimited with either " or '. The v-bind: prefix causes Vue to treat the value of the attribute as a JavaScript expression. Within that expression the backticks will be interpreted as you're expecting. You can't just merge the two sets of quotes, they serve different purposes.


问:
automatization of requests
I need to carve out JSON-file from web interface for a certain time period. Notes' limit - 100. JSON-file consists from some events and timestamps, when events happened. If the response is too big, I get the notification in file - moreDataAvailable = True. To get other data which are not included in file that I already got, I need to make a new request with some changes in URL - to change the timestamp on timestamp of last event (receivedDateTime) increased it by 1 millisecond.

So, I've already wrote the request via Python with requests.get()

```<code>>>> import requests
>>> response = requests.get(
...     'https://api.blablabla.com/event/eventstatuses?requestId=1234&datetype=received&starttime=2020-02-10T00%3A00%3A57.001Z&...'
... )
>>> json_response = response.json()
>>> print(json_response)
</code>```

How I can to automatize my requests to carve out all data in requested period? (moreDataAvailable = False)
Is it possible to connect all downloaded JSONs, for example, in a one file to export it in a data warehouse?

答:
You can just write a loop for this. </p>

```<code>import time
timeout = time.time() + 60*5   # 5 minutes from now
while True:
    sendRequest()
    if time.time() > timeout:
        break
    time.sleep(60)   # Delays for 60 seconds. You can also use a float value.

def sendRequest():
  import requests
  response = requests.get(
    'https://api.blablabla.com/event/eventstatuses?
      requestId=1234&datetype=received&starttime=2020-02-
       10T00%3A00%3A57.001Z&...'
   )
  json_response = response.json()
  print(json_response)
</code>```

Title: automatization of requests

Body:
I need to carve out JSON-file from web interface for a certain time period. Notes' limit - 100. JSON-file consists from some events and timestamps, when events happened. If the response is too big, I get the notification in file - moreDataAvailable = True. To get other data which are not included in file that I already got, I need to make a new request with some changes in URL - to change the timestamp on timestamp of last event (receivedDateTime) increased it by 1 millisecond.

So, I've already wrote the request via Python with requests.get()

>>> import requests
>>> response = requests.get(
...     'https://api.blablabla.com/event/eventstatuses?requestId=1234&datetype=received&starttime=2020-02-10T00%3A00%3A57.001Z&...'
... )
>>> json_response = response.json()
>>> print(json_response)

How I can to automatize my requests to carve out all data in requested period? (moreDataAvailable = False)
Is it possible to connect all downloaded JSONs, for example, in a one file to export it in a data warehouse?

Body:
You can just write a loop for this.

import time
timeout = time.time() + 60*5   # 5 minutes from now
while True:
    sendRequest()
    if time.time() > timeout:
        break
    time.sleep(60)   # Delays for 60 seconds. You can also use a float value.

def sendRequest():
  import requests
  response = requests.get(
    'https://api.blablabla.com/event/eventstatuses?
      requestId=1234&datetype=received&starttime=2020-02-
       10T00%3A00%3A57.001Z&...'
   )
  json_response = response.json()
  print(json_response)


问:
Issue using node-sass after updating NodeJS
I get an issue using node-sass after updating my NodeJS version.

Issue :

```<code>(node:472) fs: re-evaluating native module sources is not supported. If you are using the graceful-fs module, please update it to a more recent version.
C:\aglqng\src\main\webapp\node_modules\node-sass\lib\index.js:15
    throw new Error(errors.missingBinary());
    ^

Error: Missing binding C:\aglqng\src\main\webapp\node_modules\node-sass\vendor\win32-x64-48\binding.node
Node Sass could not find a binding for your current environment: Windows 64-bit with Node.js 6.x

Found bindings for the following environments:
  - Windows 64-bit with Node 0.12.x

This usually happens because your environment has changed since running `npm install`.
Run `npm rebuild node-sass` to build the binding for your current environment.
    at Object.<anonymous> (C:\aglqng\src\main\webapp\node_modules\node-sass\lib\index.js:15:11)
    at Module._compile (module.js:541:32)
    at Object.Module._extensions..js (module.js:550:10)
    at Module.load (module.js:458:32)
    at tryModuleLoad (module.js:417:12)
    at Function.Module._load (module.js:409:3)
    at Module.require (module.js:468:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (C:\aglqng\src\main\webapp\node_modules\gulp-sass\index.js:187:21)
    at Module._compile (module.js:541:32)
</code>```

Versions :

```<code>node-sass 3.8.0 (Wrapper) [JavaScript]
libsass 3.3.6 (Sass Compiler) [C/C++]
nodejs v6.3.1
</code>```

Platform : Windows 10 x64

I tried this and it doesn't work :

1)

```<code>node rebuild node-sass
</code>```

2)

```<code>npm uninstall node-sass
npm i node-sass
</code>```

答:
Instead of deleting node-Modules, running below helps:

```<code>cd <Your project path>
node node_modules/node-sass/scripts/install.js
</code>```

Body:
I get an issue using node-sass after updating my NodeJS version.

Issue :

(node:472) fs: re-evaluating native module sources is not supported. If you are using the graceful-fs module, please update it to a more recent version.
C:\aglqng\src\main\webapp\node_modules\node-sass\lib\index.js:15
    throw new Error(errors.missingBinary());
    ^

Error: Missing binding C:\aglqng\src\main\webapp\node_modules\node-sass\vendor\win32-x64-48\binding.node
Node Sass could not find a binding for your current environment: Windows 64-bit with Node.js 6.x

Found bindings for the following environments:
  - Windows 64-bit with Node 0.12.x

This usually happens because your environment has changed since running `npm install`.
Run `npm rebuild node-sass` to build the binding for your current environment.
    at Object.<anonymous> (C:\aglqng\src\main\webapp\node_modules\node-sass\lib\index.js:15:11)
    at Module._compile (module.js:541:32)
    at Object.Module._extensions..js (module.js:550:10)
    at Module.load (module.js:458:32)
    at tryModuleLoad (module.js:417:12)
    at Function.Module._load (module.js:409:3)
    at Module.require (module.js:468:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (C:\aglqng\src\main\webapp\node_modules\gulp-sass\index.js:187:21)
    at Module._compile (module.js:541:32)

Versions :

node-sass 3.8.0 (Wrapper) [JavaScript]
libsass 3.3.6 (Sass Compiler) [C/C++]
nodejs v6.3.1

Platform : Windows 10 x64

I tried this and it doesn't work :

1)

node rebuild node-sass

2)

npm uninstall node-sass
npm i node-sass

Body:
Instead of deleting node-Modules, running below helps:

cd <Your project path>
node node_modules/node-sass/scripts/install.js


问:
kafka connect transformations ordering guarantees
We are planning to use the JMS Source Connector to stream data into our Kafka cluster.
The data from ActiveMQ is in XML format. The JMS Source Connector uses the internal messageID (Message.getJMSMessageID()) as key.

The field that serves as the key - on the Kafka topic that the Connector streams to - needs to be retrieved from within the (XML) payload.

To achieve this a few steps are necessary in the Connector.

To transform the XML to the internal Kafka Connect Struct we use a custom transformation plugin (https://github.com/jcustenborder/kafka-connect-transform-xml)

Then the ValueToKey and ExtractField transformers set the key that was part of the payload.

Now this key-value pair is ready to be sent to our Kafka topic.

We are dealing with financial transactions and need to guarantee the order of the messages.
We have high throughput, and from what I understand, configuring tasks.max allows parallelism by distributing tasks among the Kafka Connect Workers.

First question: How does parallelism work in combination with single message transformers? Do the '(Source)Connector - Transformer - Converter' form a pipeline that is together distributed by setting tasks.max, or does the tasks.max setting somehow only apply to the Connector?

The latter seems a bit odd, so assuming the former is correct I have another doubt.

Our Kafka topic key - that will guarantee the order on the Kafka topic - is determined within the Connector's tasks. Choosing tasks.max > 1 the incoming messages are distributed among the running tasks.

Being distributed among multiple tasks, two (or more) messages (containing the same key within the payload) arrive in a certain order from ActiveMQ and can be sent to different Kafka Connect tasks.

Theoretically the order could be reversed when finally streaming into the Kafka topic (on the same partition, as they now have the same key).

Am I right reasoning this way and is there are way to circumvent this? Or is an ordering guarantee only possible in this use-case using one task only.

答:
does the tasks.max setting somehow only apply to the Connector?

This

Our Kafka topic key - that will guarantee the order on the Kafka topic

No it doesn't. It only guarantees partitioning, and that's it

is an ordering guarantee only possible in this use-case using one task only.

It depends on the source. I don't know AMQ, but if reading a message removes it from the queue, there's no chance that multiple tasks would get the message


答:
You would write something along the lines of

select t1.id, name, place, text from table 1 as t1

join table 2 as t2 on t2.id = t1.id
group by t1.id

Title: Inner Join with similar IDs


问:
How to select two attributes from the same node with one expression in XPath?
For example:

```<code>//person[@id='abc123']/@haircolor|/@weight"
</code>```

PS. there are lots of "person" records

答:
If you are trying to get the values of the specified attributes I would suggest introducing a variable for the requested person.

```<code><xsl:variable name="person" select="//person[@id = 'abc123']" />
</code>```

After that you can get any attribute from the requested person by using the specified variable.

```<code><xsl:value-of select="$person/@haircolor" />
<xsl:value-of select="$person/@weight" />
</code>```

Body:
For example:

//person[@id='abc123']/@haircolor|/@weight"

PS. there are lots of "person" records

Body:
If you are trying to get the values of the specified attributes I would suggest introducing a variable for the requested person.

<xsl:variable name="person" select="//person[@id = 'abc123']" />

After that you can get any attribute from the requested person by using the specified variable.

<xsl:value-of select="$person/@haircolor" />
<xsl:value-of select="$person/@weight" />


问:
Could not find a base address that matches scheme net.tcp for the endpoint with binding NetTcpBinding. Base address schemes are [http]
I have this configuration for my WCF service which runs on IIS Express port number 50187. The service is hosted on IIS Express of Visual Studio 2017:

```<code><system.serviceModel>
    <bindings>
      <basicHttpBinding>
        <binding name="QCConsumerBinding" closeTimeout="00:10:00" openTimeout="00:10:00" receiveTimeout="00:10:00" sendTimeout="00:10:00" allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" maxBufferSize="50000000" maxBufferPoolSize="5242880" maxReceivedMessageSize="50000000" messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered" useDefaultWebProxy="true">
          <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
          <security mode="None">
            <transport clientCredentialType="None" proxyCredentialType="None" realm="" />
            <message clientCredentialType="UserName" algorithmSuite="Default" />
          </security>
        </binding>
      </basicHttpBinding>
    </bindings>
    <services>
      <service name="QCWCFService.QCService">
        <endpoint address="" binding="basicHttpBinding" bindingConfiguration="QCConsumerBinding" contract="QCWCFService.IQCService" />
      </service>
      <service name="QCWCFService.QCFinalService">
        <endpoint address="" binding="basicHttpBinding" bindingConfiguration="QCConsumerBinding" contract="QCWCFService.IQCFinalService" />
      </service>

      <service name="QCWCFService.CalibrationService">
        <endpoint address="service" binding="netTcpBinding" contract="QCWCFService.ICalibrationService" />
        <endpoint address="" binding="wsDualHttpBinding" contract="QCWCFService.ICalibrationService" />
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
        <host>
          <baseAddresses>
            <add baseAddress="net.tcp://localhost:8080/CalibrationService" />
            <add baseAddress="http://localhost:8081/CalibrationService" />
          </baseAddresses>

        </host>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <!-- To avoid disclosing metadata information, set the values below to false before deployment -->
          <serviceMetadata httpGetEnabled="true" />
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="true" />
          <dataContractSerializer maxItemsInObjectGraph="2147483647" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <protocolMapping>
      <add scheme="http" binding="wsDualHttpBinding" />
    </protocolMapping>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
</code>```

But when I try to run the service it gives this exception:

```<code>System.InvalidOperationException: Could not find a base address that matches scheme net.tcp for the endpoint with binding NetTcpBinding. Registered base address schemes are [http].
</code>```

While I have another application with the same configuration for Dual Http Binding which works perfectly

答:
By default, The IIS express doesn’t support Net.tcp protocol.
The service endpoint with Nettcpbinding requires a base address based on NetTcp protocol.

```<code><endpoint address="service" binding="netTcpBinding" contract="QCWCFService.ICalibrationService" />
</code>```

Although we provide a Nettcp base address by using the Host Section, It won’t work. This is due to the fact IIS express use self-configuration to provide a base address to run the current project. The configuration of IIS express usually located in the .vs folder of the current Solution, called applicationhost.config

If we run this project in a console application with this configuration, it will work. Thereby we should provide one base address with Nettcp protocol. This can be completed in IIS.

1. Enable windows feature for net.tcp protocol.

2. Add Net.tcp support on the website.

3. Add net.tcp protocol in site binding module.

Please refer to the below for details of adding net.tcp protocol to a website.

WCF ContractFilter Mismatch when enabling Reliable Session

Feel free to let me know if the problem still exists.

Body:
I have this configuration for my WCF service which runs on IIS Express port number 50187. The service is hosted on IIS Express of Visual Studio 2017:

<system.serviceModel>
    <bindings>
      <basicHttpBinding>
        <binding name="QCConsumerBinding" closeTimeout="00:10:00" openTimeout="00:10:00" receiveTimeout="00:10:00" sendTimeout="00:10:00" allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" maxBufferSize="50000000" maxBufferPoolSize="5242880" maxReceivedMessageSize="50000000" messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered" useDefaultWebProxy="true">
          <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
          <security mode="None">
            <transport clientCredentialType="None" proxyCredentialType="None" realm="" />
            <message clientCredentialType="UserName" algorithmSuite="Default" />
          </security>
        </binding>
      </basicHttpBinding>
    </bindings>
    <services>
      <service name="QCWCFService.QCService">
        <endpoint address="" binding="basicHttpBinding" bindingConfiguration="QCConsumerBinding" contract="QCWCFService.IQCService" />
      </service>
      <service name="QCWCFService.QCFinalService">
        <endpoint address="" binding="basicHttpBinding" bindingConfiguration="QCConsumerBinding" contract="QCWCFService.IQCFinalService" />
      </service>

      <service name="QCWCFService.CalibrationService">
        <endpoint address="service" binding="netTcpBinding" contract="QCWCFService.ICalibrationService" />
        <endpoint address="" binding="wsDualHttpBinding" contract="QCWCFService.ICalibrationService" />
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
        <host>
          <baseAddresses>
            <add baseAddress="net.tcp://localhost:8080/CalibrationService" />
            <add baseAddress="http://localhost:8081/CalibrationService" />
          </baseAddresses>

        </host>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior>

          <serviceMetadata httpGetEnabled="true" />

          <serviceDebug includeExceptionDetailInFaults="true" />
          <dataContractSerializer maxItemsInObjectGraph="2147483647" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <protocolMapping>
      <add scheme="http" binding="wsDualHttpBinding" />
    </protocolMapping>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
  </system.serviceModel>

But when I try to run the service it gives this exception:

System.InvalidOperationException: Could not find a base address that matches scheme net.tcp for the endpoint with binding NetTcpBinding. Registered base address schemes are [http].

While I have another application with the same configuration for Dual Http Binding which works perfectly

Body:
By default, The IIS express doesn’t support Net.tcp protocol.
The service endpoint with Nettcpbinding requires a base address based on NetTcp protocol.

<endpoint address="service" binding="netTcpBinding" contract="QCWCFService.ICalibrationService" />

Although we provide a Nettcp base address by using the Host Section, It won’t work. This is due to the fact IIS express use self-configuration to provide a base address to run the current project. The configuration of IIS express usually located in the .vs folder of the current Solution, called applicationhost.config

If we run this project in a console application with this configuration, it will work. Thereby we should provide one base address with Nettcp protocol. This can be completed in IIS.

1. Enable windows feature for net.tcp protocol.

2. Add Net.tcp support on the website.

3. Add net.tcp protocol in site binding module.

Please refer to the below for details of adding net.tcp protocol to a website.

WCF ContractFilter Mismatch when enabling Reliable Session

Feel free to let me know if the problem still exists.


问:
GIT: Move changes from one branch to other
I have 2 branches A and B.
I made some changes to A and committed them.
I then made more changes to A (by mistake).
I pushed them to B and committed them. </p>

<p>But now  I see changes from A (old) and B (new) being committed. How do I revert this? </p>

答:
If you have pushed commits, that means the remote branch is impacted (not just your local branch)

You will need to cherry-pick the commit from B to A (assuming only one commit was done on B by mistake):

```<code>git switch A
git cherry-pick B
git switch B
git reset --hard B~
git push --force
</code>```

That would override the B history, which can be problematic if several collaborators are working from the remote repo.

Another option is to revert B HEAD, to add an additional commit which cancels the content of the last one.

```<code>git switch B
git revert @
git push
</code>```

No --force needed there.

Body:
I have 2 branches A and B.
I made some changes to A and committed them.
I then made more changes to A (by mistake).
I pushed them to B and committed them.

But now  I see changes from A (old) and B (new) being committed. How do I revert this?

Body:
If you have pushed commits, that means the remote branch is impacted (not just your local branch)

You will need to cherry-pick the commit from B to A (assuming only one commit was done on B by mistake):

git switch A
git cherry-pick B
git switch B
git reset --hard B~
git push --force

That would override the B history, which can be problematic if several collaborators are working from the remote repo.

Another option is to revert B HEAD, to add an additional commit which cancels the content of the last one.

git switch B
git revert @
git push

No --force needed there.


问:
How would I add a new ViewController if and only if the screen is rotated into landscape mode in swift
I am starting on first project in swift and I need to add a new ViewController when the screen is rotated in landscape mode. And if rotated back to portrait mode it will return to original screen. I am a  beginner in swift so please make explanation as clear as possible. Thank you in advance!</p>

答:
Try this

First ViewController

```<code>class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
    super.viewWillTransition(to: size, with: coordinator)
    if UIDevice.current.orientation.isLandscape {
        print("Landscape")
        let vc2 = self.storyboard?.instantiateViewController(withIdentifier: "ViewController2")
        self.navigationController?.pushViewController(vc2!, animated: false)
    } else {
        print("Portrait")
    }
}
override func viewDidAppear(_ animated: Bool) {
    let value = UIInterfaceOrientation.portrait.rawValue
    UIDevice.current.setValue(value, forKey: "orientation")
}
override func viewDidLoad() {
    super.viewDidLoad()
}
}
</code>```

Second ViewController

```<code>class ViewController2: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
}

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
    super.viewWillTransition(to: size, with: coordinator)
    if UIDevice.current.orientation.isLandscape {
        print("Landscape")
    } else {
        print("Portrait")
        self.navigationController?.popViewController(animated: false)
    }
}
}
</code>```

You will detect orientation change in viewWillTransition method, so you need to override it

Body:
Try this

First ViewController

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
    super.viewWillTransition(to: size, with: coordinator)
    if UIDevice.current.orientation.isLandscape {
        print("Landscape")
        let vc2 = self.storyboard?.instantiateViewController(withIdentifier: "ViewController2")
        self.navigationController?.pushViewController(vc2!, animated: false)
    } else {
        print("Portrait")
    }
}
override func viewDidAppear(_ animated: Bool) {
    let value = UIInterfaceOrientation.portrait.rawValue
    UIDevice.current.setValue(value, forKey: "orientation")
}
override func viewDidLoad() {
    super.viewDidLoad()
}
}

Second ViewController

class ViewController2: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
}

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
    super.viewWillTransition(to: size, with: coordinator)
    if UIDevice.current.orientation.isLandscape {
        print("Landscape")
    } else {
        print("Portrait")
        self.navigationController?.popViewController(animated: false)
    }
}
}

You will detect orientation change in viewWillTransition method, so you need to override it


问:
Error : in my query i am using multiple variables in c#
i am not getting what is the issue in the query probably i am not following the correct way to put the string and char sign , i am inserting the data in c# to local host with where clause please check the query and Error i am getting

Here is the query

```<code>String insertQuery = "insert into exam_add (id,session_id,Title,From_date,To_date,class_id,is_Post,is_Lock) select '"+id+ ",s.session,'" + title.Text+",'"+ from.Value.Date.ToString("yyyy-MM-dd")+",'"+to.Value.Date.ToString("yyyy-MM-dd")+ ", c.class_name,'"+x+",'"+x+" from year_session s, classes c where s.id = '1' and c.id='" + cls + "'";
</code>```

Exception image
here the image for exception i am getting after run this query

答: On your ...'"+x+"... you forgot to close the single quotes. You open them but you never close them after you add the X variable to your query. All SQL is seeing is "'0," which is invalid syntax.</p>

Body:
i am not getting what is the issue in the query probably i am not following the correct way to put the string and char sign , i am inserting the data in c# to local host with where clause please check the query and Error i am getting

Here is the query

String insertQuery = "insert into exam_add (id,session_id,Title,From_date,To_date,class_id,is_Post,is_Lock) select '"+id+ ",s.session,'" + title.Text+",'"+ from.Value.Date.ToString("yyyy-MM-dd")+",'"+to.Value.Date.ToString("yyyy-MM-dd")+ ", c.class_name,'"+x+",'"+x+" from year_session s, classes c where s.id = '1' and c.id='" + cls + "'";

Exception image
here the image for exception i am getting after run this query


问:
Flask-wtforms Redirect on Form Submission and Pass Variables
I am struggling to figure out why I am unable to pass variables to my redirected url. I have attempted the suggestions in the following questions, but for some reason they are not working.

redirect while passing arguments

How can I pass arguments into redirect(url_for()) of Flask?

The only thing I can think of is that it is because I am using flask-wtforms to validate the form before the redirect. I haven't seen much in way of answers/suggestions for this scenario. So here I am.

```<code>    @app.route('/quiz/', methods=['GET', 'POST'])
    def quiz():
        form = Quiz()
        if form.validate_on_submit():
            q1_answer = 'North'
            return redirect(url_for('result', q1_answer=q1_answer))
        return render_template('quiz.html', form=form)

    @app.route('/result/', methods=['GET', 'POST'])
    def result():
        q1_correct_answer = request.args.get('q1_answer')
        return render_template('result.html', q1_correct_answer=q1_correct_answer)
</code>```

The redirect works the way it should. The 'result' url and its corresponding template are rendered. I just can't get the variable (q1_answer) to pass. My template always returns a value of None. Any help would be greatly appreciated.

答:
I think you use it</p>
```<code>@app.route('/quiz/', methods=['GET', 'POST'])

def quiz():

    form = Quiz()
    if request.method == "POST" and form.validate_on_submit():
        q1_answer = 'North'
        return redirect(url_for('result', q1_answer=q1_answer))
    return render_template('quiz.html', form=form)

@app.route('/result/', methods=['GET', 'POST'])

def result(q1_answer):

    return render_template('result.html', q1_correct_answer=q1_answer)
</code>```

Body:
I am struggling to figure out why I am unable to pass variables to my redirected url. I have attempted the suggestions in the following questions, but for some reason they are not working.

redirect while passing arguments

How can I pass arguments into redirect(url_for()) of Flask?

The only thing I can think of is that it is because I am using flask-wtforms to validate the form before the redirect. I haven't seen much in way of answers/suggestions for this scenario. So here I am.

    @app.route('/quiz/', methods=['GET', 'POST'])
    def quiz():
        form = Quiz()
        if form.validate_on_submit():
            q1_answer = 'North'
            return redirect(url_for('result', q1_answer=q1_answer))
        return render_template('quiz.html', form=form)

    @app.route('/result/', methods=['GET', 'POST'])
    def result():
        q1_correct_answer = request.args.get('q1_answer')
        return render_template('result.html', q1_correct_answer=q1_correct_answer)

The redirect works the way it should. The 'result' url and its corresponding template are rendered. I just can't get the variable (q1_answer) to pass. My template always returns a value of None. Any help would be greatly appreciated.

Body:
I think you use it

@app.route('/quiz/', methods=['GET', 'POST'])

def quiz():

    form = Quiz()
    if request.method == "POST" and form.validate_on_submit():
        q1_answer = 'North'
        return redirect(url_for('result', q1_answer=q1_answer))
    return render_template('quiz.html', form=form)

@app.route('/result/', methods=['GET', 'POST'])

def result(q1_answer):

    return render_template('result.html', q1_correct_answer=q1_answer)


问:
How to sum float numbers in the format hours and minutes?
How to sum float numbers in the format hours and minutes?

Those. if  calculate two such numbers 0.35+3.45 then it should be = 4.20, not 3.80

var arr = [0.15, 0.2, 3.45, 0.4, 2, 0.3, 5.2, 1, 1.4, 1.1, 2.4, 1, 3.4]

var sum = 0.0;

arr.forEach(function(item) {
  console.log(sum);
  sum += parseFloat(item);
});```
</div>
</div>
</p>

<p>The result should be like this:</p>

```0
0.15
0.35
4.20
5.0
7.0
7.30
12.50
13.50
15.30
16.40
19.20
20.20
```

答:
// We got this after simple addition
// Now we want to change it into 4.2
sample = 3.8

// Now here are the minutes that the float currently shows
minutes = (sample % 1) * 100

// And the hours
hours = Math.floor(sample)

// Here are the number of hours that can be reduced from minutes
AddHours = Math.floor(minutes / 60)

// Adding them to the hours count
hours += AddHours

// Reducing mintues
minutes %= 60

// Finally formatting hour and minutes into your format
final = hours + (minutes / 100.0)
console.log(final)```

You can use this logic after doing simple arithmetic addition, this will convert the sum into time format

Body:
How to sum float numbers in the format hours and minutes?

Those. if  calculate two such numbers 0.35+3.45 then it should be = 4.20, not 3.80

var arr = [0.15, 0.2, 3.45, 0.4, 2, 0.3, 5.2, 1, 1.4, 1.1, 2.4, 1, 3.4]

var sum = 0.0;

arr.forEach(function(item) {
  console.log(sum);
  sum += parseFloat(item);
});

The result should be like this:

0
0.15
0.35
4.20
5.0
7.0
7.30
12.50
13.50
15.30
16.40
19.20
20.20

Body:
// We got this after simple addition
// Now we want to change it into 4.2
sample = 3.8

// Now here are the minutes that the float currently shows
minutes = (sample % 1) * 100

// And the hours
hours = Math.floor(sample)

// Here are the number of hours that can be reduced from minutes
AddHours = Math.floor(minutes / 60)

// Adding them to the hours count
hours += AddHours

// Reducing mintues
minutes %= 60

// Finally formatting hour and minutes into your format
final = hours + (minutes / 100.0)
console.log(final)

You can use this logic after doing simple arithmetic addition, this will convert the sum into time format


问:
Deleting Rows via For-Loop (within a multi Area Range)
Usually, I would delete Rows using a For-Loop with row-numbers by working backward, which would look similar to this:

```<code>For rowIndex = 10 to 1 Step (-1)
    'delete Row with current row index
    next rowIndex
</code>```

How do I do this while cycling through a specified cell range? The following code obviously won't work (it will skip a cell/row in the next iteration when the delete command has been executed, check here or here):

```<code>Dim someRange as Range
'Note: someRange might be a multi area range (multiple unadjoined cells) within one sheet
Dim singleCell as Range
For each singleCell In SomeRange.Cells
    'check for some condition e.g. based (but not limited to) the singleCell's value
    If condition = True then
        singleCell.EntireRow.Delete
        'Note: the deletion has to be done before the next loop-iteration starts
               'Unfortunately, this makes solutions like working with Union unfeasible
        End If
    Next singleCell
</code>```

Has anyone an idea how to make the second code block work without switching to a "Backward-Row-Number-Loop" (see first code block)? Is there a way to somehow "reset" the singleCell-pointer/counter to a new value so the loop does not skip the next cell/row? Or any other alternative (like make the Range-Loop work backward etc.)? Any hint for a solution would be appreciated, a code snipped as well but if necessary I can do without.

I have to avoid adding the undesired row into an array (range etc.) and deleting the whole array after the loop is done. Unfortunately as a condition for the implementation the row has to be deleted before the next cell is evaluated.

Essentially there might be a case where two cell which rows ought to be deleted will be in the same row. In this case the 2nd cell will be deleted before it's even checked, that's desired behaviour. The solution does not have to but should be expandable to include this case.

EDIT: Another solution I'm thinking about is reversing the range before doing the For-Loop (see here), so far I haven't tried it out though.

答:
To strictly follow your stated desire to to top down deletion, and to allow for possible multiple hits on one row, and to allow for non-contiguous ranges,  I'd suggest not using a for loop, but rather a Do Loop over the Areas and Rows in your someRange, and a For loop over each row (terminate the For when you get a hit).  Something like

```<code>Sub Demo()
    Dim rng As Range, cl As Range
    Dim someRange As Range
    Dim AreaRange As Range
    Dim DeletedRow As Boolean
    Dim areaNum As Long
    Dim i As Long

    ' Set your test range, eg
    Set someRange = [A1:F3,A8:F10,A16:F19]
    areaNum = 1
    ' Set first row to test
    Do
        ' Track discontiguous range areas
        Set AreaRange = someRange.Areas(areaNum)
        Set rng = someRange.Areas(areaNum).Rows(1)
        Do Until rng Is Nothing
            DeletedRow = False
            For Each cl In rng.Cells
                ' test condition, eg empty
                If IsEmpty(cl) Then
                    ' update rng to next row.  do this before the Delete
                    Set rng = Application.Intersect(someRange, rng.Offset(1, 0))
                    ' delete row
                    cl.EntireRow.Delete
                    DeletedRow = True
                    ' stop looping the row
                    Exit For
                End If
            Next
            ' if not already updated...
            If Not DeletedRow Then
                Set rng = Application.Intersect(someRange, rng.Offset(1, 0))
            End If
        Loop

        ' not all rows in area have been deleted, increment AreaNum
        ' AreaRange end up in a state where it's not Nothing, and isn't valid
        On Error Resume Next
            i = 0
            i = AreaRange.Count
        On Error GoTo 0
        If i > 0 Then
            areaNum = areaNum + 1
        End If
    Loop Until areaNum > someRange.Areas.Count
End Sub

</code>```

Note that this will be quite inefficient, but does meet your stated aims

Body:
Usually, I would delete Rows using a For-Loop with row-numbers by working backward, which would look similar to this:

For rowIndex = 10 to 1 Step (-1)
    'delete Row with current row index
    next rowIndex

How do I do this while cycling through a specified cell range? The following code obviously won't work (it will skip a cell/row in the next iteration when the delete command has been executed, check here or here):

Dim someRange as Range
'Note: someRange might be a multi area range (multiple unadjoined cells) within one sheet
Dim singleCell as Range
For each singleCell In SomeRange.Cells
    'check for some condition e.g. based (but not limited to) the singleCell's value
    If condition = True then
        singleCell.EntireRow.Delete
        'Note: the deletion has to be done before the next loop-iteration starts
               'Unfortunately, this makes solutions like working with Union unfeasible
        End If
    Next singleCell

Has anyone an idea how to make the second code block work without switching to a "Backward-Row-Number-Loop" (see first code block)? Is there a way to somehow "reset" the singleCell-pointer/counter to a new value so the loop does not skip the next cell/row? Or any other alternative (like make the Range-Loop work backward etc.)? Any hint for a solution would be appreciated, a code snipped as well but if necessary I can do without.

I have to avoid adding the undesired row into an array (range etc.) and deleting the whole array after the loop is done. Unfortunately as a condition for the implementation the row has to be deleted before the next cell is evaluated.

Essentially there might be a case where two cell which rows ought to be deleted will be in the same row. In this case the 2nd cell will be deleted before it's even checked, that's desired behaviour. The solution does not have to but should be expandable to include this case.

EDIT: Another solution I'm thinking about is reversing the range before doing the For-Loop (see here), so far I haven't tried it out though.

Body:
To strictly follow your stated desire to to top down deletion, and to allow for possible multiple hits on one row, and to allow for non-contiguous ranges,  I'd suggest not using a for loop, but rather a Do Loop over the Areas and Rows in your someRange, and a For loop over each row (terminate the For when you get a hit).  Something like

Sub Demo()
    Dim rng As Range, cl As Range
    Dim someRange As Range
    Dim AreaRange As Range
    Dim DeletedRow As Boolean
    Dim areaNum As Long
    Dim i As Long

    ' Set your test range, eg
    Set someRange = [A1:F3,A8:F10,A16:F19]
    areaNum = 1
    ' Set first row to test
    Do
        ' Track discontiguous range areas
        Set AreaRange = someRange.Areas(areaNum)
        Set rng = someRange.Areas(areaNum).Rows(1)
        Do Until rng Is Nothing
            DeletedRow = False
            For Each cl In rng.Cells
                ' test condition, eg empty
                If IsEmpty(cl) Then
                    ' update rng to next row.  do this before the Delete
                    Set rng = Application.Intersect(someRange, rng.Offset(1, 0))
                    ' delete row
                    cl.EntireRow.Delete
                    DeletedRow = True
                    ' stop looping the row
                    Exit For
                End If
            Next
            ' if not already updated...
            If Not DeletedRow Then
                Set rng = Application.Intersect(someRange, rng.Offset(1, 0))
            End If
        Loop

        ' not all rows in area have been deleted, increment AreaNum
        ' AreaRange end up in a state where it's not Nothing, and isn't valid
        On Error Resume Next
            i = 0
            i = AreaRange.Count
        On Error GoTo 0
        If i > 0 Then
            areaNum = areaNum + 1
        End If
    Loop Until areaNum > someRange.Areas.Count
End Sub

Note that this will be quite inefficient, but does meet your stated aims


问:
Clean up ugly WYSIWYG HTML code? Python or *nix utility
I'm finally upgrading (rewriting ;) ) my first Django app, but I am migrating all the content.

I foolishly gave users a full WYSIWYG editor for certain tasks, the HTML code produced is of course terribly ugly with more extra tags than content.

Does anyone know of a library or external shell app I could use to clean up the code?

I use tidy sometimes, but as far as I know that doesn't do what I'm asking. I want to simplify all the extra span and other garbage tags. I cleaned the most offensive offending styles with some regex, but I it would take a really long time to do anything more using just regex.

Any ideas?

答:
The standard answer is Beautiful Soup.

"Extra span" and "garbage tags" is something you'll need to define very, very carefully so you can remove the tags without removing content.

I would suggest you do two things.

Fix  your app so that users don't provide HTML under any circumstances.  Django can use RST markup which is much more user-friendly.  http://docs.djangoproject.com/en/1.3/ref/templates/builtins/#django-contrib-markup

Write a Beautiful Soup parser and transform the user's content into RST markup.  Keep the structural elements (headings, lists, etc.) and lose the formatting to the extent possible.


问:
how to make ssh keygen work properly to set ssh keys for cloning and other purposes
In the below code

############-L1 MINGW64 ~
$ which git
/mingw64/bin/git

############-L1 MINGW64 ~
$ git --version
git version 2.22.0.windows.1

############-L1 MINGW64 ~
$ which git -v
GNU which v2.21, Copyright (C) 1999 - 2015 Carlo Wood.
GNU which comes with ABSOLUTELY NO WARRANTY;
This program is free software; your freedom to use, change
and distribute this program is protected by the GPL.

############-L1 MINGW64 ~
$ ssh-keygen -t rsa

############-L1 MINGW64 ~
$
```

which is run in Git Bash v2.22. I am not able to create the SSH key using the above ssh-keygen command. I have made sure I cleared the credentials using credential manager for Git. I have made sure to restart the computer once the installations were done. Any suggestions how can I make this work?
I need this so I can clone something from the local repository in my GitLab account and do other functionalities which require an SSH key.

答:
The full command would be

```<code>ssh-keygen -t rsa -P "" -m PEM
cd
cd .ssh
ls -alrth
</code>```

Check that id_rsa/id_rsa.pub are created.

Body:
In the below code

############-L1 MINGW64 ~
$ which git
/mingw64/bin/git

############-L1 MINGW64 ~
$ git --version
git version 2.22.0.windows.1

############-L1 MINGW64 ~
$ which git -v
GNU which v2.21, Copyright (C) 1999 - 2015 Carlo Wood.
GNU which comes with ABSOLUTELY NO WARRANTY;
This program is free software; your freedom to use, change
and distribute this program is protected by the GPL.

############-L1 MINGW64 ~
$ ssh-keygen -t rsa

############-L1 MINGW64 ~
$

which is run in Git Bash v2.22. I am not able to create the SSH key using the above ssh-keygen command. I have made sure I cleared the credentials using credential manager for Git. I have made sure to restart the computer once the installations were done. Any suggestions how can I make this work?
I need this so I can clone something from the local repository in my GitLab account and do other functionalities which require an SSH key.

Body:
The full command would be

ssh-keygen -t rsa -P "" -m PEM
cd
cd .ssh
ls -alrth

Check that id_rsa/id_rsa.pub are created.


问:
Validating a textbox entry if duplicate display error message microsoft access
i have searched around and cant find an answer, so i am using Microsoft Access Office 2019 and cant seem to validate my textbox for a duplicate entry. The user will add a record and enter a short text primary key (which in this case is the new employee's ID) Field - [EMPID] in the [EMPDETAILS] table. The below code has worked for validating my Autonumber primary key but doesnt seem to work for a custom short text primary key and i am getting this error

"The expression you entered as a query parameter produced this error :
  'VS123'

<= this is the Employee ID which is a custom short text primary key :

```<code>Private Sub unqidd_BeforeUpdate(Cancel As Integer)

On Error GoTo Err_Handler

Dim strMessage As String
'PartNum is the name of a textbox that contains the primary key, the rest are text to display.
strMessage = "Employee ID" & Me!unqidd & " already exists."

' confirm that part number doesn't already exist.
If (DLookup("[empid]", "[empdetails]", "[empID] = " & Forms![driverdetails]![unqidd])) Then
    MsgBox strMessage, vbInformation, "Invalid Operation"
    Cancel = True
End If
Exit_Here:
Exit Sub

Err_Handler:
MsgBox Err.Description
Resume Exit_Here

End Sub
</code>```

答:
Since you are trying to add a string into [empID] I am going to assume it is a string field, in which case you need to include quotes:

```<code>If (DLookup("[empid]", "[empdetails]", "[empID] = '" & Forms![driverdetails]![unqidd] & "'")) Then
</code>```

Body:
i have searched around and cant find an answer, so i am using Microsoft Access Office 2019 and cant seem to validate my textbox for a duplicate entry. The user will add a record and enter a short text primary key (which in this case is the new employee's ID) Field - [EMPID] in the [EMPDETAILS] table. The below code has worked for validating my Autonumber primary key but doesnt seem to work for a custom short text primary key and i am getting this error

"The expression you entered as a query parameter produced this error :
  'VS123'

<= this is the Employee ID which is a custom short text primary key :

Private Sub unqidd_BeforeUpdate(Cancel As Integer)

On Error GoTo Err_Handler

Dim strMessage As String
'PartNum is the name of a textbox that contains the primary key, the rest are text to display.
strMessage = "Employee ID" & Me!unqidd & " already exists."

' confirm that part number doesn't already exist.
If (DLookup("[empid]", "[empdetails]", "[empID] = " & Forms![driverdetails]![unqidd])) Then
    MsgBox strMessage, vbInformation, "Invalid Operation"
    Cancel = True
End If
Exit_Here:
Exit Sub

Err_Handler:
MsgBox Err.Description
Resume Exit_Here

End Sub

Body:
Since you are trying to add a string into [empID] I am going to assume it is a string field, in which case you need to include quotes:

If (DLookup("[empid]", "[empdetails]", "[empID] = '" & Forms![driverdetails]![unqidd] & "'")) Then


问:
MySQL query to find all URLs that are substring of other URLs
I have a MySQL field URL of type Varchar.

Is it possible with one MySQL query to return all records where the string value URL is a substring of another record URL value, and display both the substrings and full strings records?

答:
You join the table with itself. Something like:

```
SELECT t1.URL, t2.URL AS SUBURL
FROM mytable t1, mytable t2
WHERE INSTR(t1.URL, t2.URL) > 0
AND t1.ID < t2.ID
```

Note that the query has N^2 complexity and string matching is slow. Expect terrible performance on large tables.

Body:
You join the table with itself. Something like:

SELECT t1.URL, t2.URL AS SUBURL
FROM mytable t1, mytable t2
WHERE INSTR(t1.URL, t2.URL) > 0
AND t1.ID < t2.ID

Note that the query has N^2 complexity and string matching is slow. Expect terrible performance on large tables.