问:
Mongo .updateMany() returns TypeError: Property 'updateMany' of object is not a function
I have the following documents in a users collection:

Document 1:

```<code>{
    "_id": {
        "$oid": "5934fd84d6ba4c241259bed1"
    },
    "first_name": "Joe",
    "last_name": "Smith",
    "username": "jsmith",
    "email": "jsmith@gmail.com",
    "password": "$2a$10$eyIbahYKETTtP.i6WlyYd.QeqGNWswW1y/H/aOWw8euFDmWz.wwH2",
    "gender": "male",
    "messages": [
        {
            "$oid": "5937a1118ca79a02a6d10b11"
        }
    ],
    "__v": 16
}
</code>```

Document 2:

```<code>{
    "_id": {
        "$oid": "5934fe100b557624207db665"
    },
    "first_name": "Sarah",
    "last_name": "Smith",
    "username": "tsmith",
    "email": "tsmith@gmail.com",
    "password": "$2a$10$hfPXLRU4wu2i0/HiVCXO5e2k4ORTsJGZhJ63OpU9OsfTz7JJYRnDS",
    "gender": "female",
    "messages": [
        {
            "$oid": "5937a1118ca79a02a6d10b11"
        }
    ],
    "__v": 25
}
</code>```

How do I iterate through the entire collection, and delete the messages array (keep the messages key, but with an empty array)?  This collection only has 2 documents, but I want to do it with as many documents as needed.

The resulting document should look like this:

```<code>{
    "_id": {
        "$oid": "5934fd84d6ba4c241259bed1"
    },
    "first_name": "Joe",
    "last_name": "Smith",
    "username": "jsmith",
    "email": "jsmith@gmail.com",
    "password": "$2a$10$eyIbahYKETTtP.i6WlyYd.QeqGNWswW1y/H/aOWw8euFDmWz.wwH2",
    "gender": "male",
    "messages": [],
    "__v": 16
}
</code>```

I tried doing this with db.users.updateMany({}, { $set: { "messages": []}}), but I'm getting an error: E QUERY TypeError: Property 'updateMany' of object my_match.users is not a function.  I'm not passing in a <filter> parameter to updateMany() because I want to update all documents in the collection per the mongoDB docs: "Specify an empty document { } to update all documents in the collection."

I can do this one-by-one using db.users.update({first_name: "Joe"}, { $set: { "messages": []}}), but this is inefficient, and not really what I want.

答:
What is the mongo version you are using?
Since "UpdateMany" has been introduced on 3.2 , make sure you are using at least that version.</p>

Body:
I have the following documents in a users collection:

Document 1:

{
    "_id": {
        "$oid": "5934fd84d6ba4c241259bed1"
    },
    "first_name": "Joe",
    "last_name": "Smith",
    "username": "jsmith",
    "email": "jsmith@gmail.com",
    "password": "$2a$10$eyIbahYKETTtP.i6WlyYd.QeqGNWswW1y/H/aOWw8euFDmWz.wwH2",
    "gender": "male",
    "messages": [
        {
            "$oid": "5937a1118ca79a02a6d10b11"
        }
    ],
    "__v": 16
}

Document 2:

{
    "_id": {
        "$oid": "5934fe100b557624207db665"
    },
    "first_name": "Sarah",
    "last_name": "Smith",
    "username": "tsmith",
    "email": "tsmith@gmail.com",
    "password": "$2a$10$hfPXLRU4wu2i0/HiVCXO5e2k4ORTsJGZhJ63OpU9OsfTz7JJYRnDS",
    "gender": "female",
    "messages": [
        {
            "$oid": "5937a1118ca79a02a6d10b11"
        }
    ],
    "__v": 25
}

How do I iterate through the entire collection, and delete the messages array (keep the messages key, but with an empty array)?  This collection only has 2 documents, but I want to do it with as many documents as needed.

The resulting document should look like this:

{
    "_id": {
        "$oid": "5934fd84d6ba4c241259bed1"
    },
    "first_name": "Joe",
    "last_name": "Smith",
    "username": "jsmith",
    "email": "jsmith@gmail.com",
    "password": "$2a$10$eyIbahYKETTtP.i6WlyYd.QeqGNWswW1y/H/aOWw8euFDmWz.wwH2",
    "gender": "male",
    "messages": [],
    "__v": 16
}

I tried doing this with db.users.updateMany({}, { $set: { "messages": []}}), but I'm getting an error: E QUERY TypeError: Property 'updateMany' of object my_match.users is not a function.  I'm not passing in a <filter> parameter to updateMany() because I want to update all documents in the collection per the mongoDB docs: "Specify an empty document { } to update all documents in the collection."

I can do this one-by-one using db.users.update({first_name: "Joe"}, { $set: { "messages": []}}), but this is inefficient, and not really what I want.


来源: stackexchange

问:
How to return value from a cell same as it is in vba?
How to return value from a cell same as it is in VBA?

For example:

A1 has "0.00000" But when I create a double and store this value in that, it stores as "0" But I want it with the same format.

```<code>Dim i as Double
i = Range("A1").Value
</code>```

Result: i = 0

答:
You are confusing the value of a cell with the textural representation of the value.

If you want the latter then use

```<code>Dim s as String
s = Range("A1").Text
</code>```

But note that a number is simply a number. The quantity of zeros after the decimal separator or the number of zeros before the number does not change the value of that number.

ContentLicense: CC BY-SA 3.0

Body:
How to return value from a cell same as it is in VBA?

For example:

A1 has "0.00000" But when I create a double and store this value in that, it stores as "0" But I want it with the same format.

Dim i as Double
i = Range("A1").Value

Result: i = 0

Body:
You are confusing the value of a cell with the textural representation of the value.

If you want the latter then use

Dim s as String
s = Range("A1").Text

But note that a number is simply a number. The quantity of zeros after the decimal separator or the number of zeros before the number does not change the value of that number.


问:
How to generate simpler xml in c#?
if there any way to generate xml file in c# with form like this:

```<code><data>
<tableName fieldname="value" fieldname2="value2" fieldname3="value3" />
</data>
</code>```

I tried

```<code>System.Data.DataTable datatable = new System.Data.DataTable("tableName");
datatable.Columns.Add("filename", typeof(string));
datatable.Columns.Add("time", typeof(string));
datatable.Columns.Add("message", typeof(string));
.
.
datatable.WriteXml("Raports.xml")
</code>```

and my xml has body like:

```<code><tableName>
<filename>Raport_1201_1</filename>
<time>15:21:11.343</time>
<message>START</message>
</tableName>
</code>```

答:
The answer is, to use XAttributes inside Xelement:

```<code>XElement data = new XElement("data");
data.Add( new XElement("tableName",
new XAttribute("fieldname", "value"),
new XAttribute("fieldname", "value2"),
new XAttribute("fieldname", "value3")
)
);
data.save("some.xml");
</code>```

Thanks for help everyone! ^^

Title: How to generate simpler xml in c#?

Body:
if there any way to generate xml file in c# with form like this:

<data>
<tableName fieldname="value" fieldname2="value2" fieldname3="value3" />
</data>

I tried

System.Data.DataTable datatable = new System.Data.DataTable("tableName");
datatable.Columns.Add("filename", typeof(string));
datatable.Columns.Add("time", typeof(string));
datatable.Columns.Add("message", typeof(string));
.
.
datatable.WriteXml("Raports.xml")

and my xml has body like:

<tableName>
<filename>Raport_1201_1</filename>
<time>15:21:11.343</time>
<message>START</message>
</tableName>

Body:
The answer is, to use XAttributes inside Xelement:

XElement data = new XElement("data");
data.Add( new XElement("tableName",
new XAttribute("fieldname", "value"),
new XAttribute("fieldname", "value2"),
new XAttribute("fieldname", "value3")
)
);
data.save("some.xml");

Thanks for help everyone! ^^


问:
Partitioning in window functions with same value in different chunk of rows
In the picture below you can example data. I would like to get first occurence of batch_start for each batch. As you can see (green highlight) batch 1522049 occurs in 2 chunks, one has 2 rows and second has 1 row.

```<code>SELECT FIRST_VALUE(batch_start) OVER (PARTITION BY batch ORDER BY batch_start)
</code>```

does not solve the problem, since it joins both chunks into one and result is '2013-01-29 10:27:23' for both of them.

Any idea how to distinguish these rows and get batch_start of each chunk of data?

答:
This seems to me a simple gaps-and-islands problem: you just need to calculate a value, which is the same for every subsequent rows for the same batch value, which will be

```<code>row_number() over (order by batch_start) - row_number() over (partition by batch order by batch_start)
</code>```

From this, the solution depends on what do you want to do with these "batch groups". F.ex. here is a variant, which will aggregate them, to find out which is the first batch_start:

```<code>select   batch, min(batch_start)
from     (select *, row_number() over (order by batch_start) -
                    row_number() over (partition by batch order by batch_start) batch_number
          from   batches) b
group by batch, batch_number
</code>```

http://rextester.com/XLX80303

Body:
In the picture below you can example data. I would like to get first occurence of batch_start for each batch. As you can see (green highlight) batch 1522049 occurs in 2 chunks, one has 2 rows and second has 1 row.

SELECT FIRST_VALUE(batch_start) OVER (PARTITION BY batch ORDER BY batch_start)

does not solve the problem, since it joins both chunks into one and result is '2013-01-29 10:27:23' for both of them.

Any idea how to distinguish these rows and get batch_start of each chunk of data?

Body:
This seems to me a simple gaps-and-islands problem: you just need to calculate a value, which is the same for every subsequent rows for the same batch value, which will be

row_number() over (order by batch_start) - row_number() over (partition by batch order by batch_start)

From this, the solution depends on what do you want to do with these "batch groups". F.ex. here is a variant, which will aggregate them, to find out which is the first batch_start:

select   batch, min(batch_start)
from     (select *, row_number() over (order by batch_start) -
                    row_number() over (partition by batch order by batch_start) batch_number
          from   batches) b
group by batch, batch_number

http://rextester.com/XLX80303


问:
How to re render sub component on prop change with redux?
I have a react native app using redux and immutable js. When i dispatch an action from my main screen, it goes through my actions, to my reducer and then back to my container, however, the view doesn't update and componentWillReceieveProps is never called. Furthermore, the main screen is a list whose items are sub components Item. Here's the relevant code for the issue, if you want to see more let me know.

Render the row with the data:

```<code>renderRow(rowData) {
    return (
        <Item item={ rowData } likePostEvent={this.props.likePostEvent} user={ this.props.user } removable={ this.props.connected } />
    )
}
</code>```

The part of Item.js which dispatches an action, and shows the result:

```<code><View style={{flex: 1, justifyContent:'center', alignItems: 'center'}}>
                        <TouchableOpacity onPress={ this.changeStatus.bind(this, "up") }>
                            <Image source={require('../img/up-arrow.png')} style={s.upDownArrow} />
                        </TouchableOpacity>
                        <Text style={[s.cardText,{fontSize:16,padding:2}]}>
                            { this.props.item.starCount }
                        </Text>
                        <TouchableOpacity onPress={ this.changeStatus.bind(this, "down") }>
                            <Image source={require('../img/up-arrow.png')} style={[s.upDownArrow,{transform: [{rotate: '180deg'}]}]} />
                        </TouchableOpacity>
                    </View>
</code>```

The action dispatched goes to firebase, which has an onChange handler that dispatches another action.

The reducer:

```<code>const initialState = Map({
 onlineList: [],
 offlineList: [],
 filteredItems: [],
 connectionChecked: false,
 user: ''
})
...
...
case ITEM_CHANGED:
list = state.get('onlineList')
if(state.get('onlineList').filter((e) => e.id == action.item.id).length > 0){
  let index = state.get('onlineList').findIndex(item => item.id === action.item.id);
  list[index] = action.item
  list = list.sort((a, b) => b.time_posted - a.time_posted)
}
return state.set('onlineList',  list)
            .set('offlineList', list)
</code>```

The container:

```<code>function mapStateToProps(state) {
 return {
    onlineItems: state.items.get('onlineList'),
    offlineItems: state.items.get('offlineList'),
    filteredItems: state.items.get('filteredItems'),
    connectionChecked: state.items.get('connectionChecked'),
    connected: state.items.get('connected'),
    user: state.login.user
  }
}
</code>```

Where I connect the onChange:

```<code>export function getInitialState(closure_list) {
  itemsRef.on('child_removed', (snapshot) => {
    closure_list.removeItem(snapshot.val().id)
  })
  itemsRef.on('child_added', (snapshot) => {
    closure_list.addItem(snapshot.val())
  })

  itemsRef.on('child_changed', (snapshot) => {
    closure_list.itemChanged(snapshot.val())
  })

  connectedRef.on('value', snap => {
    if (snap.val() === true) {
      closure_list.goOnline()
    } else {
      closure_list.goOffline()
    }
  })
  return {
    type: GET_INITIAL_STATE,
    connected: true
  }
}
</code>```

Calling get initial state:

```<code>this.props.getInitialState({
        addItem: this.props.addItem,
        removeItem: this.props.removeItem,
        goOnline: this.props.goOnline,
        goOffline: this.props.goOffline,
        itemChanged: this.props.itemChanged
    })
</code>```

Any suggestions are welcome, thanks so much!

答:
```<code>  import React from 'react';
import ReactDOM from 'react-dom';
import { createStore,combineReducers } from 'redux' //Redux.createStore
import { Provider,connect } from 'react-redux';

//Функція яка змінює store
const hello = (state= {message:'none'}, action) => {
    switch (action.type) {
        case 'HELLO':
            return Object.assign({}, state, {message:"hello world"});
            break
        case  'buy':
            return Object.assign({}, state, {message:"buy"});
            break;
        case 'DELETE':
            return Object.assign({}, state, {message:"none"});
            break;
        default :
            return state;
    }
};

const price = (state= {value:0}, action) => {
    switch (action.type) {
        case 'HELLO':
            return Object.assign({}, state, {value: state.value + 1 });
            break;
        default :
            return Object.assign({}, state, {value:0});
    }
};

const myApp = combineReducers({
    hello,price
});

//створюємо  store
let store = createStore(myApp);

let unsubscribe = store.subscribe(() => console.log(store.getState()))

//VIEW
class App extends React.Component {

    constructor(props) {
        super(props);
    }

    render() {
        return (
            <div>

                <p>value: {this.props.price}</p>

                <a href="#" onClick={this.props.onClick}>click</a><b>{this.props.message}</b>
            </div>
        )
    }
}

//mapStateToProps() для чтения состояния и mapDispatchToProps() для передачи события

const mapStateToProps = (state, ownProps) => {
    return {
        message: state.hello.message,
        price: state.price.value
    }
};
const mapDispatchToProps = (dispatch, ownProps) => {
    return {
            onClick: () => {

                var items= ['HELLO','buy','DELETE','error']
                var item = items[Math.floor(Math.random()*items.length)];

                dispatch({ type: item })
        }
}
}

const ConnectedApp = connect(
    mapStateToProps,
    mapDispatchToProps
)(App);

ReactDOM.render(
    <Provider store={store}>
        <ConnectedApp />
    </Provider>,
    document.getElementById('app')
);
</code>```

Body:
I have a react native app using redux and immutable js. When i dispatch an action from my main screen, it goes through my actions, to my reducer and then back to my container, however, the view doesn't update and componentWillReceieveProps is never called. Furthermore, the main screen is a list whose items are sub components Item. Here's the relevant code for the issue, if you want to see more let me know.

Render the row with the data:

renderRow(rowData) {
    return (
        <Item item={ rowData } likePostEvent={this.props.likePostEvent} user={ this.props.user } removable={ this.props.connected } />
    )
}

The part of Item.js which dispatches an action, and shows the result:

<View style={{flex: 1, justifyContent:'center', alignItems: 'center'}}>
                        <TouchableOpacity onPress={ this.changeStatus.bind(this, "up") }>
                            <Image source={require('../img/up-arrow.png')} style={s.upDownArrow} />
                        </TouchableOpacity>
                        <Text style={[s.cardText,{fontSize:16,padding:2}]}>
                            { this.props.item.starCount }
                        </Text>
                        <TouchableOpacity onPress={ this.changeStatus.bind(this, "down") }>
                            <Image source={require('../img/up-arrow.png')} style={[s.upDownArrow,{transform: [{rotate: '180deg'}]}]} />
                        </TouchableOpacity>
                    </View>

The action dispatched goes to firebase, which has an onChange handler that dispatches another action.

The reducer:

const initialState = Map({
 onlineList: [],
 offlineList: [],
 filteredItems: [],
 connectionChecked: false,
 user: ''
})
...
...
case ITEM_CHANGED:
list = state.get('onlineList')
if(state.get('onlineList').filter((e) => e.id == action.item.id).length > 0){
  let index = state.get('onlineList').findIndex(item => item.id === action.item.id);
  list[index] = action.item
  list = list.sort((a, b) => b.time_posted - a.time_posted)
}
return state.set('onlineList',  list)
            .set('offlineList', list)

The container:

function mapStateToProps(state) {
 return {
    onlineItems: state.items.get('onlineList'),
    offlineItems: state.items.get('offlineList'),
    filteredItems: state.items.get('filteredItems'),
    connectionChecked: state.items.get('connectionChecked'),
    connected: state.items.get('connected'),
    user: state.login.user
  }
}

Where I connect the onChange:

export function getInitialState(closure_list) {
  itemsRef.on('child_removed', (snapshot) => {
    closure_list.removeItem(snapshot.val().id)
  })
  itemsRef.on('child_added', (snapshot) => {
    closure_list.addItem(snapshot.val())
  })

  itemsRef.on('child_changed', (snapshot) => {
    closure_list.itemChanged(snapshot.val())
  })

  connectedRef.on('value', snap => {
    if (snap.val() === true) {
      closure_list.goOnline()
    } else {
      closure_list.goOffline()
    }
  })
  return {
    type: GET_INITIAL_STATE,
    connected: true
  }
}

Calling get initial state:

this.props.getInitialState({
        addItem: this.props.addItem,
        removeItem: this.props.removeItem,
        goOnline: this.props.goOnline,
        goOffline: this.props.goOffline,
        itemChanged: this.props.itemChanged
    })

Any suggestions are welcome, thanks so much!


问:
Compiling and installing OpenSSH android NDK
hi i am following this guide (https://wiki.openssl.org/index.php/Android) on compiling and installing OpenSSH for Android NDK and get the following error when i execute this command:

```<code>sudo -E make install CC=$ANDROID_TOOLCHAIN/arm-linux-androideabi-gcc RANLIB=$ANDROID_TOOLCHAIN/arm-linux-androideabi-ranlib
</code>```

The error below:

```<code>make[1]: Nothing to be done for `install'.
making install in tools...
installing libcrypto.a
/bin/sh: /arm-linux-androideabi-ranlib: No such file or directory
</code>```

Am not sure where it is trying to find this file or what this file is?

答: I had to execute export ANDROID_TOOLCHAIN= /path/to/toolchain again as the setEnv-android.sh did not set the toolchain environment for some odd reason</p>

Body:
hi i am following this guide (https://wiki.openssl.org/index.php/Android) on compiling and installing OpenSSH for Android NDK and get the following error when i execute this command:

sudo -E make install CC=$ANDROID_TOOLCHAIN/arm-linux-androideabi-gcc RANLIB=$ANDROID_TOOLCHAIN/arm-linux-androideabi-ranlib

The error below:

make[1]: Nothing to be done for `install'.
making install in tools...
installing libcrypto.a
/bin/sh: /arm-linux-androideabi-ranlib: No such file or directory

Am not sure where it is trying to find this file or what this file is?


问:
Read app.config using LINQ
I have implemented (using System.Configuration namespace) and configured next App.config structure:

```<code><bot>
    <strategies>
        <add name="TestStrategy" type="Bot.Strategy.Test" >
            <indicators>
                <add name="Foo" type="Bot.Indicators.Foo, Bot" />
                <add name="Bar" type="Bot.Indicators.Bar, Bot" />
            </indicators>
            <orders>
                <add id="123" amount="0.1" />
            </orders>
        </add>
    </strategies>
</bot>
</code>```

for next classes:

```<code>class TestStrategy : IStrategy
{
    public TestStrategy(IEnumerable<IIndicator> indicators, IEnumerable<Order> orders) { }
}

interface IIndicator { }

class Order
{
    public int ID { get; set; }
    public double Amount { get; set; }
}
</code>```

So how can I read my App.config to instantiate IEnumerable<IStrategy> calling the constructor of each with appropriate IEnumerable<IIndicator> and IEnumerable<Order> using LINQ?

I have already next:

```<code>var section = ((BotSection)ConfigurationManager.GetSection("bot"));
return from strategy in section.Strategies
       let strategyType = Type.GetType(strategy.Type)
       where !strategyType.IsInterface && !strategyType.IsAbstract && typeof(IStrategy).IsAssignableFrom(strategyType)
       select (IStrategy)Activator.CreateInstance(strategyType, ?);
</code>```

答:
If your BotSection is defined correctly, you can do this (note the sub queries):

```<code>return
    from strategy in section.Strategies
    let strategyType = Type.GetType(strategy.Type)
    where !strategyType.IsInterface && !strategyType.IsAbstract
        && typeof(IStrategy).IsAssignableFrom(strategyType)
    let indicators = (
        from indicator in strategy.Indicators
        let indicatorType = Type.GetType(indicator.Type)
        select (IIndicator)Activator.CreateInstance(indicatorType))
    let orders = (
        from order in strategy.Orders
        let id = order.Id
        select new Order { Id = order.Id, Amount = order.Amount })
    select (IStrategy)Activator.CreateInstance(strategyType, indicators, orders);
</code>```

ContentLicense: CC BY-SA 2.5

Title: Read app.config using LINQ

Body:
I have implemented (using System.Configuration namespace) and configured next App.config structure:

<bot>
    <strategies>
        <add name="TestStrategy" type="Bot.Strategy.Test" >
            <indicators>
                <add name="Foo" type="Bot.Indicators.Foo, Bot" />
                <add name="Bar" type="Bot.Indicators.Bar, Bot" />
            </indicators>
            <orders>
                <add id="123" amount="0.1" />
            </orders>
        </add>
    </strategies>
</bot>

for next classes:

class TestStrategy : IStrategy
{
    public TestStrategy(IEnumerable<IIndicator> indicators, IEnumerable<Order> orders) { }
}

interface IIndicator { }

class Order
{
    public int ID { get; set; }
    public double Amount { get; set; }
}

So how can I read my App.config to instantiate IEnumerable<IStrategy> calling the constructor of each with appropriate IEnumerable<IIndicator> and IEnumerable<Order> using LINQ?

I have already next:

var section = ((BotSection)ConfigurationManager.GetSection("bot"));
return from strategy in section.Strategies
       let strategyType = Type.GetType(strategy.Type)
       where !strategyType.IsInterface && !strategyType.IsAbstract && typeof(IStrategy).IsAssignableFrom(strategyType)
       select (IStrategy)Activator.CreateInstance(strategyType, ?);

Body:
If your BotSection is defined correctly, you can do this (note the sub queries):

return
    from strategy in section.Strategies
    let strategyType = Type.GetType(strategy.Type)
    where !strategyType.IsInterface && !strategyType.IsAbstract
        && typeof(IStrategy).IsAssignableFrom(strategyType)
    let indicators = (
        from indicator in strategy.Indicators
        let indicatorType = Type.GetType(indicator.Type)
        select (IIndicator)Activator.CreateInstance(indicatorType))
    let orders = (
        from order in strategy.Orders
        let id = order.Id
        select new Order { Id = order.Id, Amount = order.Amount })
    select (IStrategy)Activator.CreateInstance(strategyType, indicators, orders);


问:
TSQL Select into Temporary Table and add Id
I'm currently working on an T-SQL Query on SQL Server 2014.

I'm trying to Select data from 1 table into another and add an extra Id to each row.

My query looks like this:

```<code>DECLARE @TargetId = 1

SELECT * INTO #tmpProjects FROM @Projects
UNION SELECT @TargetId AS 'TargetId'
</code>```

Unfortunately this Select statement does not work...

My desired output #tmpProjects should look like this:

```<code>ProjectId |    Title    | Manager   | TargetId
----------+-------------+-----------+-----------
1         |   projectX  |   1123    |  1
2         |   projectY  |   2245    |  1
3         |   projectZ  |   3335    |  1
</code>```

In my importing table @Projects, I get the columns ProjectId, Title and Manager.

Do you know how to solve this issue? Thus to select into a temporary table and add an extra Id?

Thank you very much!!

答:
If you want to add an extra column to your table then you need to Alter it to add a new column.
For keeping default value in the column you can use the DEFAULT keyword and provide the value.
Please find the query below, I hope this will be helpful:

```<code>CREATE TABLE PROJECTS(ProjectId int, Title varchar(50), Manager varchar(50))
INSERT INTO PROJECTS
VALUES
(1, 'projectX' , '1123'),
(2, 'projectY' , '2245'),
(3, 'projectZ' , '3335')
GO
BEGIN
SELECT * INTO #tmpProjects FROM PROJECTS
ALTER TABLE  #tmpProjects ADD TargetId INT NOT NULL DEFAULT (1)
SELECT * FROM #tmpProjects
END
</code>```

You cannot use any variable inside default keyword. But you can create a scalar function to use any variable of your choice.
You can check this link how to use the scalar function to add the default value to your column.

ALTER TABLE with programmatically determined constant DEFAULT value

One more thing here.You must explicitly define your column as NOT NULL if you want to use DEFAULT keyword to insert default values.
If you are not doing it then it will hold only NULL values and will not insert any value which you have provided with DEFAULT keyword

Code:

```<code>ALTER TABLE  #tmpProjects ADD TargetId INT NOT NULL DEFAULT (1)
</code>```

This will insert 1 in your TargetId column. But,

```<code>ALTER TABLE  #tmpProjects ADD TargetId INT DEFAULT (1)
</code>```

This will insert NULL in your TargetId column

Hope this will resolve your issue.

Body:
I'm currently working on an T-SQL Query on SQL Server 2014.

I'm trying to Select data from 1 table into another and add an extra Id to each row.

My query looks like this:

DECLARE @TargetId = 1

SELECT * INTO #tmpProjects FROM @Projects
UNION SELECT @TargetId AS 'TargetId'

Unfortunately this Select statement does not work...

My desired output #tmpProjects should look like this:

ProjectId |    Title    | Manager   | TargetId
----------+-------------+-----------+-----------
1         |   projectX  |   1123    |  1
2         |   projectY  |   2245    |  1
3         |   projectZ  |   3335    |  1

In my importing table @Projects, I get the columns ProjectId, Title and Manager.

Do you know how to solve this issue? Thus to select into a temporary table and add an extra Id?

Thank you very much!!

Body:
If you want to add an extra column to your table then you need to Alter it to add a new column.
For keeping default value in the column you can use the DEFAULT keyword and provide the value.
Please find the query below, I hope this will be helpful:

CREATE TABLE PROJECTS(ProjectId int, Title varchar(50), Manager varchar(50))
INSERT INTO PROJECTS
VALUES
(1, 'projectX' , '1123'),
(2, 'projectY' , '2245'),
(3, 'projectZ' , '3335')
GO
BEGIN
SELECT * INTO #tmpProjects FROM PROJECTS
ALTER TABLE  #tmpProjects ADD TargetId INT NOT NULL DEFAULT (1)
SELECT * FROM #tmpProjects
END

You cannot use any variable inside default keyword. But you can create a scalar function to use any variable of your choice.
You can check this link how to use the scalar function to add the default value to your column.

ALTER TABLE with programmatically determined constant DEFAULT value

One more thing here.You must explicitly define your column as NOT NULL if you want to use DEFAULT keyword to insert default values.
If you are not doing it then it will hold only NULL values and will not insert any value which you have provided with DEFAULT keyword

Code:

ALTER TABLE  #tmpProjects ADD TargetId INT NOT NULL DEFAULT (1)

This will insert 1 in your TargetId column. But,

ALTER TABLE  #tmpProjects ADD TargetId INT DEFAULT (1)

This will insert NULL in your TargetId column

Hope this will resolve your issue.


问:
Pip not installing in Ubuntu
I gave the command on terminal of Ubuntu 16.04 LTS as-

```<code> $ sudo apt install python-pip
</code>```

It is giving the error as:

```<code>> Reading package lists... Done Building dependency tree        Reading
> state information... Done You might want to run 'apt-get -f install'
> to correct these: The following packages have unmet dependencies:
> bcmwl-kernel-source:i386 : Depends: dkms:i386
>                             Depends: linux-libc-dev:i386 but it is not going to be installed
>                             Depends: libc6-dev:i386 but it is not going to be installed
>                             Depends: linux-headers-generic:i386 but it is not going to be installed or
>                                      linux-headers:i386  dkms : Depends: module-init-tools but it is not going to be installed
> python-pip : Depends: python-pip-whl (= 8.1.1-2ubuntu0.4) but it is
> not going to be installed
>               Recommends: python-all-dev (>= 2.6) but it is not going to be installed
>               Recommends: python-setuptools but it is not going to be installed
>               Recommends: python-wheel but it is not going to be installed E: Unmet dependencies. Try 'apt-get -f install' with no
> packages (or specify a solution).
</code>```

How can I install pip? Please see to the errors above.

答:
Okay so to get pip you need to install those missing dependencies. Try the following:

sudo apt-get update

Then

sudo apt-get upgrade

Next try:

sudo apt-get install python-pip

If that doesn't work then try with -f

For more help check this out :https://www.liquidweb.com/kb/how-to-install-pip-on-ubuntu-14-04-lts/

Title: Pip not installing in Ubuntu

Body:
I gave the command on terminal of Ubuntu 16.04 LTS as-

 $ sudo apt install python-pip

It is giving the error as:

> Reading package lists... Done Building dependency tree        Reading
> state information... Done You might want to run 'apt-get -f install'
> to correct these: The following packages have unmet dependencies:
> bcmwl-kernel-source:i386 : Depends: dkms:i386
>                             Depends: linux-libc-dev:i386 but it is not going to be installed
>                             Depends: libc6-dev:i386 but it is not going to be installed
>                             Depends: linux-headers-generic:i386 but it is not going to be installed or
>                                      linux-headers:i386  dkms : Depends: module-init-tools but it is not going to be installed
> python-pip : Depends: python-pip-whl (= 8.1.1-2ubuntu0.4) but it is
> not going to be installed
>               Recommends: python-all-dev (>= 2.6) but it is not going to be installed
>               Recommends: python-setuptools but it is not going to be installed
>               Recommends: python-wheel but it is not going to be installed E: Unmet dependencies. Try 'apt-get -f install' with no
> packages (or specify a solution).

How can I install pip? Please see to the errors above.


问:
Split a column into separate columns using regex
I have got a single column that includes the information as follows:

```<code>1 x=abc1000000\ty=pqr2000000\tz=olk78fgzu_zuii8999_ikooo
2 x=oljhh88999\ty=lop9876666
3 x=frdt876544\ty=ztr6u76532\ty=uzrt899963\tz=wertttts_765342_ioooosww\tz=tzuuuee_66554422_88uuiiid
</code>```

So, none of the id types has a certain number of occurences in a line.
They are all separated by tab.
I am searching for a way to obtain the IDs for each line as separate columns and have found tstrsplit within data.table but cannot figure out how I can use it with multiple split arguments. Any ideas?

Edit: The expected format is:

```<code>     x1          x2        y1    y2                          z1                  z2
1  abc1000000   NA pqr2000000    NA         olk78fgzu_zuii8999_ikooo            NA
2  oljhh88999   NA lop9876666    NA                               NA            NA
3  frdt876544   NA ztr6u76532   uzrt899963  wertttts_765342_ioooosww  zuuuee_66554422_88uuiiid
</code>```

Note that the id's do not include 'id' in their names. So I updated the example accordingly. The id's may appear a number of times in each line. The format given above is just an example to make the question clearer. In reality, the X type of IDs for example, can have 20 occurences in one line. The number of columns for X will be then the maximum number of appearance of this particular type of ID in a line given the whole dataset. The data is pretty large. We are talking about some 30m lines.

答:
You didn't specify what the output should look like. In order to beat akrun to the answer, here's a list where elements of the list represent your rows.

In this solution, you can split each row by the tab and find the pattern of [xyz]id[integer].

```<code>x <- c("xid1=abc1000000\tyid2=pqr2000000\tzid3=olk78fgzu_zuii8999_ikooo",
       "xid4=oljhh88999\tyid5=lop9876666",
       "xid6=frdt876544\tyid7=ztr6u76532\tyid8=uzrt899963tzid8=wertttts_765342_ioooosww\tzid9=tzuuuee_66554422_88uuiiid")

res <- sapply(x, FUN = function(m) {
  m <- strsplit(m, "\t")
  out <- sapply(m, FUN = function(o) gsub(pattern = "(^[[:alpha:]]id\\d+)(=.*$)", replacement = "\\1", x = o),
         simplify = FALSE)
  out
  }, simplify = FALSE)

res <- unname(res)
res

[[1]]
[[1]][[1]]
[1] "xid1" "yid2" "zid3"

[[2]]
[[2]][[1]]
[1] "xid4" "yid5"

[[3]]
[[3]][[1]]
[1] "xid6" "yid7" "yid8" "zid9"
</code>```

If you omit simplify = FALSE and do not unname the result, you can get

```<code>$`xid1=abc1000000\tyid2=pqr2000000\tzid3=olk78fgzu_zuii8999_ikooo`
     [,1]
[1,] "xid1"
[2,] "yid2"
[3,] "zid3"

$`xid4=oljhh88999\tyid5=lop9876666`
     [,1]
[1,] "xid4"
[2,] "yid5"

$`xid6=frdt876544\tyid7=ztr6u76532\tyid8=uzrt899963tzid8=wertttts_765342_ioooosww\tzid9=tzuuuee_66554422_88uuiiid`
     [,1]
[1,] "xid6"
[2,] "yid7"
[3,] "yid8"
[4,] "zid9"
</code>```

If you don't care about where each element came from, you can do

```<code>rapply(as.list(x), f = function(m){
  m <- strsplit(m, "\t")
  out <- sapply(m, FUN = function(o) gsub(pattern = "(^[[:alpha:]]id\\d+)(=.*$)", replacement = "\\1", x = o),
                simplify = FALSE)
})

[1] "xid1" "yid2" "zid3" "xid4" "yid5" "xid6" "yid7" "yid8" "zid9"
</code>```

but even this can be reconstructed using the first solution (counting number of elements in each list).

Body:
I have got a single column that includes the information as follows:

1 x=abc1000000\ty=pqr2000000\tz=olk78fgzu_zuii8999_ikooo
2 x=oljhh88999\ty=lop9876666
3 x=frdt876544\ty=ztr6u76532\ty=uzrt899963\tz=wertttts_765342_ioooosww\tz=tzuuuee_66554422_88uuiiid

So, none of the id types has a certain number of occurences in a line.
They are all separated by tab.
I am searching for a way to obtain the IDs for each line as separate columns and have found tstrsplit within data.table but cannot figure out how I can use it with multiple split arguments. Any ideas?

Edit: The expected format is:

     x1          x2        y1    y2                          z1                  z2
1  abc1000000   NA pqr2000000    NA         olk78fgzu_zuii8999_ikooo            NA
2  oljhh88999   NA lop9876666    NA                               NA            NA
3  frdt876544   NA ztr6u76532   uzrt899963  wertttts_765342_ioooosww  zuuuee_66554422_88uuiiid

Note that the id's do not include 'id' in their names. So I updated the example accordingly. The id's may appear a number of times in each line. The format given above is just an example to make the question clearer. In reality, the X type of IDs for example, can have 20 occurences in one line. The number of columns for X will be then the maximum number of appearance of this particular type of ID in a line given the whole dataset. The data is pretty large. We are talking about some 30m lines.

Body:
You didn't specify what the output should look like. In order to beat akrun to the answer, here's a list where elements of the list represent your rows.

In this solution, you can split each row by the tab and find the pattern of [xyz]id[integer].

x <- c("xid1=abc1000000\tyid2=pqr2000000\tzid3=olk78fgzu_zuii8999_ikooo",
       "xid4=oljhh88999\tyid5=lop9876666",
       "xid6=frdt876544\tyid7=ztr6u76532\tyid8=uzrt899963tzid8=wertttts_765342_ioooosww\tzid9=tzuuuee_66554422_88uuiiid")

res <- sapply(x, FUN = function(m) {
  m <- strsplit(m, "\t")
  out <- sapply(m, FUN = function(o) gsub(pattern = "(^[[:alpha:]]id\\d+)(=.*$)", replacement = "\\1", x = o),
         simplify = FALSE)
  out
  }, simplify = FALSE)

res <- unname(res)
res

[[1]]
[[1]][[1]]
[1] "xid1" "yid2" "zid3"

[[2]]
[[2]][[1]]
[1] "xid4" "yid5"

[[3]]
[[3]][[1]]
[1] "xid6" "yid7" "yid8" "zid9"

If you omit simplify = FALSE and do not unname the result, you can get

$`xid1=abc1000000\tyid2=pqr2000000\tzid3=olk78fgzu_zuii8999_ikooo`
     [,1]
[1,] "xid1"
[2,] "yid2"
[3,] "zid3"

$`xid4=oljhh88999\tyid5=lop9876666`
     [,1]
[1,] "xid4"
[2,] "yid5"

$`xid6=frdt876544\tyid7=ztr6u76532\tyid8=uzrt899963tzid8=wertttts_765342_ioooosww\tzid9=tzuuuee_66554422_88uuiiid`
     [,1]
[1,] "xid6"
[2,] "yid7"
[3,] "yid8"
[4,] "zid9"

If you don't care about where each element came from, you can do

rapply(as.list(x), f = function(m){
  m <- strsplit(m, "\t")
  out <- sapply(m, FUN = function(o) gsub(pattern = "(^[[:alpha:]]id\\d+)(=.*$)", replacement = "\\1", x = o),
                simplify = FALSE)
})

[1] "xid1" "yid2" "zid3" "xid4" "yid5" "xid6" "yid7" "yid8" "zid9"

but even this can be reconstructed using the first solution (counting number of elements in each list).


问:
Swift ios check if remote push notifications are enabled in ios9 and ios10
How can I check if the user has enabled remote notifications on ios 9 or ios 10?

If the user has not allowed or clicked No I want to toggle a message asking if they want to enable notifications.

答:
Apple recommends to use UserNotifications framework instead of shared instances. So, do not forget to import UserNotifications framework. As this framework is new in iOS 10 it's really only safe to use this code in apps building for iOS10+

```<code>let current = UNUserNotificationCenter.current()

current.getNotificationSettings(completionHandler: { (settings) in
    if settings.authorizationStatus == .notDetermined {
        // Notification permission has not been asked yet, go for it!
    } else if settings.authorizationStatus == .denied {
        // Notification permission was previously denied, go to settings & privacy to re-enable
    } else if settings.authorizationStatus == .authorized {
        // Notification permission was already granted
    }
})
</code>```

You may check official documentation for further information: https://developer.apple.com/documentation/usernotifications

Body:
Apple recommends to use UserNotifications framework instead of shared instances. So, do not forget to import UserNotifications framework. As this framework is new in iOS 10 it's really only safe to use this code in apps building for iOS10+

let current = UNUserNotificationCenter.current()

current.getNotificationSettings(completionHandler: { (settings) in
    if settings.authorizationStatus == .notDetermined {
        // Notification permission has not been asked yet, go for it!
    } else if settings.authorizationStatus == .denied {
        // Notification permission was previously denied, go to settings & privacy to re-enable
    } else if settings.authorizationStatus == .authorized {
        // Notification permission was already granted
    }
})

You may check official documentation for further information: https://developer.apple.com/documentation/usernotifications

ContentLicense: CC BY-SA 4.0


问:
Developing new versions of my Android Studio project
I am a newbie in Android Studio stuff. I have already developed a version 1.0 of my app. However, I want to update it into a new version 2.0 without overwritting the previous one. What is the correct way to achieve this?

Should I duplicate the project and work in other folder? Should I specify to gradle that my version is not the same as before?

Sorry for the dumb question, but I got lost here.

Thanks in advance :)

答:
Way 1:
You can create a new module in the same project. Now add the module in settings.gradle in project path. In this case, you will have 2 modules, module-1 for version-1 and module-2 for version-2. Finally, whenever you compile select the module you want to compile.

Way 2:
Create Git remote repository and push your current project in master branch. Now create a new branch in the same repository and develop your project in new branch for version 2. You can retrieve your version-1 project from master branch.

Way 2 is recommended for better practice.


问:
What is the difference between `bitCount()` and `bitLength()` of a `BigInteger`
The descriptions of bitCount() and bitLength() are rather cryptic:

public int bitCount()

Returns the number of bits in the two's complement representation of this BigInteger that differ from its sign bit. This method is useful when implementing bit-vector style sets atop BigIntegers.

Returns:
      number of bits in the two's complement representation of this BigInteger that differ from its sign bit.

public int bitLength()

Returns the number of bits in the minimal two's-complement representation of this BigInteger, excluding a sign bit. For positive BigIntegers, this is equivalent to the number of bits in the ordinary binary representation. (Computes (ceil(log2(this < 0 ? -this : this+1))).)

Returns:
      number of bits in the minimal two's-complement representation of this BigInteger, excluding a sign bit.

What is the real difference between these two methods and when should I use which?

I have used bitCount occasionally to count the number of set bits in a positive integer but I've only rarely use bitLength and usually when I meant bitCount because the differences between the descriptions are too subtle for me to instantly grok.

Google Attractor: Java BigInteger bitCount vs bitLength

答:
A quick demonstration:

```<code>public void test() {
    BigInteger b = BigInteger.valueOf(0x12345L);
    System.out.println("b = " + b.toString(2));
    System.out.println("bitCount(b) = " + b.bitCount());
    System.out.println("bitLength(b) = " + b.bitLength());
}
</code>```

prints

b = 10010001101000101

bitCount(b) = 7

bitLength(b) = 17

So, for positive integers:

bitCount() returns the number of set bits in the number.

bitLength() returns the position of the highest set bit i.e. the length of the binary representation of the number (i.e. log2).

Body:
A quick demonstration:

public void test() {
    BigInteger b = BigInteger.valueOf(0x12345L);
    System.out.println("b = " + b.toString(2));
    System.out.println("bitCount(b) = " + b.bitCount());
    System.out.println("bitLength(b) = " + b.bitLength());
}

prints

b = 10010001101000101

bitCount(b) = 7

bitLength(b) = 17

So, for positive integers:

bitCount() returns the number of set bits in the number.

bitLength() returns the position of the highest set bit i.e. the length of the binary representation of the number (i.e. log2).


问:
Distinct method doesn't work for class with overriden Equals
I created class with overriden Equals. The problem is that Distinct method doesn't work for my class.

```<code>class MyClass
{
    public int Item1 { get; private set; }
    public int Item2 { get; private set; }

    public MyClass(int item1, int item2)=>(Item1,Item2)=(item1,item2);

    public override bool Equals(object obj)
    {
        var other = obj as MyClass;

        if (other == null)
        {
            return false;
        }

        return (this.Item1 == other.Item1 && this.Item2 == other.Item2);
    }
}

class Program
{
    static void Main(string[] args)
    {
        MyClass x = new MyClass(1, 0);
        MyClass y = new MyClass(1, 0);
        var list = new List<MyClass>();
        list.Add(x);
        list.Add(y);

        bool b = x.Equals(y));  //True
        var distincts = list.Distinct(); //Doesn't work, contains both
    }
}
</code>```

How can I fix that and why it doesn't use my Equals in Distinct?

答:
You need to implement IEquatable<MyClass> in MyClass and provide your own implementation of GetHashCode and Equals method.

see this for more information.

```<code>class MyClass
{
    public int Item1 { get; private set; }
    public int Item2 { get; private set; }

    public MyClass(int item1, int item2)=>(Item1,Item2)=(item1,item2);

    public override bool Equals(object obj)
    {
        var other = obj as MyClass;

        if (other == null)
        {
            return false;
        }

        return (this.Item1 == other.Item1 && this.Item2 == other.Item2);
    }

    public override int GetHashCode()
    {

        return this.Item1;
    }
}
</code>```

Body:
I created class with overriden Equals. The problem is that Distinct method doesn't work for my class.

class MyClass
{
    public int Item1 { get; private set; }
    public int Item2 { get; private set; }

    public MyClass(int item1, int item2)=>(Item1,Item2)=(item1,item2);

    public override bool Equals(object obj)
    {
        var other = obj as MyClass;

        if (other == null)
        {
            return false;
        }

        return (this.Item1 == other.Item1 && this.Item2 == other.Item2);
    }
}

class Program
{
    static void Main(string[] args)
    {
        MyClass x = new MyClass(1, 0);
        MyClass y = new MyClass(1, 0);
        var list = new List<MyClass>();
        list.Add(x);
        list.Add(y);

        bool b = x.Equals(y));  //True
        var distincts = list.Distinct(); //Doesn't work, contains both
    }
}

How can I fix that and why it doesn't use my Equals in Distinct?

Body:
You need to implement IEquatable<MyClass> in MyClass and provide your own implementation of GetHashCode and Equals method.

see this for more information.

class MyClass
{
    public int Item1 { get; private set; }
    public int Item2 { get; private set; }

    public MyClass(int item1, int item2)=>(Item1,Item2)=(item1,item2);

    public override bool Equals(object obj)
    {
        var other = obj as MyClass;

        if (other == null)
        {
            return false;
        }

        return (this.Item1 == other.Item1 && this.Item2 == other.Item2);
    }

    public override int GetHashCode()
    {

        return this.Item1;
    }
}


问:
build a "fake" stake using startActivity()
I need to build a fake back stack in my application. I am starting an activity using aContext.startActivity(aIntent) and would like to build a stack to allow the user to go to the HomeActivity instead of exiting the application.

Now I know about the TaskStackBuilder but I am not sure on how to implement it when it comes to startActivity method.

This is what I got so far when building the stack but I am not sure how to use it in startActivity method

```<code>    Intent detailActivity = new Intent(aContext, DetailsActivity.class);
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(aContext);
    stackBuilder.addNextIntentWithParentStack(detailActivity);
    PendingIntent pendingIntent = stackBuilder
            .getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
</code>```

答:
You need to start activity without adding to back stack, then override the onBackpressed</p>

```<code>//Start activity without adding to history stack
Intent i = new Intent(...); // Your list's Intent
i.setFlags(i.getFlags() | Intent.FLAG_ACTIVITY_NO_HISTORY); // Adds the FLAG_ACTIVITY_NO_HISTORY flag
startActivity(i);

//Override the newly open activity onBackPressed()
@Override
public void onBackPressed()
{
    Intent i= new Intent(getApplicationContext(),HomeActivity.class);
    startActivity(i);
}
</code>```

Body:
I need to build a fake back stack in my application. I am starting an activity using aContext.startActivity(aIntent) and would like to build a stack to allow the user to go to the HomeActivity instead of exiting the application.

Now I know about the TaskStackBuilder but I am not sure on how to implement it when it comes to startActivity method.

This is what I got so far when building the stack but I am not sure how to use it in startActivity method

    Intent detailActivity = new Intent(aContext, DetailsActivity.class);
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(aContext);
    stackBuilder.addNextIntentWithParentStack(detailActivity);
    PendingIntent pendingIntent = stackBuilder
            .getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

Body:
You need to start activity without adding to back stack, then override the onBackpressed

//Start activity without adding to history stack
Intent i = new Intent(...); // Your list's Intent
i.setFlags(i.getFlags() | Intent.FLAG_ACTIVITY_NO_HISTORY); // Adds the FLAG_ACTIVITY_NO_HISTORY flag
startActivity(i);

//Override the newly open activity onBackPressed()
@Override
public void onBackPressed()
{
    Intent i= new Intent(getApplicationContext(),HomeActivity.class);
    startActivity(i);
}


问:
Can/should IdentityServer4 be used to create a token for user-email verification
I have IdentityServer4 setup for API authentication although I have a use case where I want to verify that a guest (user) is essentially a valid user.  A valid user in my case is anyone with a valid email address, so I want to do the following:

send the user an email with a verification token (preferably something which is a mash up of their email address, some salt and an expiry

the user can then enter this token into my app and they are "allowed" to go ahead

I was wondering if IdentityServer4 can/should be used to achieve the above?

Their tools show that you can generate a token although I am very new to this topic so was hoping for some guidance.

答:
No, the tokens Identity Server deals with are access_tokens which are to do with claims-based authentication.

The tokens you need to use for email verification are commonly referred to as User Tokens, or one-time passwords (OTP). You can find a wealth of information on how to generate/consume these using those search terms but if you use the aspnet identity classes such as the UserManager you will find it has some in-built read to use. Or you can register your own UserTokenProvider with the UserManager.

In general you'd do something like this:

Use your UserTokenProvider to get a token (otp) for a specific user. The UserManager will use the security hash of that user and your own 'reason' (e.g. "EmailVerification") to generate the short OTP.

You could then wrap that OTP into an object that includes the email address, a userid maybe, and whatever you like. Safe Base64 encode it (there is a helper function within Identity Server that has this in fact, making sure it doesn't have the superfluous _ at the end which will mess with HTML links), put it in an email to the user

User clicks your link which takes them to your 'verify password' controller, with your mashed up token as payload. You decode it, work out which user it was for, get UserManager to verify the OTP part is still valid.

Job done.

If you want them to enter the OTP into your app directly, while logged in, then you could just skip the whole mash-up part of emailing a link, and email the short OTP directly.


问:
Two form_tag on the same haml page
routes.rb

```<code> put '/', to: 'search#admin_action', as: 'admin_action'
 root 'search#index
</code>```

search_controller.rb

```<code>class SearchController < ApplicationController

  def index
  end

  def admin_action
    redirect_to root_path
  end
end
</code>```

I have two forms under index.html.haml page
...

```<code>= form_tag({action:'index'}, {method: :get})
</code>```

...

```<code>= submit_tag 'Search'
</code>```

...

```<code>= form_tag({url: admin_action_path}, {method: :put})
</code>```

...

```<code>= submit_tag 'Action'
</code>```

All two submit buttons will be processed by index method in this case (never admin_action will be called). Actually, always action from first form is active for all below submit buttons. In erb files, maybe I can use some <% end %> to split these forms, but how to do that in haml file.

答:
Form_tag (under haml) doesn't generate </form> into final source. form_for works fine. To get correct final source, form_tag has to be use with do. So correct first line will be

```<code>= form_tag({action:'index'}, {method: :get}) do
</code>```

Title: Two form_tag on the same haml page

Body:
routes.rb

 put '/', to: 'search#admin_action', as: 'admin_action'
 root 'search#index

search_controller.rb

class SearchController < ApplicationController

  def index
  end

  def admin_action
    redirect_to root_path
  end
end

I have two forms under index.html.haml page
...

= form_tag({action:'index'}, {method: :get})

...

= submit_tag 'Search'

...

= form_tag({url: admin_action_path}, {method: :put})

...

= submit_tag 'Action'

All two submit buttons will be processed by index method in this case (never admin_action will be called). Actually, always action from first form is active for all below submit buttons. In erb files, maybe I can use some <% end %> to split these forms, but how to do that in haml file.

Body:
Form_tag (under haml) doesn't generate </form> into final source. form_for works fine. To get correct final source, form_tag has to be use with do. So correct first line will be

= form_tag({action:'index'}, {method: :get}) do


问:
Perl. Can't enter to a while (<>) loop
I have a piece of code in perl, that is used for a pre-recieve git hook (it restricts the size of files, that can be pushed. It is on the server side). The problem is that I can't enter the while (<>) loop, I don't really know, how it works. Could you explain it to me? Why can't I enter a loop?

Thanks in advance!

The code of while loop is here:

```<code>while (<>) {
  print "I can't enter here, so I cannot block the files!!!"
  chomp;
  my ($old, $new, $ref) = split / /, $_;
  my %visited = ();
  my $log = ($old =~ /^0+$/ ? `/usr/bin/git log --pretty=%H $new`
                            : `/usr/bin/git log --pretty=%H $old..$new`);
  for my $commit (split /\n/, $log) {
    # pick new files in each commit
    for my $entry (split /\n/,
      ($old =~ /^0+$/
        ? `/usr/bin/git diff-tree --no-commit-id -r $commit`
        : `/usr/bin/git diff-tree --no-commit-id -r $old..$commit`)) {
      if ($entry =~ /^:\d+ \d+ \w+ (\w+) \w+\t(.*)$/ && !$visited{$1}) {
        my $sha = $1;
        my $name = $2;
        unless ($sha =~ /^0+$/) {
          $visited{$sha} = 1;
          # check file size
          my $size = `/usr/bin/git cat-file -s $sha`;
          chomp $size;
          # reject file size is greater than limit
          if ($size > $limit) {
            my $shortsha = substr($commit, 0, 10);
            my $hsize = hsize($size);
            my $hlimit = hsize($limit);
            print "'$name' of size $hsize in $shortsha is over $hlimit limit";
            $hasBadFiles = 1;
          }
        }
      }
    }
  }
}
</code>```

答:
<> - the diamond operator - is also known and used as <ARGV>:

perldoc perlvar

ARGV
  The special filehandle that iterates over command-line filenames in @ARGV . Usually written as the null filehandle in the angle operator <> . Note that currently ARGV only has its magical effect within the <> operator; elsewhere it is just a plain filehandle corresponding to the last file opened by <> . In particular, passing *ARGV as a parameter to a function that expects a filehandle may not cause your function to automatically read the contents of all the files in @ARGV .

```<code>while ( <> ) {
</code>```

Tells perl to either:

Open files specified as arguments, and read them line by line.

Read STDIN line by line.

Title: Perl. Can't enter to a while (<>) loop

Body:
I have a piece of code in perl, that is used for a pre-recieve git hook (it restricts the size of files, that can be pushed. It is on the server side). The problem is that I can't enter the while (<>) loop, I don't really know, how it works. Could you explain it to me? Why can't I enter a loop?

Thanks in advance!

The code of while loop is here:

while (<>) {
  print "I can't enter here, so I cannot block the files!!!"
  chomp;
  my ($old, $new, $ref) = split / /, $_;
  my %visited = ();
  my $log = ($old =~ /^0+$/ ? `/usr/bin/git log --pretty=%H $new`
                            : `/usr/bin/git log --pretty=%H $old..$new`);
  for my $commit (split /\n/, $log) {
    # pick new files in each commit
    for my $entry (split /\n/,
      ($old =~ /^0+$/
        ? `/usr/bin/git diff-tree --no-commit-id -r $commit`
        : `/usr/bin/git diff-tree --no-commit-id -r $old..$commit`)) {
      if ($entry =~ /^:\d+ \d+ \w+ (\w+) \w+\t(.*)$/ && !$visited{$1}) {
        my $sha = $1;
        my $name = $2;
        unless ($sha =~ /^0+$/) {
          $visited{$sha} = 1;
          # check file size
          my $size = `/usr/bin/git cat-file -s $sha`;
          chomp $size;
          # reject file size is greater than limit
          if ($size > $limit) {
            my $shortsha = substr($commit, 0, 10);
            my $hsize = hsize($size);
            my $hlimit = hsize($limit);
            print "'$name' of size $hsize in $shortsha is over $hlimit limit";
            $hasBadFiles = 1;
          }
        }
      }
    }
  }
}

Body:
<> - the diamond operator - is also known and used as <ARGV>:

perldoc perlvar

ARGV
  The special filehandle that iterates over command-line filenames in @ARGV . Usually written as the null filehandle in the angle operator <> . Note that currently ARGV only has its magical effect within the <> operator; elsewhere it is just a plain filehandle corresponding to the last file opened by <> . In particular, passing *ARGV as a parameter to a function that expects a filehandle may not cause your function to automatically read the contents of all the files in @ARGV .

while ( <> ) {

Tells perl to either:

Open files specified as arguments, and read them line by line.

Read STDIN line by line.


问:
Android - How to stop showing notification when open application
I'm new to android development... trying to build application which send notification at specific time daily.First time if I tap on notification it opens application and notification doesn't come again. But after that if I open application it shows notification again.. how to stop showing it again? but show only at particular time?
..

MainAcitivty code is:

```<code>    public class MainActivity extends AppCompatActivity {
        @Override
        protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, 8);
        calendar.set(Calendar.MINUTE, 36);
        calendar.set(Calendar.SECOND, 0);
        Intent intent = new Intent(MainActivity.this, AlarmReceiver.class);
        pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        AlarmManager am = (AlarmManager) MainActivity.this.getSystemService(MainActivity.this.ALARM_SERVICE);
        am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
        Intent i = getIntent();
        if (i.getBooleanExtra("STARTED_BY_RECEIVER", false)) {
            pendingIntent.cancel();
        }
    }
</code>```

AlarmReceiver Class is :

```<code>public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

        intent = new Intent(context, MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        intent.putExtra("STARTED_BY_RECEIVER", true);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 100, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        NotificationCompat.Builder builder = (NotificationCompat.Builder) new NotificationCompat.Builder(context)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentIntent(pendingIntent)
                .setContentText("notification text")
                .setContentTitle("notification title")
                .setAutoCancel(true)
                .setOngoing(true);
        notificationManager.notify(100, builder.build());
}
}
</code>```

答:
Your main Activity look like this:-

```<code> public class MainActivity extends AppCompatActivity {

    private PendingIntent pendingIntent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Intent i = getIntent();

        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, 1);
        calendar.set(Calendar.MINUTE, 49);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.AM_PM,Calendar.PM);

        if(calendar.getTimeInMillis()>System.currentTimeMillis()){

             Intent intent = new Intent(MainActivity.this, AlarmReceiver.class);
             pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
             AlarmManager am = (AlarmManager) MainActivity.this.getSystemService(MainActivity.this.ALARM_SERVICE);
             am.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 24*60*60*1000, pendingIntent); //Repeat every 24 h

         }
        else{

            Toast.makeText(getApplicationContext(),"Always set value with greater than current time",Toast.LENGTH_SHORT).show();
        }

    }
}
</code>```

and put below code on your reciever:-

```<code>NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

    intent = new Intent(context, MainActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
    intent.putExtra("STARTED_BY_RECEIVER", true);
    context.startActivity(intent);

    PendingIntent pendingIntent = PendingIntent.getActivity(context, 100, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    NotificationCompat.Builder builder = (NotificationCompat.Builder) new NotificationCompat.Builder(context)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentIntent(pendingIntent)
            .setContentText("notification text")
            .setContentTitle("notification title")
            .setAutoCancel(true)
            .setOngoing(true);
    notificationManager.notify(100, builder.build());
</code>```

Body:
I'm new to android development... trying to build application which send notification at specific time daily.First time if I tap on notification it opens application and notification doesn't come again. But after that if I open application it shows notification again.. how to stop showing it again? but show only at particular time?
..

MainAcitivty code is:

    public class MainActivity extends AppCompatActivity {
        @Override
        protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, 8);
        calendar.set(Calendar.MINUTE, 36);
        calendar.set(Calendar.SECOND, 0);
        Intent intent = new Intent(MainActivity.this, AlarmReceiver.class);
        pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        AlarmManager am = (AlarmManager) MainActivity.this.getSystemService(MainActivity.this.ALARM_SERVICE);
        am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
        Intent i = getIntent();
        if (i.getBooleanExtra("STARTED_BY_RECEIVER", false)) {
            pendingIntent.cancel();
        }
    }

AlarmReceiver Class is :

public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

        intent = new Intent(context, MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        intent.putExtra("STARTED_BY_RECEIVER", true);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 100, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        NotificationCompat.Builder builder = (NotificationCompat.Builder) new NotificationCompat.Builder(context)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentIntent(pendingIntent)
                .setContentText("notification text")
                .setContentTitle("notification title")
                .setAutoCancel(true)
                .setOngoing(true);
        notificationManager.notify(100, builder.build());
}
}

Body:
Your main Activity look like this:-

 public class MainActivity extends AppCompatActivity {

    private PendingIntent pendingIntent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Intent i = getIntent();

        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, 1);
        calendar.set(Calendar.MINUTE, 49);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.AM_PM,Calendar.PM);

        if(calendar.getTimeInMillis()>System.currentTimeMillis()){

             Intent intent = new Intent(MainActivity.this, AlarmReceiver.class);
             pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
             AlarmManager am = (AlarmManager) MainActivity.this.getSystemService(MainActivity.this.ALARM_SERVICE);
             am.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 24*60*60*1000, pendingIntent); //Repeat every 24 h

         }
        else{

            Toast.makeText(getApplicationContext(),"Always set value with greater than current time",Toast.LENGTH_SHORT).show();
        }

    }
}

and put below code on your reciever:-

NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

    intent = new Intent(context, MainActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
    intent.putExtra("STARTED_BY_RECEIVER", true);
    context.startActivity(intent);

    PendingIntent pendingIntent = PendingIntent.getActivity(context, 100, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    NotificationCompat.Builder builder = (NotificationCompat.Builder) new NotificationCompat.Builder(context)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentIntent(pendingIntent)
            .setContentText("notification text")
            .setContentTitle("notification title")
            .setAutoCancel(true)
            .setOngoing(true);
    notificationManager.notify(100, builder.build());


问:
How to create a stylesheet dynamically and add that to a node
Currently JavaFX does not allow attaching a stylesheet to a node (or scene) that is not in the classpath. So, if a css file is not in the classpath already, it cannot be added to any node. The getStyleSheets().add() method will state 'WARNING Resource [your file] not found'. So is there any workaround to this limitation?</p>

答:
Not sure if this is what you are looking for...</p>

```<code>Button node = new Button();
node.getStyleClass().add("my-new-style-class");

.my-new-style-class {
    -fx-padding: 5;
}
</code>```

Body:
Not sure if this is what you are looking for...

Button node = new Button();
node.getStyleClass().add("my-new-style-class");

.my-new-style-class {
    -fx-padding: 5;
}


答:
It is a minified code that, when executed, redirects you to this web page:
http://www.templatemark.com</p>

Title: What is the encoding used in this code?


问:
git stash newly created files
I have a master branch in git, for the recent enhancement I wrote above 20 new java files.

then I realize that I am in master branch and I am not suppose to commit changes in master branch directly.

So I created new branch angular-changes.

When I tried to switch to new branch all newly added and existing modified files were in my upstaged area, so eclipse promoted whether to stash or reset changes. I choose stash and gave a name to that stash.

After switching to new branch i.e. angular-changes. when I tried applying stashed changes, it did not add newly added files. that files which I modified in master branch only got merged.

Is there anyway to recover those files?

答:
From the command line : you want to run git stash apply --index on top of the clean head of your branch.

First you need to check that the first stash is still what you had on master :

```<code>git stash list --oneline  # this will print a hash and the stash message
                          # for each stash
</code>```

You can check that the first message is the one you expect, and that the content of the stash contains all that you had (inspect the content of <hash>, and its parents)

Title: git stash newly created files

Body:
From the command line : you want to run git stash apply --index on top of the clean head of your branch.

First you need to check that the first stash is still what you had on master :

git stash list --oneline  # this will print a hash and the stash message
                          # for each stash

You can check that the first message is the one you expect, and that the content of the stash contains all that you had (inspect the content of <hash>, and its parents)


问:
How would I go about making this error message appear when form field is not right?
I have an if statement and I already have it working so if certain fields are not filled in it will not send. I then have an else, and I put it like so:

```<code>if(isset($_POST['submit'])) {
    if (!empty($name) && (!empty($email) || !empty($phone))) {
    mail( "EMAIL@hotmail.com", "Monthly Specials Email",
    "Name: $name
     Email: $email
     Phone Number: $phone
     Comment: $comment", "From: $email" );

    $error = "";

   } else {
    $error = "Please fill in the required fields.";
   }
}
</code>```

In the form, I have a span class like so:

```<code><span class="error">'.$error.'</span>
</code>```

I have it so the action of the form is set to blank so it will stay on the same page when sent, and all of the functions are in the same page as the form. How would I go about updating the error span?

Thanks so much for any help or tips!

答:
When I handle form validations, I tend to create an array to hold the error messages, like so:

```<code><?php

$error = array();
if( $POST ){
 # Form is Submitted
  if( /* TRUE if "email" is empty */ ){
    $error['email'] = 'Please provide an Email Address';
  }elseif( /* TRUE if "email" is not a valid address */ ){
    $error['email'] = 'Please provide a Valid Email Address';
  }elseif( /* TRUE if "email" is already associated with a User */ ){
    $error['email'] = 'The Provided Email Address is Already Taken';
  }

...

  if( count( $error )==0 ){
   # No Error has been Recorded
   # Do Successful Things
  }
} /* Closing if( $_POST ){ */
</code>```

Then within the presentation/display section, I have something like:

```<code><?php if( count( $error )>0 ){ ?>
<div id="error">
  The following Errors have occurred:
  <ul>
<?php foreach( $error as $k => $v ){ ?>
    <li><?php echo $k; ?>: <?php echo $v; ?></li>
<?php } ?>
  </ul>
</div>
<?php } ?>
</code>```

And within the form, something like:

```<code><input name="email"<?php echo ( $error['email'] ? ' class="error"' : '' ); ?> />
</code>```

This means that:

Customised, multi-tiered error messages can be recorded.

A summary of the error messages can be shown.

Fields associated with the error messages can be marked.

Has worked well in my experience thusfar.

Body:
I have an if statement and I already have it working so if certain fields are not filled in it will not send. I then have an else, and I put it like so:

if(isset($_POST['submit'])) {
    if (!empty($name) && (!empty($email) || !empty($phone))) {
    mail( "EMAIL@hotmail.com", "Monthly Specials Email",
    "Name: $name
     Email: $email
     Phone Number: $phone
     Comment: $comment", "From: $email" );

    $error = "";

   } else {
    $error = "Please fill in the required fields.";
   }
}

In the form, I have a span class like so:

'.$error.'

I have it so the action of the form is set to blank so it will stay on the same page when sent, and all of the functions are in the same page as the form. How would I go about updating the error span?

Thanks so much for any help or tips!

Body:
When I handle form validations, I tend to create an array to hold the error messages, like so:

<?php

$error = array();
if( $POST ){
 # Form is Submitted
  if( /* TRUE if "email" is empty */ ){
    $error['email'] = 'Please provide an Email Address';
  }elseif( /* TRUE if "email" is not a valid address */ ){
    $error['email'] = 'Please provide a Valid Email Address';
  }elseif( /* TRUE if "email" is already associated with a User */ ){
    $error['email'] = 'The Provided Email Address is Already Taken';
  }

...

  if( count( $error )==0 ){
   # No Error has been Recorded
   # Do Successful Things
  }
} /* Closing if( $_POST ){ */

Then within the presentation/display section, I have something like:

<?php if( count( $error )>0 ){ ?>
<div id="error">
  The following Errors have occurred:
  <ul>
<?php foreach( $error as $k => $v ){ ?>
    <li><?php echo $k; ?>: <?php echo $v; ?></li>
<?php } ?>
  </ul>
</div>
<?php } ?>

And within the form, something like:

<input name="email"<?php echo ( $error['email'] ? ' class="error"' : '' ); ?> />

This means that:

Customised, multi-tiered error messages can be recorded.

A summary of the error messages can be shown.

Fields associated with the error messages can be marked.

Has worked well in my experience thusfar.


问:
SQL inner join returns multiple values
I have 2 tables, with following values:

tbl_a1

```<code>ID  Prod_Code   Prod_Sub    Prod_Note   Rec_Name    Prod_Qty    Prod_Flow   Rec_Mat_Act
306     111     1   falcon 1128     Stab120     25  5000    22623.17
307     111     2   falcon 1128     Stab120     25  5000    22635.52
308     111     3   falcon 1128     Stab120     24  5000    21623.89
309     111     4   falcon 1128     Stab120     27  5000    24439.78
311     111     5   falcon 1128     Stab120     27  5000    24402.79
313     111     6   falcon 1128     Stab120     24  5000    21582.37
315     111     7   falcon 1128     Stab120     14  5000    12654.76
316     111     8   falcon 1128     Stab120     27  5000    24447.1
317     111     9   falcon 1128     Stab120     25  5000    22613.14
318     111     10  falcon 1128     Stab120     23  5000    20759.74
</code>```

tbl_c1

```<code>ID  Prod_Code   Prod_Sub    Prod_Note   Rec_Name    Prod_Qty    Prod_Flow   Rec_Mat_Act
226     111     1   falcon 1128     Stab120     25  5000    1604.125
227     111     2   falcon 1128     Stab120     25  5000    1601.498
228     111     3   falcon 1128     Stab120     24  5000    1645.118
229     111     4   falcon 1128     Stab120     27  5000    1740.419
231     111     5   falcon 1128     Stab120     27  5000    1774.387
233     111     6   falcon 1128     Stab120     24  5000    1674.871
235     111     7   falcon 1128     Stab120     14  5000    918.7184
236     111     8   falcon 1128     Stab120     27  5000    1740.139
237     111     9   falcon 1128     Stab120     25  5000    1633.708
238     111     10  falcon 1128     Stab120     23  5000    1536.74
</code>```

e is unique and appears in both tables.

Prod_Code is the unique production numbers Prod_Sub is the batch number (a prod_code can have several batch numbers)

rec_mat_act is the actual used material in production

I'm trying to get a list with all unique prod_codes and their prod_sub and the used materials but I get duplicates results.

I'm using the following query:

```<code>SELECT      a1.Prod_Code,
            a1.Prod_Sub,
            a1.Prod_Note,
            c1.Rec_Mat_Act
FROM        Tbl_Aggr1 as a1 INNER JOIN  Tbl_Cem1 as c1
            on c1.Prod_Code = a1.Prod_Code
WHERE       a1.Prod_Code = '111'
</code>```

using a DISTINCT in the SELECT didn't help me, neither did GROUP BY but maybe i'm using it all wrong.

答:
If you put a distinct in the select it should just get the distinct prod_code from the first table and then all the resulting attached to it i.e:</p>

```<code>select distinct
    a.prod_code, a.prod_sub, c.rec_mat_act
from tbl_a1 a
inner join tbl_c1 c on a.prod_code = c.prod_code
where a.prod_code = 111
</code>```

Title: SQL inner join returns multiple values

Body:
I have 2 tables, with following values:

tbl_a1

ID  Prod_Code   Prod_Sub    Prod_Note   Rec_Name    Prod_Qty    Prod_Flow   Rec_Mat_Act
306     111     1   falcon 1128     Stab120     25  5000    22623.17
307     111     2   falcon 1128     Stab120     25  5000    22635.52
308     111     3   falcon 1128     Stab120     24  5000    21623.89
309     111     4   falcon 1128     Stab120     27  5000    24439.78
311     111     5   falcon 1128     Stab120     27  5000    24402.79
313     111     6   falcon 1128     Stab120     24  5000    21582.37
315     111     7   falcon 1128     Stab120     14  5000    12654.76
316     111     8   falcon 1128     Stab120     27  5000    24447.1
317     111     9   falcon 1128     Stab120     25  5000    22613.14
318     111     10  falcon 1128     Stab120     23  5000    20759.74

tbl_c1

ID  Prod_Code   Prod_Sub    Prod_Note   Rec_Name    Prod_Qty    Prod_Flow   Rec_Mat_Act
226     111     1   falcon 1128     Stab120     25  5000    1604.125
227     111     2   falcon 1128     Stab120     25  5000    1601.498
228     111     3   falcon 1128     Stab120     24  5000    1645.118
229     111     4   falcon 1128     Stab120     27  5000    1740.419
231     111     5   falcon 1128     Stab120     27  5000    1774.387
233     111     6   falcon 1128     Stab120     24  5000    1674.871
235     111     7   falcon 1128     Stab120     14  5000    918.7184
236     111     8   falcon 1128     Stab120     27  5000    1740.139
237     111     9   falcon 1128     Stab120     25  5000    1633.708
238     111     10  falcon 1128     Stab120     23  5000    1536.74

e is unique and appears in both tables.

Prod_Code is the unique production numbers Prod_Sub is the batch number (a prod_code can have several batch numbers)

rec_mat_act is the actual used material in production

I'm trying to get a list with all unique prod_codes and their prod_sub and the used materials but I get duplicates results.

I'm using the following query:

SELECT      a1.Prod_Code,
            a1.Prod_Sub,
            a1.Prod_Note,
            c1.Rec_Mat_Act
FROM        Tbl_Aggr1 as a1 INNER JOIN  Tbl_Cem1 as c1
            on c1.Prod_Code = a1.Prod_Code
WHERE       a1.Prod_Code = '111'

using a DISTINCT in the SELECT didn't help me, neither did GROUP BY but maybe i'm using it all wrong.

Body:
If you put a distinct in the select it should just get the distinct prod_code from the first table and then all the resulting attached to it i.e:

select distinct
    a.prod_code, a.prod_sub, c.rec_mat_act
from tbl_a1 a
inner join tbl_c1 c on a.prod_code = c.prod_code
where a.prod_code = 111


问:
Three js bump mapping
I have created a simple scene in three js (r85). It contains a camera, a light and a plane geometry mesh. I have also created a renderertarget where I render the bumpmap texture of the plane with a ShaderMaterial. In the fragment shader the bump mapping uses a continuous function (so the bump mapping should be "smooth"):

```<code>varying vec2 vUV;

void main() {
    float x = sin(sqrt(vUV.x * vUV.x + vUV.y * vUV.y));
    gl_FragColor.rgb = vec3(x, x, x);
}
</code>```

The code renders the following image (strange lines):

Some kind of strange lines appears when I use bump mapping with MeshPhongMaterial.

See jsfiddle here.

Can someone tell me what are those strange lines and how to avoid these? If I use a simple image for bump map (not a rendertarget) then the lines do not appear.

Thanks!

答:
This is happening because with a length of 0-sqrt(2) or 0-1.41, you're utilizing a tiny portion of the period of a sin wave 0-2*PI or 0-6.283 - so the color depth of the texture is being stressed - you're getting a step of 1 bit every 50 pixels or whatever - it's the reason that radial gradients look like a series of rings when you're fading from say 0x000000 to 0x1a1a1a.

Check out a branch i made from it. I did a couple things like changing the magfilter to linear (nearest will always look pixelated), but mostly I just changed the period of the bump map so that it goes up and down a few times rather than just going up a tiny bit over the course of the texture.

Another thing to keep in mind is that bump maps always look gross on their own and turned up to 11. It's doing a tough task which is trying to fake a 3d surface in 2d space, and because it's a texture, it has a finite resolution, which on close inspection will look gross.

Title: Three js bump mapping

Body:
I have created a simple scene in three js (r85). It contains a camera, a light and a plane geometry mesh. I have also created a renderertarget where I render the bumpmap texture of the plane with a ShaderMaterial. In the fragment shader the bump mapping uses a continuous function (so the bump mapping should be "smooth"):

varying vec2 vUV;

void main() {
    float x = sin(sqrt(vUV.x * vUV.x + vUV.y * vUV.y));
    gl_FragColor.rgb = vec3(x, x, x);
}

The code renders the following image (strange lines):

Some kind of strange lines appears when I use bump mapping with MeshPhongMaterial.

See jsfiddle here.

Can someone tell me what are those strange lines and how to avoid these? If I use a simple image for bump map (not a rendertarget) then the lines do not appear.

Thanks!


问:
Dependent DLL is not getting copied to the build output folder in Visual Studio
I have a visual studio solution.
I have many projects in the solution.
There is one main project which acts as the start up and uses other projects.
There is one project say "ProjectX". Its reference is added to main project.
The ProjectX references another .NET dll (say abc.dll) that isn't part of the solution.

Now this abc.dll should be copied to bin/debug folder of main project, but it isn't getting copied there. Why is it not getting copied, any known reasons ?

答:
NO NEED FOR DUMMY IN CODE

Just :

add a Reference to the Executeable Project

or/and ensure that the reference in the executeable project has "Copy Local" set to TRUE (which was my "fault") is seems that this "overwrote" the setting in the base referenced library-project...


问:
How to align 2 tables (left and center) inside a div?
I want to center one table inside a div and have another table floating to the left of the first one.
My desired result would look something like this:

```[ (Left Table)     (Center table)               ]```

But with my current HTML and CSS (seen below) I get this result:

```[ (Left Table)           (Center table)         ]```

The problem here being that it floats the first table to the left and centers the second table in the remaining space.

This is the code:

#wrapper {
  text-align: center;
  width: 500px;
  border: 1px solid black;
}

#left {
  float:left;
}

#center {
  margin: 0 auto;
}

td {
  border: 1px solid black;
  width: 100px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="wrapper">
  <table id="left">
    <tr>
      <td>
        Left
      </td>
    </tr>
  </table>

  <table id="center">
    <tr>
      <td>
        Center
      </td>
    </tr>
  </table>
</div></code>```

Any help on how to fix it?

答:
Try position:absolute; left:0px; for the first table and position:relative; for the wrapper

body{
    margin:0px;
    padding:0px;
}

#wrapper {
    text-align: center;
    border:1px solid #ddd;
    position:relative;

}
#left {
    position:absolute;
    left:0px;
    /*
    float:left;*/
}
#center {
    margin: 0 auto;

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="wrapper">
    <table id="left" border="1">
      <tr>
        <td>table1</td>
      </tr>
    </table>
    <table id="center" border="1">
      <tr>
        <td>table2</td>
      </tr>
    </table>
</div></code>```

Body:
I want to center one table inside a div and have another table floating to the left of the first one.
My desired result would look something like this:

[ (Left Table)     (Center table)               ]

But with my current HTML and CSS (seen below) I get this result:

[ (Left Table)           (Center table)         ]

The problem here being that it floats the first table to the left and centers the second table in the remaining space.

This is the code:

#wrapper {
  text-align: center;
  width: 500px;
  border: 1px solid black;
}

#left {
  float:left;
}

#center {
  margin: 0 auto;
}

td {
  border: 1px solid black;
  width: 100px;
}

        Left

        Center

Any help on how to fix it?

Body:
Try position:absolute; left:0px; for the first table and position:relative; for the wrapper

body{
    margin:0px;
    padding:0px;
}

#wrapper {
    text-align: center;
    border:1px solid #ddd;
    position:relative;

}
#left {
    position:absolute;
    left:0px;
    /*
    float:left;*/
}
#center {
    margin: 0 auto;

}

<div id="wrapper">
    <table id="left" border="1">
      <tr>
        <td>table1</td>
      </tr>
    </table>
    <table id="center" border="1">
      <tr>
        <td>table2</td>
      </tr>
    </table>
</div>


问:
Adobe PhoneGap - iOS app not loading until swipe up for Control Center
I am using Adobe PhoneGap with Cordova cli-6.5.0 and Apple install in a development mode.  On an iPad 2 (iOS 9.3.5) the app works correctly on launch, but on an iPhone SE and an iPhone 7 both running current iOS 10.3.2 the app will not launch until I swipe up and bring the Control Center up.  Not sure if it is an iOS version issue or device issue.

Same bug occurs whether the app is in Airplane mode for offline page or online to begin the app.  My guess is onDeviceReady is not responding on the iPhone test until the Control Center is brought up.

Any suggestions?

答:
Since this affects only iOS 10, it sounds the issue you're encountering is related to the strict application of Content Security Policy rules to UIWebView, which was added in iOS 10. By opening the Control Centre you are placing your app in the background, then dismissing the Control Centre resumes the app, which causes the issue to go away.

See this question and answer for a full explanation and solution, but in a nutshell make sure you have a Content-Security-Policy meta tag in your index.html and make sure it contains entries for gap: and file:, for example:

```<code><meta http-equiv="Content-Security-Policy" content="default-src * gap: file:; style-src 'self' 'unsafe-inline'; img-src 'self' data:; script-src * 'unsafe-inline' 'unsafe-eval'">
</code>```

Body:
Since this affects only iOS 10, it sounds the issue you're encountering is related to the strict application of Content Security Policy rules to UIWebView, which was added in iOS 10. By opening the Control Centre you are placing your app in the background, then dismissing the Control Centre resumes the app, which causes the issue to go away.

See this question and answer for a full explanation and solution, but in a nutshell make sure you have a Content-Security-Policy meta tag in your index.html and make sure it contains entries for gap: and file:, for example:

<meta http-equiv="Content-Security-Policy" content="default-src * gap: file:; style-src 'self' 'unsafe-inline'; img-src 'self' data:; script-src * 'unsafe-inline' 'unsafe-eval'">


问:
Python create all possible combinations from a integer
I have integer for example "123", using this i want to create all possible combinations listed below.
123
12,3
1,23 and so on irrespective of the digits i have entered.
Is there any way possible using python for the same? I am not able to get any idea.</p>

答:
I guess this is what you are looking for:

```<code>num = 123
s = str(num)
[[x for x in i if x is not '' and ' '] for i in [list(s.partition(item)) for item in list(s+' ')]]
</code>```

Output:

```<code>[['1', '23'], ['1', '2', '3'], ['12', '3'], ['123']]
</code>```

You could also use tuples:

```<code>s = str(num)
[tuple([x for x in i if x is not '' and ' ']) for i in [list(s.partition(item)) for item in list(s+' ')]]
</code>```

Output:

```<code>[('1', '23'), ('1', '2', '3'), ('12', '3'), ('123',)]
</code>```

Body:
I guess this is what you are looking for:

num = 123
s = str(num)
[[x for x in i if x is not '' and ' '] for i in [list(s.partition(item)) for item in list(s+' ')]]

Output:

[['1', '23'], ['1', '2', '3'], ['12', '3'], ['123']]

You could also use tuples:

s = str(num)
[tuple([x for x in i if x is not '' and ' ']) for i in [list(s.partition(item)) for item in list(s+' ')]]

Output:

[('1', '23'), ('1', '2', '3'), ('12', '3'), ('123',)]


问:
Service unavailable message in IIS
I have created a sample ASP.NET website and hosted it in IIS 6.0 . It is working fine , if the identity of the defalut app pool is "local system". But when i changed the identity with some other configurable user id then it is showing as "Service Unavailable".

The following message is found in the event viewver.

"The identity of application pool 'DefaultAppPool' is invalid, so the World Wide Web Publishing Service can not create a worker process to serve the application pool.  Therefore, the application pool has been disabled."

答: Message is self-explanatory.  The selected user id isn't valid - probably due to insufficient privaledges to run the service.</p>

Title: Service unavailable message in IIS


问:
Use Axios or fetch to make self REST Api call inside Node?
I set up a few endpoints that do certain things with express. Now ideally I'd like to call them from within the node app to process some data. Is there anyway to self call the apis from within the node instance?</p>

答: Maybe you can try working with Graphql (An Open Source Query Language by Facebook). This would provide a good layer of abstraction between the application and the express server.


问:
TSQL Select into Temporary Table and add Id
I'm currently working on an T-SQL Query on SQL Server 2014.

I'm trying to Select data from 1 table into another and add an extra Id to each row.

My query looks like this:

```<code>DECLARE @TargetId = 1

SELECT * INTO #tmpProjects FROM @Projects
UNION SELECT @TargetId AS 'TargetId'
</code>```

Unfortunately this Select statement does not work...

My desired output #tmpProjects should look like this:

```<code>ProjectId |    Title    | Manager   | TargetId
----------+-------------+-----------+-----------
1         |   projectX  |   1123    |  1
2         |   projectY  |   2245    |  1
3         |   projectZ  |   3335    |  1
</code>```

In my importing table @Projects, I get the columns ProjectId, Title and Manager.

Do you know how to solve this issue? Thus to select into a temporary table and add an extra Id?

Thank you very much!!

答:
```<code>   create table #tmpProjects
     (
        ProjectId varchar(20) ,
        Title varchar(20) ,
         Manager varchar(20),
         TargetId varchar(20)
     )
DECLARE @Projects table (ProjectId varchar(20) , Title varchar(20) ,Manager varchar(20))
insert into @Projects values ('p1' , 't1' , 'm1')
insert into @Projects values ('p2' , 't2' , 'm2')
select * from @Projects

------------- **solution starts here**  ---------------
DECLARE @TargetId int
set @TargetId = 1
insert into #tmpProjects ( ProjectId ,Title , Manager ,  TargetId )
select  ProjectId ,Title , Manager , @TargetId
from @Projects

select * from #tmpProjects
</code>```

Body:
I'm currently working on an T-SQL Query on SQL Server 2014.

I'm trying to Select data from 1 table into another and add an extra Id to each row.

My query looks like this:

DECLARE @TargetId = 1

SELECT * INTO #tmpProjects FROM @Projects
UNION SELECT @TargetId AS 'TargetId'

Unfortunately this Select statement does not work...

My desired output #tmpProjects should look like this:

ProjectId |    Title    | Manager   | TargetId
----------+-------------+-----------+-----------
1         |   projectX  |   1123    |  1
2         |   projectY  |   2245    |  1
3         |   projectZ  |   3335    |  1

In my importing table @Projects, I get the columns ProjectId, Title and Manager.

Do you know how to solve this issue? Thus to select into a temporary table and add an extra Id?

Thank you very much!!


问:
Remove model inheritance and keep id in newly created autofield
I have a model which inherit from a non-abstract super model:

```<code>class Person(models.Model):
    pass

class User(Person):
    pass
</code>```

Because of a conception mistake we want to remove the Person model and copy all person data to users. The main problem concern the "id" AutoField.

The user model doesn't have any id field autocreated by django. Because of inheritance the user's primary key is "person_ptr_id".

I'm trying to make database migrations. Django migrations want to add the "id" field as AutoField but ask for a default value. I want the initial value copied from the person_ptr_id for each user record.
I also want the postgres sequence synced with values.

Have you already performed such migrations ?

答:
I finally succeed doing it with theses migrations :

1) Change django's automatic migration by commenting column deletion of person_ptr and column creation of 'id'. Then add an 'id' column as integer :

```<code>migrations.AddField(
    model_name='user',
    name='id',
    field=models.IntegerField(null=True)
),
</code>```

2) Create a new empty migration for migrating data from person to user, removing person_ptr field and change 'id' type to AutoField

```<code>def copy_persons_data(apps, schema_editor):
    User = apps.get_model("accounts", "User")
    Person = apps.get_model("persons", "Person")
    for user in User.objects.all():
        person = Person.objects.get(id=user.person_ptr_id)
        user.new_field1 = person.new_field1
        user.new_field2 = person.new_field2
        user.id = person.id
        user.save()

class Migration(migrations.Migration):

    dependencies = [
        ('accounts', '0026_auto_20170606_1524'),
    ]

    operations = [
        migrations.RunPython(copy_persons_data, reverse_code=migrations.RunPython.noop),
        migrations.RemoveField(
            model_name='user',
            name='person_ptr',
        ),
        migrations.AlterField(
            model_name='user',
            name='id',
            field=models.AutoField(auto_created=True, null=False, primary_key=True, serialize=False, verbose_name='ID'),
            preserve_default=False,
        ),
    ]
</code>```

Doing this, django will automatically create sequence for 'id' field synced with max id.

Notes :

Using user.person_ptr in datamigration function will make django refuse to save user because of unsaved person instance. So I do a get query to fetch user's person instance.

perserve_default=false is important to avoid django need a new migrations for removing the default value for the autofield

Body:
I have a model which inherit from a non-abstract super model:

class Person(models.Model):
    pass

class User(Person):
    pass

Because of a conception mistake we want to remove the Person model and copy all person data to users. The main problem concern the "id" AutoField.

The user model doesn't have any id field autocreated by django. Because of inheritance the user's primary key is "person_ptr_id".

I'm trying to make database migrations. Django migrations want to add the "id" field as AutoField but ask for a default value. I want the initial value copied from the person_ptr_id for each user record.
I also want the postgres sequence synced with values.

Have you already performed such migrations ?

Body:
I finally succeed doing it with theses migrations :

1) Change django's automatic migration by commenting column deletion of person_ptr and column creation of 'id'. Then add an 'id' column as integer :

migrations.AddField(
    model_name='user',
    name='id',
    field=models.IntegerField(null=True)
),

2) Create a new empty migration for migrating data from person to user, removing person_ptr field and change 'id' type to AutoField

def copy_persons_data(apps, schema_editor):
    User = apps.get_model("accounts", "User")
    Person = apps.get_model("persons", "Person")
    for user in User.objects.all():
        person = Person.objects.get(id=user.person_ptr_id)
        user.new_field1 = person.new_field1
        user.new_field2 = person.new_field2
        user.id = person.id
        user.save()

class Migration(migrations.Migration):

    dependencies = [
        ('accounts', '0026_auto_20170606_1524'),
    ]

    operations = [
        migrations.RunPython(copy_persons_data, reverse_code=migrations.RunPython.noop),
        migrations.RemoveField(
            model_name='user',
            name='person_ptr',
        ),
        migrations.AlterField(
            model_name='user',
            name='id',
            field=models.AutoField(auto_created=True, null=False, primary_key=True, serialize=False, verbose_name='ID'),
            preserve_default=False,
        ),
    ]

Doing this, django will automatically create sequence for 'id' field synced with max id.

Notes :

Using user.person_ptr in datamigration function will make django refuse to save user because of unsaved person instance. So I do a get query to fetch user's person instance.

perserve_default=false is important to avoid django need a new migrations for removing the default value for the autofield