问:
A fast way for this matrix transformation?
Consider the code below to make a matrix x:

```<code>x = matrix(1:18, nrow=6, byrow=T)
x
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    4    5    6
[3,]    7    8    9
[4,]   10   11   12
[5,]   13   14   15
[6,]   16   17   18
</code>```

Now I want x to be transformed to a new matrix, x1, in which each two following rows of x is taken as a new matrix, get transposed and finally all the transposed matrices are merged. This can be done by the following code:

```<code>x1 = c()
for (i in 1:(nrow(X)/2)) x1 = rbind(x1, t(x[((i-1)*2+1):(i*2),]))
x1
      [,1] [,2]
 [1,]    1    4
 [2,]    2    5
 [3,]    3    6
 [4,]    7   10
 [5,]    8   11
 [6,]    9   12
 [7,]   13   16
 [8,]   14   17
 [9,]   15   18
</code>```

I wonder if this could be done by a member of apply family, because in my case x is very big and using for loop takes very long time to be performed. I also wonder if there are any other fast code for this transformation.

Edit: My x is with 1770000 rows and 12 columns. The number of rows is a multiplication of 590, so the resulting matrix x1 should be with 36000 rows and 590 columns. I try to adjust @akrun code as:

```<code>x1 = do.call(rbind, lapply(split(x, (seq_len(nrow(x))-1) %/% 590),
     matrix, ncol=590, byrow = TRUE))
</code>```

But I receive the warning:

```<code>In FUN(X[[i]], ...) :
data length [12] is not a sub-multiple or multiple of the number of columns [590]
</code>```

Also x1 is something like:

```<code>     [,1]        [,2]        [,3]        [,4]        [,5]        [,6]
[1,] Numeric,590 Numeric,590 Numeric,590 Numeric,590 Numeric,590 Numeric,590
[2,] Numeric,590 Numeric,590 Numeric,590 Numeric,590 Numeric,590 Numeric,590
[3,] Numeric,590 Numeric,590 Numeric,590 Numeric,590 Numeric,590 Numeric,590
</code>```

Body:
Consider the code below to make a matrix x:

x = matrix(1:18, nrow=6, byrow=T)
x
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    4    5    6
[3,]    7    8    9
[4,]   10   11   12
[5,]   13   14   15
[6,]   16   17   18

Now I want x to be transformed to a new matrix, x1, in which each two following rows of x is taken as a new matrix, get transposed and finally all the transposed matrices are merged. This can be done by the following code:

x1 = c()
for (i in 1:(nrow(X)/2)) x1 = rbind(x1, t(x[((i-1)*2+1):(i*2),]))
x1
      [,1] [,2]
 [1,]    1    4
 [2,]    2    5
 [3,]    3    6
 [4,]    7   10
 [5,]    8   11
 [6,]    9   12
 [7,]   13   16
 [8,]   14   17
 [9,]   15   18

I wonder if this could be done by a member of apply family, because in my case x is very big and using for loop takes very long time to be performed. I also wonder if there are any other fast code for this transformation.

Edit: My x is with 1770000 rows and 12 columns. The number of rows is a multiplication of 590, so the resulting matrix x1 should be with 36000 rows and 590 columns. I try to adjust @akrun code as:

x1 = do.call(rbind, lapply(split(x, (seq_len(nrow(x))-1) %/% 590),
     matrix, ncol=590, byrow = TRUE))

But I receive the warning:

In FUN(X[[i]], ...) :
data length [12] is not a sub-multiple or multiple of the number of columns [590]

Also x1 is something like:

     [,1]        [,2]        [,3]        [,4]        [,5]        [,6]
[1,] Numeric,590 Numeric,590 Numeric,590 Numeric,590 Numeric,590 Numeric,590
[2,] Numeric,590 Numeric,590 Numeric,590 Numeric,590 Numeric,590 Numeric,590
[3,] Numeric,590 Numeric,590 Numeric,590 Numeric,590 Numeric,590 Numeric,590

Body:
Using array dimensions and aperm:

x = matrix(1:18, nrow=6, byrow=T)

fun <- function(x, n) {
  cols <- ncol(x)
  rows <- nrow(x)
  dim(x) <- c(n, rows / n, cols)
  x <- aperm(x, c(3, 2 , 1))
  dim(x) <- c(rows * cols / n, n)
  x
}

fun(x, 2)
#     [,1] [,2]
#[1,]    1    4
#[2,]    2    5
#[3,]    3    6
#[4,]    7   10
#[5,]    8   11
#[6,]    9   12
#[7,]   13   16
#[8,]   14   17
#[9,]   15   18

Benchmarks:

library(microbenchmark)
x <- matrix(1:180000, nrow = 60000, byrow = TRUE)
microbenchmark(
  "for" = {
    x1 = c()
    for (i in 1:(nrow(x)/2)) x1 = rbind(x1, t(x[((i-1)*2+1):(i*2),]))
    x1
  },
  array = fun(x, 2),
  split = do.call(rbind, lapply(split(x, (seq_len(nrow(x))-1) %/% 2),
                               matrix, ncol=2, byrow = TRUE)),
  indexing = {
    l <- length(x[,1])
    v1 <- x[(1:(l/2))*2,]
    v2 <- x[1+(0:(l/2 - 1))*2,]
    cbind(as.vector(t(v1)), as.vector(t(v2)))
  },
  times = 10
)
#Unit: microseconds
#    expr         min          lq         mean      median          uq         max neval cld
#     for 4313487.101 4333270.083 4557851.0186 4614434.395 4746682.820 4792838.589    10   c
#   array     655.037     690.119     730.7068     735.828     754.394     805.096    10 a
#   split  133945.299  137704.718  148001.8562  146424.032  154185.373  175473.046    10  b
#indexing    1369.482    1393.553    1803.0670    1424.027    1951.795    2984.285    10 a


来源: stackexchange

问:
Disable/Freeze view controller
I need to know how to disable all of the action from view controller.
In another words, all of the objects in the view controller will be frozen.
As a practice, I declare a button and some objects like textfield, slider, etc.
Then all of the objects cannot be used when the button pressed.

I need to disable all activities from this view controller.

答:
Great answer by Bartu. Here is the Swift version.</p>

```<code>self.view.isUserInteractionEnabled = false
</code>```

ContentLicense: CC BY-SA 3.0

Title: Disable/Freeze view controller

Body:
Great answer by Bartu. Here is the Swift version.

self.view.isUserInteractionEnabled = false


问:
Profile doesn't include certificate
Using Xcode 9.1, after building an iOS app, I try to archive it.
But I get the following error message:

Provisioning profile "MyAppProfile" doesn't include signing
  certificate "iPhone Developer: My Name (X1YZ2AB3CD)".

What is the simplest way to solve this?

答:
Open key chain in your mac and check your  development certificate...I think  your certificate is expired using which you have created your Provisioning profile..thats why it is showing "MyAppProfile" doesn't include signing certificate.

1.To solve this issue go to your developer account and download  the latest development certificate and add it to keychain and remove all expired certificates from keychain.

```<code>                                Or
</code>```

2.This issue also comes when you have multiple developer accounts in your keychain and the expired developer certificate name is same as that of active developer certificate. After removing the expired certificates, you must restart Xcode to let it reload the remaining certificates.

ContentLicense: CC BY-SA 4.0

Title: Profile doesn't include certificate

Body:
Open key chain in your mac and check your  development certificate...I think  your certificate is expired using which you have created your Provisioning profile..thats why it is showing "MyAppProfile" doesn't include signing certificate.

1.To solve this issue go to your developer account and download  the latest development certificate and add it to keychain and remove all expired certificates from keychain.

                                Or

2.This issue also comes when you have multiple developer accounts in your keychain and the expired developer certificate name is same as that of active developer certificate. After removing the expired certificates, you must restart Xcode to let it reload the remaining certificates.


问:
How to pass value to an exe and then the next button should be executed by powershell?
I have the code below which executes an exe file and then i want the path which is assigned to a variable to be copied into the text box of that exe and once it gets copied then the next button in the exe should get clicked\executed automatically by powershell.

```<code>& "D:\SOFTWARE\notepad ++.exe"
$Path="C:\Program Files"
</code>```

Basically i will be using this code for some other exe file but process would be same. So is there any way by which i can do this by using powershell?

Consider the snapshot below of the UI of application installed. If i want to pass the product key which i have declared in a variable inside the powershell after passing it to the application and then i want its Get Product Details button to be hit\Run.

答:
You should look at using SendKeys.

https://blogs.technet.microsoft.com/heyscriptingguy/2011/01/10/provide-input-to-applications-with-powershell/

Body:
I have the code below which executes an exe file and then i want the path which is assigned to a variable to be copied into the text box of that exe and once it gets copied then the next button in the exe should get clicked\executed automatically by powershell.

& "D:\SOFTWARE\notepad ++.exe"
$Path="C:\Program Files"

Basically i will be using this code for some other exe file but process would be same. So is there any way by which i can do this by using powershell?

Consider the snapshot below of the UI of application installed. If i want to pass the product key which i have declared in a variable inside the powershell after passing it to the application and then i want its Get Product Details button to be hit\Run.


问:
Adding a variable to the serialized buffer without serializing it with protobuf.net
So I have a class that I want to serialize except for a certain value "key" which
would be used to identify what class that is to deserialize it.

Now I understand that , that could be done manually but I made a class that handles serialization/deserialization and I wanted to make it as generic as possible.

Example code

```<code>[ProtoContract]
public class GeneralPacket
{
   public uint Identity;
   [ProtoMember(1, IsRequired = true)]
   public uint Arg1;
   [ProtoMember(2, IsRequired = true)]
   public uint Arg2;
   [ProtoMember(3, IsRequired = true)]
   public uint Arg3;
}
</code>```

where I want Identity to be included in stream but not serialized.

答:
It sounds like you want a "discriminator". Protobuf-net doesn't currently have any code to support that, especially on the deserialization side (simply writing the extra value is fairly easy: the hard bit is making use of it when reading). What protobuf-net does support is:

various inheritance scenarios with a common ancestor and keyed sub-types

manual usage via SerializeWithLengthPrefix allowing to to specify a numeric key when serializing, and provide a type resolver (from key to type) when deserializing

If there is a good use case for stronger discriminator support I'm happy to consider it, but that doesn't exist today. I'd need to see example intended usage and think about the implementation consequences.

Body:
So I have a class that I want to serialize except for a certain value "key" which
would be used to identify what class that is to deserialize it.

Now I understand that , that could be done manually but I made a class that handles serialization/deserialization and I wanted to make it as generic as possible.

Example code

[ProtoContract]
public class GeneralPacket
{
   public uint Identity;
   [ProtoMember(1, IsRequired = true)]
   public uint Arg1;
   [ProtoMember(2, IsRequired = true)]
   public uint Arg2;
   [ProtoMember(3, IsRequired = true)]
   public uint Arg3;
}

where I want Identity to be included in stream but not serialized.


问:
Personal Portfolio Page - Stuck with Bootstrap Grid Layout
https://codepen.io/shaan046/pen/vWmVNY

HTML code:

```<code><body>
  <div id="header" class="row">
    <div class="col-md-1 col-lg-1"><h3 id="myText">Shantanu Tomar</h3</div>
        <div class="col-md-offset-5 col-md-2 col-lg-offset-5 col-lg-2"><button class="btn btn-primary">Button1</button></div>
        <div class="col-md-2 col-lg-2"><button class="btn">Button2</button></div>
        <div class="col-md-2 col-lg-2"><button class="btn">Button3</button></div>
        </div>
  </body>
</html>
</code>```

CSS Code

```<code>#header{
  background-color:red;
}
</code>```

JS code:

```<code>$(document).ready(function() {
  $("body").addClass("container-fluid");

});
</code>```

What I want is that the text “Shantanu Tomar” and 3 buttons on screen should come in div #header in a single row. I am using Bootstrap3. Not sure how I can provide col-- tags so that the webpage is visible on Phone, tablet, Laptop in right manner? I tried using lg and md classes but the buttons are not lining up with text “Shantanu Tomar”.

Thanks for the help!!

答:
Just use col-xs-3 (since you have four elements) if you want the elements to be in a single row, and no need for jquery here.

#header {
  background-color: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<div class="container-fluid">
  <div id="header" class="row">
    <div class="col-xs-3">
      <h3 id="myText">Shantanu Tomar</h3>
    </div>
    <div class="col-xs-3">
      <button class="btn btn-primary">Button1</button>
    </div>
    <div class="col-xs-3">
      <button class="btn">Button2</button>
    </div>
    <div class="col-xs-3">
      <button class="btn">Button3</button>
    </div>
  </div>
</div></code>```

Body:
https://codepen.io/shaan046/pen/vWmVNY

HTML code:

Shantanu Tomar</h3

<button class="btn btn-primary">Button1</button>

<button class="btn">Button2</button>

<button class="btn">Button3</button>

CSS Code

#header{
  background-color:red;
}

JS code:

$(document).ready(function() {
  $("body").addClass("container-fluid");

});

What I want is that the text “Shantanu Tomar” and 3 buttons on screen should come in div #header in a single row. I am using Bootstrap3. Not sure how I can provide col-- tags so that the webpage is visible on Phone, tablet, Laptop in right manner? I tried using lg and md classes but the buttons are not lining up with text “Shantanu Tomar”.

Thanks for the help!!

Body:
Just use col-xs-3 (since you have four elements) if you want the elements to be in a single row, and no need for jquery here.

#header {
  background-color: red;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<div class="container-fluid">
  <div id="header" class="row">
    <div class="col-xs-3">
      <h3 id="myText">Shantanu Tomar</h3>
    </div>
    <div class="col-xs-3">
      <button class="btn btn-primary">Button1</button>
    </div>
    <div class="col-xs-3">
      <button class="btn">Button2</button>
    </div>
    <div class="col-xs-3">
      <button class="btn">Button3</button>
    </div>
  </div>
</div>


问:
Version Control on Mac
I am a student and my uses of source control are mostly academic (HW assignments, 2-4 person projects and so on).

Until now I have been using Subversion hosted in google code, and used the eclipse plugin to manage my repository.

Recently I heard of git, which to my understanding needs to be synced between each two collaborates each time, and something called Mercurial.

So basically my question has 3 parts:

Which source control system is recommended and what benefits does git offer? Is it worth learning it?

Which is a good free host that will support this system?

What is the best tool to manage my repository? Is using the command line better in any way than the Eclipse plugin? or is there some other software that is recommended?

If my question is to vague please comment and I'll be glad to revise it.

答:
Use the one that you are the most comfortable with,

Git is a proven distributed version control system, branching and merging are cheap, keep track of changes and merge, the only problem is that git is tracking a full project, and working on a directory of the project is difficult.

Mercurial is widely used at Google as I heard.

Compared to SVN,
- svn is a descendant of CVS and keep most of its structures and fault.
- Having 1 point of failure ( central repository ) is somewhat bad. Distributed SCM could also work on a central repository model.
- Distibuted SCM keep a repository copy in local. you push and pull to the remote server, allowing you to do a local versioning without disturbing the "central" repository, then allowing you to branch as much as you like.
- On central repository model, people are somewhat reluctant to branch and branch then merge (Merge on subversion can be a consuming task).
- Trouble with subersion, is that you cannot give per directory access right, it done at the repository level.
- Subersion do not keep track of merges.

I use subversion at work and people are often ignorant on how to manage it, distributed SCM reduce the need of an administrator if you don't need a central repository.

ContentLicense: CC BY-SA 2.5

Title: Version Control on Mac


问:
How to dynamically define this.state based on props in reactjs
My reactjs opinion poll currently has this code:

```<code>//App.js
import React, { Component } from 'react';
import './App.css';

const PollOption = ({options,selected, onChange}) => {
   return (
    <div className="pollOption">
      {options.map((choice, index) => (
        <label key={index}>
        <input type="radio"
                name="vote"
                value={choice.value}
                key={index}
                checked={selected === choice.value}
                onChange={onChange}/>
                {choice.text}
        </label>
      ))}
    </div>
   );
};

const VoteCount = ({totalVotes, choiceOneVotes, choiceTwoVotes}) =>{
  return(
      <div className="VoteCount">
          <h2>Total Votes {totalVotes}</h2>
          <ul>
            <li>Yes: {choiceOneVotes}</li>
            <li>No: {choiceTwoVotes}</li>
          </ul>
      </div>
  );
}

class OpinionPoll extends Component{
  constructor(props) {
    super(props);
    this.state = {selectedOption: '',
                  totalVotes: 0,
                  choiceOneVotes: 0,
                  choiceTwoVotes: 0}
  }

  handleClick(){
    console.log('submitted option', this.state.selectedOption);
    this.setState(prevState => {
      return {totalVotes: prevState.totalVotes + 1}
    })
   if(this.state.selectedOption === "yes"){
    this.setState(prevState => {
      return {choiceOneVotes: prevState.choiceOneVotes + 1}
    })
   }else{
    this.setState(prevState => {
      return {choiceTwoVotes: prevState.choiceTwoVotes + 1}
    })
   }
  }

  handleOnChange(e){
    console.log('selected option', e.target.name);
    this.setState({ selectedOption: e.target.value});
  }

  render(){
    return (
      <div className="poll">
        {this.props.model.question}
        <PollOption
          options={this.props.model.choices}
          onChange={(e) => this.handleOnChange(e)}
          selected={this.state.selectedOption}/>

        <button onClick={() => this.handleClick()}>Vote!</button>
        <VoteCount
          totalVotes={this.state.totalVotes}
          choiceOneVotes={this.state.choiceOneVotes}
          choiceTwoVotes={this.state.choiceTwoVotes}/>
      </div>
    );
  }
}

export default OpinionPoll;

//index.js
import React from 'react';
import {render} from 'react-dom';
import './index.css';
import OpinionPoll from './App';

var json = {
        question: 'Do you support cookies in cakes?',
        choices:
        [
           {text: "Yes", value: "yes"},
           {text: "No", value: "no"}
        ]
    }
const root = document.getElementById("root");
render(<OpinionPoll model ={json} />, root)
</code>```

My handleClick() and VoteCount component code feels inelegant since if I add the number of choices to the poll then I'd have to go and modify the state object and add another setState call. How can I make this dynamic?

答:
const PollOption = ({options,selected, onChange}) => {
  return (

      {options.map((choice, index) => (

        <input type="radio"
                name="vote"
                key={index}
                onChange={(e)=>onChange(e,index)}/>
                {choice.tag}

      ))}

   );
};

const VoteCount = ({totalVotes, options}) =>{
  return(

Total Votes {totalVotes}

            {options.map((element,index)=>(

{element.tag}: {element.count}

            ))}

  );
}

class OpinionPoll extends React.Component{
  constructor(props) {
    super(props);
    this.state = {
      selectedOption: 0,
      totalVotes: 0,
      choiceOneVotes: 0,
      choiceTwoVotes: 0,
      options: [
        {tag:"A", count:0},
        {tag:"B", count:0},
        {tag:"C", count:0},
        {tag:"D", count:0}
      ]
    }
  }

  handleClick(){
    this.setState(prevState => {
      return {totalVotes: prevState.totalVotes + 1}
    })
   const selectedIndex =   this.state.selectedOption
   const newOption = [...this.state.options]
   debugger
   newOption[selectedIndex].count += 1
    this.setState({
      options: newOption,
    })
  }

  handleOnChange(e,index){
    this.setState({
      selectedOption: index
    });
  }

  render(){
    return (

        {this.props.model.question}
        <PollOption
          options={this.state.options}
          onChange={(e,index) => this.handleOnChange(e,index)}
          selected={this.state.selectedOption}/>

        <button onClick={() => this.handleClick()}>Vote!</button>
        <VoteCount
          totalVotes={this.state.totalVotes}
           options={this.state.options}
          />

    );
  }
}

var json = {
        question: 'Do you support cookies in cakes?',
        choices:
        [
           {text: "Yes", value: "yes"},
           {text: "No", value: "no"}
        ]
    }
const root = document.getElementById("root");
ReactDOM.render(<OpinionPoll model ={json} />, root)
//ReactDOM.render(
test
, root)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div></code>```

This way dynmamic choices can be added

Body:
My reactjs opinion poll currently has this code:

//App.js
import React, { Component } from 'react';
import './App.css';

const PollOption = ({options,selected, onChange}) => {
   return (

      {options.map((choice, index) => (

        <input type="radio"
                name="vote"
                value={choice.value}
                key={index}
                checked={selected === choice.value}
                onChange={onChange}/>
                {choice.text}

      ))}

   );
};

const VoteCount = ({totalVotes, choiceOneVotes, choiceTwoVotes}) =>{
  return(

Total Votes {totalVotes}

Yes: {choiceOneVotes}

No: {choiceTwoVotes}

  );
}

class OpinionPoll extends Component{
  constructor(props) {
    super(props);
    this.state = {selectedOption: '',
                  totalVotes: 0,
                  choiceOneVotes: 0,
                  choiceTwoVotes: 0}
  }

  handleClick(){
    console.log('submitted option', this.state.selectedOption);
    this.setState(prevState => {
      return {totalVotes: prevState.totalVotes + 1}
    })
   if(this.state.selectedOption === "yes"){
    this.setState(prevState => {
      return {choiceOneVotes: prevState.choiceOneVotes + 1}
    })
   }else{
    this.setState(prevState => {
      return {choiceTwoVotes: prevState.choiceTwoVotes + 1}
    })
   }
  }

  handleOnChange(e){
    console.log('selected option', e.target.name);
    this.setState({ selectedOption: e.target.value});
  }

  render(){
    return (

        {this.props.model.question}
        <PollOption
          options={this.props.model.choices}
          onChange={(e) => this.handleOnChange(e)}
          selected={this.state.selectedOption}/>

        <button onClick={() => this.handleClick()}>Vote!</button>
        <VoteCount
          totalVotes={this.state.totalVotes}
          choiceOneVotes={this.state.choiceOneVotes}
          choiceTwoVotes={this.state.choiceTwoVotes}/>

    );
  }
}

export default OpinionPoll;

//index.js
import React from 'react';
import {render} from 'react-dom';
import './index.css';
import OpinionPoll from './App';

var json = {
        question: 'Do you support cookies in cakes?',
        choices:
        [
           {text: "Yes", value: "yes"},
           {text: "No", value: "no"}
        ]
    }
const root = document.getElementById("root");
render(<OpinionPoll model ={json} />, root)

My handleClick() and VoteCount component code feels inelegant since if I add the number of choices to the poll then I'd have to go and modify the state object and add another setState call. How can I make this dynamic?

Body:
const PollOption = ({options,selected, onChange}) => {
  return (
    <div className="pollOption">
      {options.map((choice, index) => (
        <label key={index}>
        <input type="radio"
                name="vote"
                key={index}
                onChange={(e)=>onChange(e,index)}/>
                {choice.tag}
        </label>
      ))}
    </div>
   );
};

const VoteCount = ({totalVotes, options}) =>{
  return(
      <div className="VoteCount">
          <h2>Total Votes {totalVotes}</h2>
          <ul>
            {options.map((element,index)=>(
              <li>{element.tag}: {element.count}</li>
            ))}
          </ul>
      </div>
  );
}

class OpinionPoll extends React.Component{
  constructor(props) {
    super(props);
    this.state = {
      selectedOption: 0,
      totalVotes: 0,
      choiceOneVotes: 0,
      choiceTwoVotes: 0,
      options: [
        {tag:"A", count:0},
        {tag:"B", count:0},
        {tag:"C", count:0},
        {tag:"D", count:0}
      ]
    }
  }

  handleClick(){
    this.setState(prevState => {
      return {totalVotes: prevState.totalVotes + 1}
    })
   const selectedIndex =   this.state.selectedOption
   const newOption = [...this.state.options]
   debugger
   newOption[selectedIndex].count += 1
    this.setState({
      options: newOption,
    })
  }

  handleOnChange(e,index){
    this.setState({
      selectedOption: index
    });
  }

  render(){
    return (
      <div className="poll">
        {this.props.model.question}
        <PollOption
          options={this.state.options}
          onChange={(e,index) => this.handleOnChange(e,index)}
          selected={this.state.selectedOption}/>

        <button onClick={() => this.handleClick()}>Vote!</button>
        <VoteCount
          totalVotes={this.state.totalVotes}
           options={this.state.options}
          />
      </div>
    );
  }
}

var json = {
        question: 'Do you support cookies in cakes?',
        choices:
        [
           {text: "Yes", value: "yes"},
           {text: "No", value: "no"}
        ]
    }
const root = document.getElementById("root");
ReactDOM.render(<OpinionPoll model ={json} />, root)
//ReactDOM.render(<div>test </div>, root)

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>

This way dynmamic choices can be added


问:
Replacing data on some condition in RDDs and filtering out non required RDDs
I've RDD which looks like this:

```<code>[((String, String, String), (String, String))]
</code>```

Sample data is like this:

```<code>((10,1,a),(x,3))
((10,2,b),(y,5))
((11,2,b),
((11,3,c),(z,4))
</code>```

So if the value of 2nd string inside key is 2 or 3, replace it with 2-3, if it is 1 or if the rdd is like the 3rd one, remove that rdd.

So the expected output is like this:

```<code>((10,2-3,b),(y,5))
((11,2-3,c),(z,4))
</code>```

Body:
I've RDD which looks like this:

[((String, String, String), (String, String))]

Sample data is like this:

((10,1,a),(x,3))
((10,2,b),(y,5))
((11,2,b),
((11,3,c),(z,4))

So if the value of 2nd string inside key is 2 or 3, replace it with 2-3, if it is 1 or if the rdd is like the 3rd one, remove that rdd.

So the expected output is like this:

((10,2-3,b),(y,5))
((11,2-3,c),(z,4))

Body:
Given a input data as

val rdd = spark.sparkContext.parallelize(Seq(
  (("10","1","a"),("x","3")),
  (("10","2","b"),("y","5")),
  (("11","2","b"),()),
  (("11","3","c"),("z","4"))
))

You can do the following to get your desired output as

rdd.filter(x => x._1._2 != "1").filter(x => x._2 != ()).map(x => {
  if(x._1._2 == "2" || x._1._2 == "3") ((x._1._1, "2-3", x._1._3), x._2)
  else ((x._1._1, x._1._2, x._1._3), x._2)
})

Your output would be

((10,2-3,b),(y,5))
((11,2-3,c),(z,4))

Thanks to philantrovert for pointing out that it has to be String rather than an Int.


问:
How to find missing elements in a list?
I have a target list as

```<code>target_list = ['one', 'two', 'three','four', 'five']
</code>```

And a output list as

```<code>output_list = ['two','three','four', 'five']
</code>```

The target_list is fixed, while the output_list will change depending on the output of some function. I want to find which element will be missed in the target_list based on the observation from output_list.

As in the above example, the element one is missing. I also want to count the number of missing element. Could you help me to do it in python?

答:
You can find the missing elements by using Counter. Every missing element has its occurrence.

```<code>from collections import Counter
target_list = ["one", "two", "three", "four", "five"]
output_list = ['two','three','four', 'five']
Counter(target_list)-Counter(output_list)
</code>```

Output:

```<code>Counter({'one': 1})
</code>```

Title: How to find missing elements in a list?

Body:
I have a target list as

target_list = ['one', 'two', 'three','four', 'five']

And a output list as

output_list = ['two','three','four', 'five']

The target_list is fixed, while the output_list will change depending on the output of some function. I want to find which element will be missed in the target_list based on the observation from output_list.

As in the above example, the element one is missing. I also want to count the number of missing element. Could you help me to do it in python?

Body:
You can find the missing elements by using Counter. Every missing element has its occurrence.

from collections import Counter
target_list = ["one", "two", "three", "four", "five"]
output_list = ['two','three','four', 'five']
Counter(target_list)-Counter(output_list)

Output:

Counter({'one': 1})


问:
C# / JavaScript local code in hosted web apps on Windows 10
We have a fully functional website. Now we want to develop a windows 10 app and since hosted web apps seem the quickest way we want to explore that option. I have created hosted web app for our site but can I embed any local code in the app that can communicate with code website. Like can I change the user agent string to recognize request is from hosted web app? Can I access camera from local code? I was unable to find any resources on these. Or do I have to use a webview in UWP app and load website in it? Any suggestions? </p>

答: Check this page first. If your url is defined within the app’s bounds(ACURs), then you can call windows runtime api which can help you acess to camera. But I didn't find any windows runtime API which can help you change your user agent.   </p>


问:
Can I know how much of a XML document is processed by an XSL transformation?
I have rather large input XML files that must be converted to a given format with XSL. These XSL files have been hand-crafted, and we want to make sure that every non-empty text node in the original document is taken into account, i.e. either value-of'ed, copy-of'ed, or read and concatenated with something else.

Is this even possible? I.e., is it possible to know how much of an input document is "covered" by an XSL transformation?

答:
The best I can come up with now is to add something like this to the end of your xsl:

```<code><xsl:template match="text()[normalize-space()]">
  To battle stations!
  This sneaky tag tried to escape: <xsl:value-of select="name(..)"/>
</xsl:template>
</code>```

But it really depends on <xsl:apply-templates/> being called in all the right places and probably won't do it for non-trivial stylesheets...

OwnerDisplayName: lindelof

Body:
The best I can come up with now is to add something like this to the end of your xsl:

<xsl:template match="text()[normalize-space()]">
  To battle stations!
  This sneaky tag tried to escape: <xsl:value-of select="name(..)"/>
</xsl:template>

But it really depends on <xsl:apply-templates/> being called in all the right places and probably won't do it for non-trivial stylesheets...

OwnerDisplayName: sth


问:
Oracle Insert with nodeJS causing missing keyword error
I am trying to create table and insert data into oracle db using nodeJS

below is my query code

```<code>oracledb.getConnection(
    {
        user: userId,
        password: password,
        connectString: `(DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = ${host})(PORT = ${port}))(CONNECT_DATA = (SID = ${sid})))`
    },
    function (err, connection) {
        if (err) {
            errorHandler(err);
            return;
        }
        connection.execute(
            query,
            function (err, result) {
                if (err) {
                    errorHandler(err);
                    oracleFunctions.connection.doRelease(connection, errorHandler);
                    return;
                }

                successHandler(result);
                oracleFunctions.connection.doRelease(connection, errorHandler);
            });
    });
</code>```

As a query I am using the below for creating table.

```<code>begin
execute immediate 'CREATE TABLE "table0" ("Channel" VARCHAR(128),
"Pay_mode" VARCHAR(128),
"Product_group" VARCHAR(128),
"PivotDimension" VARCHAR(128),
"Values" DECIMAL(18,6))';
execute immediate 'CREATE TABLE "table1" ("Channel" VARCHAR(128),
"Pay_mode" VARCHAR(128),
"Product_group" VARCHAR(128),
"PivotDimension" VARCHAR(128),
"Values" DECIMAL(18,6))';
end;
</code>```

I am also using the below for inserting data into the created tables.

```<code>INSERT ALL
INTO "table0" VALUES ('AM' , 'PP' , 'NP ISP Annuity' , '1' , '0.11' )
INTO "table0" VALUES ('AM' , 'PP' , 'NP ISP Annuity' , '2' , '0.26' )
SELECT * from dual;
</code>```

These queries work perfectly on Jetbrain's DataGrip.

I am executing the create table query first and when success response is returned, I am inserting rows into the tables.

However, strangely, when I execute the code, two errors occur

```<code>Error: ORA-00955: name is already used by an existing object
ORA-06512: at line 2
</code>```

for creating table and

```<code>Error: ORA-00905: missing keyword
</code>```

for inserting into the table.

Even more strangely, the table gets created fine but the insertion does not happen.

I have checked many times to make sure that the create table runs only once and insertion only runs once for each table. What could I possibly be doing wrong?

答:
There is nothing strange here. You're asked to do doubtful things and Oracle tries to complete it, no more.

First of all, when using Oracle, you should almost never to create tables dinamically. ORA-955 means that you executed your request more than once. You created tables, ok. You asked to create it again. What answer you're waiting for? Oracle said that these tables already exists. Nothing strange, I guess.

ORA-905, most probably, means that you tries to execute select * from dual as a part of INSERT ALL statement. Oracle is waiting for next INTO statement but got SELECT instead of it, so it indicates syntax error. Again, nothing strange.

Body:
I am trying to create table and insert data into oracle db using nodeJS

below is my query code

oracledb.getConnection(
    {
        user: userId,
        password: password,
        connectString: `(DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = ${host})(PORT = ${port}))(CONNECT_DATA = (SID = ${sid})))`
    },
    function (err, connection) {
        if (err) {
            errorHandler(err);
            return;
        }
        connection.execute(
            query,
            function (err, result) {
                if (err) {
                    errorHandler(err);
                    oracleFunctions.connection.doRelease(connection, errorHandler);
                    return;
                }

                successHandler(result);
                oracleFunctions.connection.doRelease(connection, errorHandler);
            });
    });

As a query I am using the below for creating table.

begin
execute immediate 'CREATE TABLE "table0" ("Channel" VARCHAR(128),
"Pay_mode" VARCHAR(128),
"Product_group" VARCHAR(128),
"PivotDimension" VARCHAR(128),
"Values" DECIMAL(18,6))';
execute immediate 'CREATE TABLE "table1" ("Channel" VARCHAR(128),
"Pay_mode" VARCHAR(128),
"Product_group" VARCHAR(128),
"PivotDimension" VARCHAR(128),
"Values" DECIMAL(18,6))';
end;

I am also using the below for inserting data into the created tables.

INSERT ALL
INTO "table0" VALUES ('AM' , 'PP' , 'NP ISP Annuity' , '1' , '0.11' )
INTO "table0" VALUES ('AM' , 'PP' , 'NP ISP Annuity' , '2' , '0.26' )
SELECT * from dual;

These queries work perfectly on Jetbrain's DataGrip.

I am executing the create table query first and when success response is returned, I am inserting rows into the tables.

However, strangely, when I execute the code, two errors occur

Error: ORA-00955: name is already used by an existing object
ORA-06512: at line 2

for creating table and

Error: ORA-00905: missing keyword

for inserting into the table.

Even more strangely, the table gets created fine but the insertion does not happen.

I have checked many times to make sure that the create table runs only once and insertion only runs once for each table. What could I possibly be doing wrong?


问:
Cannot stop JQuery event
Here is the simplified scenario

$(function() {
  $('#btn').on('click', function() {
    alert('JQuery')
  })
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" id='btn' value="Button" onclick="alert('onclick');return false;" /></code>```

two alerts are called even though I have returned false. How can I prevent script written inside ready event?

答:
You should stop the alert('click') before you call the alert function.
Usually it can be done with event.preventDefault() used within a function

$(function() {
  $('#btn').on('click', function() {
    alert('JQuery')
  })
  function alert_first(event){
      event.stopPropagation();
  }

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" id='btn' value="Button" onclick="alert_first();alert('click);"/></code>```

Title: Cannot stop JQuery event

Body:
Here is the simplified scenario

$(function() {
  $('#btn').on('click', function() {
    alert('JQuery')
  })
});

<input type="button" id='btn' value="Button" onclick="alert('onclick');return false;" />

two alerts are called even though I have returned false. How can I prevent script written inside ready event?

Body:
You should stop the alert('click') before you call the alert function.
Usually it can be done with event.preventDefault() used within a function

$(function() {
  $('#btn').on('click', function() {
    alert('JQuery')
  })
  function alert_first(event){
      event.stopPropagation();
  }

});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" id='btn' value="Button" onclick="alert_first();alert('click);"/>


问:
JAVA gives me wrong Date Results on Several devices
I have a weird problem I used Java to get a current date but I am getting different results on several devices, on one correct & on another wrong.
Here is my code:

```<code> public String getCurrentDate() {
     /// get date
     DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH);
     dateFormat.setTimeZone(TimeZone.getTimeZone("Asia/Tehran"));
     Date date = new Date();
     System.out.println(dateFormat.format(date)); //2017-11-13 18:20:46 correct time is 11am
     return dateFormat.format(date);
}
</code>```

On the device that gives the wrong result I set automatic time zone use network-provided time zone & time of the device is correct.

答:
Are testing with real devices?

You can also try the Calendar Class that are from Android. for more info visit (https://developer.android.com/reference/java/util/Calendar.html)

Check the Example bellow:

```<code>  Calendar current_time_cal = Calendar.getInstance();
  current_time_cal.setTimeZone(TimeZone.getTimeZone("Asia/Tehran"));
  int hours = current_time.get(Calendar.HOUR);
  int current_am_pm = current_time.get(Calendar.AM_PM);
  current_time_cal.set(Calendar.HOUR_OF_DAY, (hours == 0)? 12 : hours);
  current_time_cal.set(Calendar.MINUTE, current_time.get(Calendar.MINUTE));
  current_time_cal.set(Calendar.SECOND, 0);
</code>```

Body:
I have a weird problem I used Java to get a current date but I am getting different results on several devices, on one correct & on another wrong.
Here is my code:

 public String getCurrentDate() {
     /// get date
     DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH);
     dateFormat.setTimeZone(TimeZone.getTimeZone("Asia/Tehran"));
     Date date = new Date();
     System.out.println(dateFormat.format(date)); //2017-11-13 18:20:46 correct time is 11am
     return dateFormat.format(date);
}

On the device that gives the wrong result I set automatic time zone use network-provided time zone & time of the device is correct.

Body:
Are testing with real devices?

You can also try the Calendar Class that are from Android. for more info visit (https://developer.android.com/reference/java/util/Calendar.html)

Check the Example bellow:

  Calendar current_time_cal = Calendar.getInstance();
  current_time_cal.setTimeZone(TimeZone.getTimeZone("Asia/Tehran"));
  int hours = current_time.get(Calendar.HOUR);
  int current_am_pm = current_time.get(Calendar.AM_PM);
  current_time_cal.set(Calendar.HOUR_OF_DAY, (hours == 0)? 12 : hours);
  current_time_cal.set(Calendar.MINUTE, current_time.get(Calendar.MINUTE));
  current_time_cal.set(Calendar.SECOND, 0);


答:
You need to use event.stopImmediatePropagation() to prevents other listeners of the same event from being called.

$(function() {
  $('#btn').on('click', function() {
    alert('JQuery')
  })
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" id='btn' value="Button" onclick="alert('onclick');event.stopImmediatePropagation();" /></code>```

Title: Cannot stop JQuery event

Body:
You need to use event.stopImmediatePropagation() to prevents other listeners of the same event from being called.

$(function() {
  $('#btn').on('click', function() {
    alert('JQuery')
  })
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" id='btn' value="Button" onclick="alert('onclick');event.stopImmediatePropagation();" />


问:
Detaching Rows in Pivot Table - Laravel
I have a pivot table country_team with data in this form

country_team

```<code> country_id    team_id
     1            1
     1            2
</code>```

Country

```<code>   id    name
    1    Spain
</code>```

Team

```<code> id     name
  1     Barcelona
  2     Real Madrid
</code>```

In my table, i have it displayed in this form

Table

```<code> Country_id    Team
     1         Barcelona
     1         Real Madrid
</code>```

Now, i want to detach real Madrid from the row but how can get the id of real madrid or get the name Real Madrid to detach it. I cannot delete using country_id since it will delete all teams belonging to that particular country .

Controller

```<code>public function index()
{
    $countries = Country::where('id',Auth::user()->id)->get();

    return view('admin.order.index',compact('orders'));
}

public function deleteTeam()
{
    $get_country_id = Country::findOrFail($id);
    $get_country_id->teams()->detach();
}
</code>```

HTML

```<code><tbody>
    @foreach($countries as $country)
        @foreach($country->teams as $team)
        <tr>
            <td>{{$country->id }}</td>
            <td>{{ $team->name}}</td>
        </tr>
        @endforeach
    @endforeach
</tbody>
</code>```

答:
Well You can simply pass country_id and  team_id and update your delete team as such.</p>

```<code>public function deleteTeam(Scountry_id,$team_id)
{
    $country = Country::findOrFail($country_id);
    $country->teams()->detach($team_id);
}
</code>```

Title: Detaching Rows in Pivot Table - Laravel

Body:
I have a pivot table country_team with data in this form

country_team

 country_id    team_id
     1            1
     1            2

Country

   id    name
    1    Spain

Team

 id     name
  1     Barcelona
  2     Real Madrid

In my table, i have it displayed in this form

Table

 Country_id    Team
     1         Barcelona
     1         Real Madrid

Now, i want to detach real Madrid from the row but how can get the id of real madrid or get the name Real Madrid to detach it. I cannot delete using country_id since it will delete all teams belonging to that particular country .

Controller

public function index()
{
    $countries = Country::where('id',Auth::user()->id)->get();

    return view('admin.order.index',compact('orders'));
}

public function deleteTeam()
{
    $get_country_id = Country::findOrFail($id);
    $get_country_id->teams()->detach();
}

HTML

    @foreach($countries as $country)
        @foreach($country->teams as $team)

            {{$country->id }}
            {{ $team->name}}

        @endforeach
    @endforeach

Body:
Well You can simply pass country_id and  team_id and update your delete team as such.

public function deleteTeam(Scountry_id,$team_id)
{
    $country = Country::findOrFail($country_id);
    $country->teams()->detach($team_id);
}


答:
Try this:</p>

```<code>Calendar c = Calendar.getInstance();
System.out.println("Current time: " + c.getTime());

SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy");
String formattedDate = df.format(c.getTime());
</code>```

Title: JAVA gives me wrong Date Results on Several devices

Body:
Try this:

Calendar c = Calendar.getInstance();
System.out.println("Current time: " + c.getTime());

SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy");
String formattedDate = df.format(c.getTime());


答:
Why do not use a
 ?

Something like this :

<button class="btn btn-primary">Button1</button>

<button class="btn btn-primary">Button2</button>

<button class="btn btn-primary">Button3</button>

```

Title: Personal Portfolio Page - Stuck with Bootstrap Grid Layout

Body:
https://codepen.io/shaan046/pen/vWmVNY

HTML code:

Shantanu Tomar</h3

<button class="btn btn-primary">Button1</button>

<button class="btn">Button2</button>

<button class="btn">Button3</button>

CSS Code

#header{
  background-color:red;
}

JS code:

$(document).ready(function() {
  $("body").addClass("container-fluid");

});

What I want is that the text “Shantanu Tomar” and 3 buttons on screen should come in div #header in a single row. I am using Bootstrap3. Not sure how I can provide col-- tags so that the webpage is visible on Phone, tablet, Laptop in right manner? I tried using lg and md classes but the buttons are not lining up with text “Shantanu Tomar”.

Thanks for the help!!

Body:
Why do not use a <ul> ?

Something like this :

<div id="header" class="row">
  <ul class="list-inline">
    <li><button class="btn btn-primary">Button1</button></li>
    <li><button class="btn btn-primary">Button2</button></li>
    <li><button class="btn btn-primary">Button3</button></li>
  </ul>
</div>


问:
Automatically parse json attributes into a new object
I have incoming data in json format looking like this:

Raw data:

```<code>{
  "data": [{
      "id": "Device_6",
      "type": "SensingDevice",
      "Battery": {
        "type": "Number",
        "value": "4.08",
        "metadata": {
          "timestamp": {
            "type": "DateTime",
            "value": "2017-11-09T14:49:02.00Z"
          },
          "unit": {
            "type": "Text",
            "value": "voltage"
          }
        }
      },
      "DO": {
        "type": "Number",
        "value": "5.71",
        "metadata": {
          "timestamp": {
            "type": "DateTime",
            "value": "2017-11-09T14:49:02.00Z"
          },
          "unit": {
            "type": "Text",
            "value": "mg/l"
          }
        }
      },
      "Humidity": {
        "type": "Number",
        "value": "57.30",
        "metadata": {
          "timestamp": {
            "type": "DateTime",
            "value": "2017-11-09T14:49:02.00Z"
          },
          "unit": {
            "type": "Text",
            "value": "percent"
          }
        }
      },
      "PH": {
        "type": "Number",
        "value": "14.00",
        "metadata": {
          "timestamp": {
            "type": "DateTime",
            "value": "2017-11-09T14:49:02.00Z"
          }
        }
      },
      "temperature": {
        "type": "Number",
        "value": "41.00",
        "metadata": {
          "timestamp": {
            "type": "DateTime",
            "value": "2017-11-09T14:49:02.00Z"
          },
          "unit": {
            "type": "Text",
            "value": "celsius"
          }
        }
      },
      "waterTemperature": {
        "type": "Number",
        "value": "29.69",
        "metadata": {
          "timestamp": {
            "type": "DateTime",
            "value": "2017-11-09T14:49:02.00Z"
          },
          "unit": {
            "type": "Text",
            "value": "celsius"
          }
        }
      }
    }
  ],
  "subscriptionId": "59d5eeec4f3db340052d618c"
}
</code>```

For a specific application purpose, i need to transform this complex JSON into a simple key:value format.

So I'm using this code in node js with node-json-transform package:

```<code> var map_data = {
           list:'data',
            item :  { Battery: 'Battery.value',
                        DO: 'DO.value',
                        Humidity: 'Humidity.value',
                        PH: 'PH.value',
                        temperature: 'temperature.value',
                        waterTemperature: 'waterTemperature.value', },
    };
   console.log (map_data)

         var dataTransform = DataTransform(data, map_data);
         var data_result = dataTransform.transform();
</code>```

And the output looks like what I want :

```<code>[ { Battery: '4.08',
    DO: '5.71',
    Humidity: '57.30',
    PH: '14.00',
    temperature: '41.00',
    waterTemperature: '29.69' } ]
</code>```

But now, what if I don't know the name of the attributes?
So I tried to make it automatic to discover the keys:

```<code>var keys = Object.keys(data.data[0]);
var keysvalues = '';
    for (i=2; i < keys.length; i++) {
        keysvalues += keys[i]+':"'+ keys[i] + '.value",';
    }
var item = '{'+keysvalues+'}';
var map_data = {
            list:"data",
            item,
    };
 var dataTransform = DataTransform(data, map_data);
 var data_result = dataTransform.transform();
</code>```

This is not working because the object map_data.item is a "fake" object where I manually added the {}, so it is recognized like a string :

```<code>console.log(map_data)
{ list: 'data',
  item: '{Battery:"Battery.value",DO:"DO.value",Humidity:"Humidity.value",PH:"PH.value",temperature:"temperature.value",waterTemperature:"waterTemperature.value",}' }
</code>```

Can you help me on how to make the item object a real object so I can parse the JSON automatically in the format I want?

答:
Raw JavaScript Code
can change if constrain to handle array it will not handle array if your DATA field wasn't Array it work properly

if your json have array in it it will very complex(not about code just about wat u want as a result).
another proplem is key : value format will override many of your information

BUT if you want do it any way you can simply do :

```<code>  function ToSimpleJson(json , result , prefix)
{
   for(key in json)
   {
       if(typeof json[key]!="object" )
           result[prefix+key] = json[key]
       else if (!json[key].length) // Object
           ToSimpleJson(json[key], result , (key+"."))
       else // Array (But will Override if have more than 1 index)
       {
           json[key].forEach(function (x)
           {
               ToSimpleJson(x, result , (key + "."))
           })

       }
   }

return result
}
</code>```

and call function with empty result and empty prefix

```<code>ToSimpleJson(json , {} , "")
</code>```

and result is :

```<code>{
    "data.id" : "Device_6",
    "data.type" : "SensingDevice",
    "Battery.type" : "Number",
    "Battery.value" : "4.08",
    "timestamp.type" : "DateTime",
    "timestamp.value" : "2017-11-09T14:49:02.00Z",
    "unit.type" : "Text",
    "unit.value" : "celsius",
    "DO.type" : "Number",
    "DO.value" : "5.71",
    "Humidity.type" : "Number",
    "Humidity.value" : "57.30",
    "PH.type" : "Number",
    "PH.value" : "14.00",
    "temperature.type" : "Number",
    "temperature.value" : "41.00",
    "waterTemperature.type" : "Number",
    "waterTemperature.value" : "29.69",
    "subscriptionId" : "59d5eeec4f3db340052d618c"
}
</code>```

Body:
I have incoming data in json format looking like this:

Raw data:

{
  "data": [{
      "id": "Device_6",
      "type": "SensingDevice",
      "Battery": {
        "type": "Number",
        "value": "4.08",
        "metadata": {
          "timestamp": {
            "type": "DateTime",
            "value": "2017-11-09T14:49:02.00Z"
          },
          "unit": {
            "type": "Text",
            "value": "voltage"
          }
        }
      },
      "DO": {
        "type": "Number",
        "value": "5.71",
        "metadata": {
          "timestamp": {
            "type": "DateTime",
            "value": "2017-11-09T14:49:02.00Z"
          },
          "unit": {
            "type": "Text",
            "value": "mg/l"
          }
        }
      },
      "Humidity": {
        "type": "Number",
        "value": "57.30",
        "metadata": {
          "timestamp": {
            "type": "DateTime",
            "value": "2017-11-09T14:49:02.00Z"
          },
          "unit": {
            "type": "Text",
            "value": "percent"
          }
        }
      },
      "PH": {
        "type": "Number",
        "value": "14.00",
        "metadata": {
          "timestamp": {
            "type": "DateTime",
            "value": "2017-11-09T14:49:02.00Z"
          }
        }
      },
      "temperature": {
        "type": "Number",
        "value": "41.00",
        "metadata": {
          "timestamp": {
            "type": "DateTime",
            "value": "2017-11-09T14:49:02.00Z"
          },
          "unit": {
            "type": "Text",
            "value": "celsius"
          }
        }
      },
      "waterTemperature": {
        "type": "Number",
        "value": "29.69",
        "metadata": {
          "timestamp": {
            "type": "DateTime",
            "value": "2017-11-09T14:49:02.00Z"
          },
          "unit": {
            "type": "Text",
            "value": "celsius"
          }
        }
      }
    }
  ],
  "subscriptionId": "59d5eeec4f3db340052d618c"
}

For a specific application purpose, i need to transform this complex JSON into a simple key:value format.

So I'm using this code in node js with node-json-transform package:

 var map_data = {
           list:'data',
            item :  { Battery: 'Battery.value',
                        DO: 'DO.value',
                        Humidity: 'Humidity.value',
                        PH: 'PH.value',
                        temperature: 'temperature.value',
                        waterTemperature: 'waterTemperature.value', },
    };
   console.log (map_data)

         var dataTransform = DataTransform(data, map_data);
         var data_result = dataTransform.transform();

And the output looks like what I want :

[ { Battery: '4.08',
    DO: '5.71',
    Humidity: '57.30',
    PH: '14.00',
    temperature: '41.00',
    waterTemperature: '29.69' } ]

But now, what if I don't know the name of the attributes?
So I tried to make it automatic to discover the keys:

var keys = Object.keys(data.data[0]);
var keysvalues = '';
    for (i=2; i < keys.length; i++) {
        keysvalues += keys[i]+':"'+ keys[i] + '.value",';
    }
var item = '{'+keysvalues+'}';
var map_data = {
            list:"data",
            item,
    };
 var dataTransform = DataTransform(data, map_data);
 var data_result = dataTransform.transform();

This is not working because the object map_data.item is a "fake" object where I manually added the {}, so it is recognized like a string :

console.log(map_data)
{ list: 'data',
  item: '{Battery:"Battery.value",DO:"DO.value",Humidity:"Humidity.value",PH:"PH.value",temperature:"temperature.value",waterTemperature:"waterTemperature.value",}' }

Can you help me on how to make the item object a real object so I can parse the JSON automatically in the format I want?

Body:
Raw JavaScript Code
can change if constrain to handle array it will not handle array if your DATA field wasn't Array it work properly

if your json have array in it it will very complex(not about code just about wat u want as a result).
another proplem is key : value format will override many of your information

BUT if you want do it any way you can simply do :

  function ToSimpleJson(json , result , prefix)
{
   for(key in json)
   {
       if(typeof json[key]!="object" )
           result[prefix+key] = json[key]
       else if (!json[key].length) // Object
           ToSimpleJson(json[key], result , (key+"."))
       else // Array (But will Override if have more than 1 index)
       {
           json[key].forEach(function (x)
           {
               ToSimpleJson(x, result , (key + "."))
           })

       }
   }

return result
}

and call function with empty result and empty prefix

ToSimpleJson(json , {} , "")

and result is :

{
    "data.id" : "Device_6",
    "data.type" : "SensingDevice",
    "Battery.type" : "Number",
    "Battery.value" : "4.08",
    "timestamp.type" : "DateTime",
    "timestamp.value" : "2017-11-09T14:49:02.00Z",
    "unit.type" : "Text",
    "unit.value" : "celsius",
    "DO.type" : "Number",
    "DO.value" : "5.71",
    "Humidity.type" : "Number",
    "Humidity.value" : "57.30",
    "PH.type" : "Number",
    "PH.value" : "14.00",
    "temperature.type" : "Number",
    "temperature.value" : "41.00",
    "waterTemperature.type" : "Number",
    "waterTemperature.value" : "29.69",
    "subscriptionId" : "59d5eeec4f3db340052d618c"
}


问:
How to make pop up modal shows once a day or hours
I know there is a lot of answers about this but i cant seem to implement it with my code. What i want to do is when the user open the homepage a recommendation pop up will only show once a day or hours. Any help and suggestion is greatly appreciated.

This is the code in launching the pop up modal on page load.

```<code><?php
    if(mysqli_num_rows($check_ip) > 0 )
    {
    ?>
    <script type="text/javascript">
            $(document).ready(function()
            {
                $("#myModal").modal('show');
            });
        </script>
    <?php
    }
    ?>
</code>```

This is the code for pop up modal

```<code><div id="myModal" class="modal">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                    <h4 class="modal-title">Welcome back! Here's our recommended speakers for you.</h4>
                </div>
                <div class="modal-body">

    <?php
    $user_ip = $_SERVER['REMOTE_ADDR'];

    $check_ip =  mysqli_query($conn, "SELECT ip_address FROM reservations WHERE ip_address = '$user_ip'");

    $history_data = mysqli_query($conn, "SELECT * FROM reservations WHERE ip_address = '$user_ip'");
    $row = mysqli_fetch_array($history_data);
    $topic = $row['topic'];
    $ip_address = $row['ip_address'];

    $select_speakers = mysqli_query($conn, "SELECT * FROM speakers WHERE speaker_specialization1 = '$topic' OR speaker_specialization2 = '$topic' OR speaker_specialization3 = '$topic' ORDER BY speaker_reservedcount DESC LIMIT 3");
    while($row = mysqli_fetch_array($select_speakers))
    {
        echo '
        <a href="speakerProfile.php?id='.$row["id"].'">
                        <div class=" col-sm-4 ">
                            <div class="thumbnail"><img class="speakers-image" src="img/'.$row["speaker_image"].'" style="height:150px; min-width:100%;"/>
                                <div class="caption" style="max-height:270px; min-width:100%" >
                                <center>
                                    <h3 class="speakers-name" style="font-weight:bold; margin: 2px 10px -6px 10px;">'.$row["speaker_fullname"].'</h3>
                                    <hr>
                                    <div class="speaker-topics" style="margin-top:-20px;">
                                        <p style="text-transform: capitalize;">'.$row["speaker_specialization1"].'</p>
                                    </div>
                                    <div class="speaker-topics">
                                        <p style="text-transform: capitalize;">'.$row["speaker_specialization2"].'</p>
                                    </div>
                                    <div class="speaker-topics">
                                        <p style="text-transform: capitalize;">'.$row["speaker_specialization3"].'</p>
                                    </div>
                                    <hr>
                                    <p class="speakers-name" style="margin:-10px 0px 5  px 0px;">Reserved Count: '.$row["speaker_reservedcount"].'</p>
                                </center>
                                </div>
                            </div>
                        </div>
        </a>
        ';
    }
?>
                </div>
            </div>
        </div>
    </div>
</code>```

答:
i know this is not much but it might help somebody who has a problem like this. This how i do it</p>

```<code><?php
    if(mysqli_num_rows($check_ip) > 0 && isset($_SESSION["popUp"]) == false)
    {
    $_SESSION["popUp"] = "true";
    ?>
    <script type="text/javascript">
            $(document).ready(function()
            {
                $("#myModal").modal('show');
            });
        </script>
    <?php
    }
    ?>
</code>```

Body:
I know there is a lot of answers about this but i cant seem to implement it with my code. What i want to do is when the user open the homepage a recommendation pop up will only show once a day or hours. Any help and suggestion is greatly appreciated.

This is the code in launching the pop up modal on page load.

<?php
    if(mysqli_num_rows($check_ip) > 0 )
    {
    ?>

    <?php
    }
    ?>

This is the code for pop up modal

                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Welcome back! Here's our recommended speakers for you.

    <?php
    $user_ip = $_SERVER['REMOTE_ADDR'];

    $check_ip =  mysqli_query($conn, "SELECT ip_address FROM reservations WHERE ip_address = '$user_ip'");

    $history_data = mysqli_query($conn, "SELECT * FROM reservations WHERE ip_address = '$user_ip'");
    $row = mysqli_fetch_array($history_data);
    $topic = $row['topic'];
    $ip_address = $row['ip_address'];

    $select_speakers = mysqli_query($conn, "SELECT * FROM speakers WHERE speaker_specialization1 = '$topic' OR speaker_specialization2 = '$topic' OR speaker_specialization3 = '$topic' ORDER BY speaker_reservedcount DESC LIMIT 3");
    while($row = mysqli_fetch_array($select_speakers))
    {
        echo '

'.$row["speaker_fullname"].'

'.$row["speaker_specialization1"].'

'.$row["speaker_specialization2"].'

'.$row["speaker_specialization3"].'

Reserved Count: '.$row["speaker_reservedcount"].'

        ';
    }
?>

Body:
i know this is not much but it might help somebody who has a problem like this. This how i do it

<?php
    if(mysqli_num_rows($check_ip) > 0 && isset($_SESSION["popUp"]) == false)
    {
    $_SESSION["popUp"] = "true";
    ?>
    <script type="text/javascript">
            $(document).ready(function()
            {
                $("#myModal").modal('show');
            });
        </script>
    <?php
    }
    ?>


问:
Matching Id from a file
I have a inputId file as

```<code>input_abc,input_xyz,input_def
input_def,input_qwe
input_ghf,input_tgf,input_xyz
</code>```

I have other matcherFile as

```<code>input_xyz
input_def
</code>```

I want to filter all ids in matcherFile from inputId file, So output is

```<code>input_abc
input_qwe
input_ghf,input_tgf
</code>```

Wat I have written as

```<code>inputFileName="$1"
matchFile="$2"
outputFile="$3"

matchFileIds=$(cat $matchFile);
echo "$matchFileIds"

for IDS in $(cat $inputFileName);
do
    for i in $(echo $IDS | sed "s/,/ /g")
    do
    # here we get each id in inputfile separately,
    # I want to check if $i belongs id in  matcherFile
    echo "$i"

    done
done
</code>```

答:
Here's another possible solution.</p>

```<code>$ cat input.txt
input_abc,input_xyz,input_def
input_def,input_qwe
input_ghf,input_tgf,input_xyz

$ cat filter.txt
input_xyz
input_def

$ cat filter.sh
#!/bin/sh
input_file=input.txt
filter_file=filter.txt

for filter in $(cat $filter_file)
do
        cmd="$cmd|sed -e's/$filter//g'"
done
cmd="cat ${input_file} ${cmd} | sed -e's/,,//g'| sed -e's/^,//g'| sed -e's/,$//g'"
echo $cmd > ./tmp_script.sh
bash ./tmp_script.sh

$ ./filter.sh
input_abc
input_qwe
input_ghf,input_tgf
</code>```

Title: Matching Id from a file

Body:
I have a inputId file as

input_abc,input_xyz,input_def
input_def,input_qwe
input_ghf,input_tgf,input_xyz

I have other matcherFile as

input_xyz
input_def

I want to filter all ids in matcherFile from inputId file, So output is

input_abc
input_qwe
input_ghf,input_tgf

Wat I have written as

inputFileName="$1"
matchFile="$2"
outputFile="$3"

matchFileIds=$(cat $matchFile);
echo "$matchFileIds"

for IDS in $(cat $inputFileName);
do
    for i in $(echo $IDS | sed "s/,/ /g")
    do
    # here we get each id in inputfile separately,
    # I want to check if $i belongs id in  matcherFile
    echo "$i"

    done
done

Body:
Here's another possible solution.

$ cat input.txt
input_abc,input_xyz,input_def
input_def,input_qwe
input_ghf,input_tgf,input_xyz

$ cat filter.txt
input_xyz
input_def

$ cat filter.sh
#!/bin/sh
input_file=input.txt
filter_file=filter.txt

for filter in $(cat $filter_file)
do
        cmd="$cmd|sed -e's/$filter//g'"
done
cmd="cat ${input_file} ${cmd} | sed -e's/,,//g'| sed -e's/^,//g'| sed -e's/,$//g'"
echo $cmd > ./tmp_script.sh
bash ./tmp_script.sh

$ ./filter.sh
input_abc
input_qwe
input_ghf,input_tgf


问:
ASP.NET LINQ query for filter and loop through multiple tables
I have two separate domain model classes for "App" and "AgeGroup". The App Class is containing few basic integer and strings properties and so does the AgeGroup class.

What I'm trying to achieve is JSON output of all the apps by AppOrder with their properties, nested in their associated AgeGroups that are ordered by their GroupOrder property

Required Example JSON Output Structure

```<code>"Looped List of Age Groups, order by GroupOrder"
      "Looped List of Apps, order by App Order"

 First Age Group
    Foo App Name
        Foo App Icon
        Foo App Store URL
    Bar App Name
        Bar App Icon
        Bar App Store URL
 Second Age Group
    Tur App Name
        Tur App Icon
        Tur App Store URL
    Puk App Name
        Puk App Icon
        Puk App Store URL
  and so on...
</code>```

My Approach so far:

Here is what I have in my "App.cs" Class

```<code>public int Id { get; set; }
public string Name { get; set; }
public string StoreURL { get; set; }
public int AppOrder { get; set; }
public string AppIcon { get; set; }

public AgeGroup AgeGroup { get; set; }    // Linked to AgeGroup Class
public int AgeGroupId { get; set; }
</code>```

In the "AgeGroup.cs" Class, I have following

```<code>public int Id { get; set; }
public int GroupOrder { get; set; }
public string Name { get; set; }
</code>```

and in the AppsController.cs

```<code>    [HttpGet]
    [Route("api/groups")]

    public IHttpActionResult AppsByGroup ()
    {
        var apps = _context.Apps
            .OrderBy(a => a.AppOrder)
            .Select(a => new
            {
                a.Name,
                a.StoreURL,
                a.AppIcon,
                AgeGroup = a.AgeGroup.Name
            }).GroupBy(a => a.AgeGroup);

       return Json(apps);
    }
</code>```

It gives me correct output but without AgeGroup Names.

```<code>[
  [ // Here I wanted the AgeGroup Name from the AgeGroup Table (Group A)
    {
        "Name": "First App for Group A",
        "StoreURL": "some string",
        "AppIcon": "icon string",
        "AgeGroup": "Group A"
    },
    {
        "Name": "2nd App Group A",
        "StoreURL": "aslfdj",
        "AppIcon": "asljf",
        "AgeGroup": "Group A"
    },
    {
        "Name": "3rd App Group A",
        "StoreURL": "aslfdj",
        "AppIcon": "alsfdj",
        "AgeGroup": "Group A"
    }
  ],
  [ // Here I wanted the AgeGroup Name from the AgeGroup Table (Group B)
    {
        "Name": "1st App GroupB",
        "StoreURL": "alsfdj",
        "AppIcon": "alsdjf",
        "AgeGroup": "Group B"
    },

//and so on...
</code>```

答:
I suggest to make the code a bit easier to understand and debug, you start with view models to represent the data you want to return

```<code>public class AgeGroupVM
{
    public string Name { get; set; }
    public IEnumerable<AppVM> Apps { get; set; }
}
public class AppVM
{
    public string Name { get; set; }
    public string StoreURL { get; set; }
    public string AppIcon { get; set; }
}
</code>```

Then you need to order the data and group it by the Name property of AgeGroup

```<code>var data = _context.Apps
    .OrderBy(x => x.AgeGroup.GroupOrder) // order by AgeGroup first
    .ThenBy(x => x.AppOrder) // then by the AppOrder
    .GroupBy(x => x.AgeGroup.Name) // group by the AgeGroup
    .Select(x => new AgeGroupVM // project into the view model
    {
        Name = x.Key,
        Apps = x.Select(y => new AppVM
        {
            Name = y.Name,
            StoreURL = y.StoreURL,
            AppIcon = y.AppIcon
        })
    });
return Json(data);
</code>```

Body:
I have two separate domain model classes for "App" and "AgeGroup". The App Class is containing few basic integer and strings properties and so does the AgeGroup class.

What I'm trying to achieve is JSON output of all the apps by AppOrder with their properties, nested in their associated AgeGroups that are ordered by their GroupOrder property

Required Example JSON Output Structure

"Looped List of Age Groups, order by GroupOrder"
      "Looped List of Apps, order by App Order"

 First Age Group
    Foo App Name
        Foo App Icon
        Foo App Store URL
    Bar App Name
        Bar App Icon
        Bar App Store URL
 Second Age Group
    Tur App Name
        Tur App Icon
        Tur App Store URL
    Puk App Name
        Puk App Icon
        Puk App Store URL
  and so on...

My Approach so far:

Here is what I have in my "App.cs" Class

public int Id { get; set; }
public string Name { get; set; }
public string StoreURL { get; set; }
public int AppOrder { get; set; }
public string AppIcon { get; set; }

public AgeGroup AgeGroup { get; set; }    // Linked to AgeGroup Class
public int AgeGroupId { get; set; }

In the "AgeGroup.cs" Class, I have following

public int Id { get; set; }
public int GroupOrder { get; set; }
public string Name { get; set; }

and in the AppsController.cs

    [HttpGet]
    [Route("api/groups")]

    public IHttpActionResult AppsByGroup ()
    {
        var apps = _context.Apps
            .OrderBy(a => a.AppOrder)
            .Select(a => new
            {
                a.Name,
                a.StoreURL,
                a.AppIcon,
                AgeGroup = a.AgeGroup.Name
            }).GroupBy(a => a.AgeGroup);

       return Json(apps);
    }

It gives me correct output but without AgeGroup Names.

[
  [ // Here I wanted the AgeGroup Name from the AgeGroup Table (Group A)
    {
        "Name": "First App for Group A",
        "StoreURL": "some string",
        "AppIcon": "icon string",
        "AgeGroup": "Group A"
    },
    {
        "Name": "2nd App Group A",
        "StoreURL": "aslfdj",
        "AppIcon": "asljf",
        "AgeGroup": "Group A"
    },
    {
        "Name": "3rd App Group A",
        "StoreURL": "aslfdj",
        "AppIcon": "alsfdj",
        "AgeGroup": "Group A"
    }
  ],
  [ // Here I wanted the AgeGroup Name from the AgeGroup Table (Group B)
    {
        "Name": "1st App GroupB",
        "StoreURL": "alsfdj",
        "AppIcon": "alsdjf",
        "AgeGroup": "Group B"
    },

//and so on...

Body:
I suggest to make the code a bit easier to understand and debug, you start with view models to represent the data you want to return

public class AgeGroupVM
{
    public string Name { get; set; }
    public IEnumerable<AppVM> Apps { get; set; }
}
public class AppVM
{
    public string Name { get; set; }
    public string StoreURL { get; set; }
    public string AppIcon { get; set; }
}

Then you need to order the data and group it by the Name property of AgeGroup

var data = _context.Apps
    .OrderBy(x => x.AgeGroup.GroupOrder) // order by AgeGroup first
    .ThenBy(x => x.AppOrder) // then by the AppOrder
    .GroupBy(x => x.AgeGroup.Name) // group by the AgeGroup
    .Select(x => new AgeGroupVM // project into the view model
    {
        Name = x.Key,
        Apps = x.Select(y => new AppVM
        {
            Name = y.Name,
            StoreURL = y.StoreURL,
            AppIcon = y.AppIcon
        })
    });
return Json(data);


问:
Not overwriting text file properly (Python)
My program is supposed to take a text file, print the contents, count the lines, ask for a string input, remove every occurrence of that string, say how many times the string was removed, and then output the new contents of the file. We were asked to use one file, not an input and an output file.

My code works and does everything it's supposed to up until I try to store the changes in the file at the end of the char_count function and the print_output function seems to not be working right at all.

If I have an input file of contents:

```<code>Apples
Oranges
Bananas
Apples
Oranges
Bananas
</code>```

if I try to remove Bananas, the resulting file contents for the input file is:

```<code>ApplesOrangesApplesOrangesles
Oranges
Bananas
</code>```

I've been trying to figure out what's going on with no progress, and our course textbook doesn't seem to mention overwriting input files, but we're required to do it for an assignment. What is wrong with my last two functions?

```<code>def main():

    input_file_name = input("Please Enter the name of your text file: ")
    infile = open(input_file_name, "r+")
    print()

    print("---------------------------------------")
    print("THE FILE CONTENTS ARE")
    print("---------------------------------------")
    print_file(infile)
    print("---------------------------------------")
    count_lines(infile)
    print("---------------------------------------")
    input_string = input("Please enter the word or string of words you want to remove from the text file: ")
    print("---------------------------------------")
    char_count(infile, input_string)
    print("---------------------------------------")
    print("THE NEW FILE CONTENTS ARE")
    print_output(infile)
    print("---------------------------------------")

    infile.close()

def print_file(infile):
    infile.seek(0)
    allLines = infile.readlines()
    for line in allLines:
        text = line.rstrip()
        print(text)

def count_lines(infile):
    infile.seek(0)
    allLines = infile.readlines()
    count = 0
    char = " "
    for line in allLines :
        text = line.rstrip()
        while char != "":
            char = infile.read(1)
        count = count + 1
    print("THE NUMBER OF LINES IS: %d " % count)

def char_count(infile, input_string) :
    count = 0
    infile.seek(0)
    allLines = infile.readlines()
    infile.seek(0)
    for line in allLines:
        while input_string in line:
            line = line.replace(input_string, "")
            count = count + 1
        text = line.rstrip()
        infile.write(text)
    print("NUMBER OF OCCURRENCES REMOVED IS: %d" % count)

def print_output(infile):
    infile.seek(0)
    allLines = infile.readlines()
    for line in allLines:
        text = line.rstrip()
        print(text)
main()
</code>```

答:
you have to truncate the file first to get the required output.</p>

```<code>def main():

    input_file_name = input("Please Enter the name of your text file: ")
    infile = open(input_file_name, "r+")
    print()

    print("---------------------------------------")
    print("THE FILE CONTENTS ARE")
    print("---------------------------------------")
    print_file(infile)
    print("---------------------------------------")
    count_lines(infile)
    print("---------------------------------------")
    input_string = input("Please enter the word or string of words you want to remove from the text file: ")
    print("---------------------------------------")
    char_count(infile, input_string)
    print("---------------------------------------")
    print("THE NEW FILE CONTENTS ARE")
    print_output(infile)
    print("---------------------------------------")

    infile.close()

def print_file(infile):
    infile.seek(0)
    allLines = infile.readlines()
    for line in allLines:
        text = line.rstrip()
        print(text)

def count_lines(infile):
    infile.seek(0)
    allLines = infile.readlines()
    count = 0
    char = " "
    for line in allLines :
        text = line.rstrip()
        while char != "":
            char = infile.read(1)
        count = count + 1
    print("THE NUMBER OF LINES IS: %d " % count)

def char_count(infile, input_string) :
    count = 0
    infile.seek(0)
    allLines = infile.readlines()
    infile.seek(0)
    infile.truncate() #Empty your file first to rewrite it
    for line in allLines:
        while input_string in line:
            line = line.replace(input_string, "")
            count = count + 1
        text = line.rstrip()
        if(text != ""):
            infile.write(text + "\n") #To write in multiple lines
    print("NUMBER OF OCCURRENCES REMOVED IS: %d" % count)

def print_output(infile):
    infile.seek(0)
    allLines = infile.readlines()
    for line in allLines:
        text = line.rstrip()
        print(text)
main()
</code>```

Body:
My program is supposed to take a text file, print the contents, count the lines, ask for a string input, remove every occurrence of that string, say how many times the string was removed, and then output the new contents of the file. We were asked to use one file, not an input and an output file.

My code works and does everything it's supposed to up until I try to store the changes in the file at the end of the char_count function and the print_output function seems to not be working right at all.

If I have an input file of contents:

Apples
Oranges
Bananas
Apples
Oranges
Bananas

if I try to remove Bananas, the resulting file contents for the input file is:

ApplesOrangesApplesOrangesles
Oranges
Bananas

I've been trying to figure out what's going on with no progress, and our course textbook doesn't seem to mention overwriting input files, but we're required to do it for an assignment. What is wrong with my last two functions?

def main():

    input_file_name = input("Please Enter the name of your text file: ")
    infile = open(input_file_name, "r+")
    print()

    print("---------------------------------------")
    print("THE FILE CONTENTS ARE")
    print("---------------------------------------")
    print_file(infile)
    print("---------------------------------------")
    count_lines(infile)
    print("---------------------------------------")
    input_string = input("Please enter the word or string of words you want to remove from the text file: ")
    print("---------------------------------------")
    char_count(infile, input_string)
    print("---------------------------------------")
    print("THE NEW FILE CONTENTS ARE")
    print_output(infile)
    print("---------------------------------------")

    infile.close()

def print_file(infile):
    infile.seek(0)
    allLines = infile.readlines()
    for line in allLines:
        text = line.rstrip()
        print(text)

def count_lines(infile):
    infile.seek(0)
    allLines = infile.readlines()
    count = 0
    char = " "
    for line in allLines :
        text = line.rstrip()
        while char != "":
            char = infile.read(1)
        count = count + 1
    print("THE NUMBER OF LINES IS: %d " % count)

def char_count(infile, input_string) :
    count = 0
    infile.seek(0)
    allLines = infile.readlines()
    infile.seek(0)
    for line in allLines:
        while input_string in line:
            line = line.replace(input_string, "")
            count = count + 1
        text = line.rstrip()
        infile.write(text)
    print("NUMBER OF OCCURRENCES REMOVED IS: %d" % count)

def print_output(infile):
    infile.seek(0)
    allLines = infile.readlines()
    for line in allLines:
        text = line.rstrip()
        print(text)
main()

Body:
you have to truncate the file first to get the required output.

def main():

    input_file_name = input("Please Enter the name of your text file: ")
    infile = open(input_file_name, "r+")
    print()

    print("---------------------------------------")
    print("THE FILE CONTENTS ARE")
    print("---------------------------------------")
    print_file(infile)
    print("---------------------------------------")
    count_lines(infile)
    print("---------------------------------------")
    input_string = input("Please enter the word or string of words you want to remove from the text file: ")
    print("---------------------------------------")
    char_count(infile, input_string)
    print("---------------------------------------")
    print("THE NEW FILE CONTENTS ARE")
    print_output(infile)
    print("---------------------------------------")

    infile.close()

def print_file(infile):
    infile.seek(0)
    allLines = infile.readlines()
    for line in allLines:
        text = line.rstrip()
        print(text)

def count_lines(infile):
    infile.seek(0)
    allLines = infile.readlines()
    count = 0
    char = " "
    for line in allLines :
        text = line.rstrip()
        while char != "":
            char = infile.read(1)
        count = count + 1
    print("THE NUMBER OF LINES IS: %d " % count)

def char_count(infile, input_string) :
    count = 0
    infile.seek(0)
    allLines = infile.readlines()
    infile.seek(0)
    infile.truncate() #Empty your file first to rewrite it
    for line in allLines:
        while input_string in line:
            line = line.replace(input_string, "")
            count = count + 1
        text = line.rstrip()
        if(text != ""):
            infile.write(text + "\n") #To write in multiple lines
    print("NUMBER OF OCCURRENCES REMOVED IS: %d" % count)

def print_output(infile):
    infile.seek(0)
    allLines = infile.readlines()
    for line in allLines:
        text = line.rstrip()
        print(text)
main()


问:
Mocha, Chai: Assert that Object is included in an Array of Objects
Chai has a nice way to assert if an Array includes a certain element

```<code>expect([1,2,3]).to.include(2);
</code>```

What I would like is something similar, given an Array of Objects:

```<code>expect([{a:1},{b:2}]).to.include({b:2});
</code>```

Is this possible?

答:
You can use deep method for the array of objects.

```<code>expect([{a:1},{b:2}]).to.deep.include({b:2});   //It will pass
</code>```

You can find more examples using deep method here: http://chaijs.com/api/bdd/#method_deep

The main point to remember here is about reference types.

Body:
Chai has a nice way to assert if an Array includes a certain element

expect([1,2,3]).to.include(2);

What I would like is something similar, given an Array of Objects:

expect([{a:1},{b:2}]).to.include({b:2});

Is this possible?

Body:
You can use deep method for the array of objects.

expect([{a:1},{b:2}]).to.deep.include({b:2});   //It will pass

You can find more examples using deep method here: http://chaijs.com/api/bdd/#method_deep

The main point to remember here is about reference types.


问:
onBackPressed with fragments and saving fragment state
I want to save fragment state so I use fragment .add() and fragment .show() methods.
the part I use to add fragments in my mainActivity is

```<code>android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.main_content, fragment, CURRENT_TAG);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
</code>```

On back pressed in the fragment and getting back to it the get fragment by tag returns null

```<code>       if (getSupportFragmentManager().findFragmentByTag(CURRENT_TAG) != null) {
            drawerLayout.closeDrawers();
            Runnable mPendingRunnable = new Runnable() {
                @Override
                public void run() {
                    android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
                    fragmentTransaction.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out);
                    hideTransactions(CURRENT_TAG);
                    fragmentTransaction.show(getSupportFragmentManager().findFragmentByTag(CURRENT_TAG)).commit();
                }
            };
</code>```

although onBackPressed the state of the fragment is right(TAG_PREV returns not null) in the on back pressed method

```<code>@Override
public void onBackPressed() {
    if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
        drawerLayout.closeDrawers();
        return;
    }
    if (CURRENT_TAG == TAG_HOME) {
        return;
    }
    navItemIndex = 0;
    TAG_PREV = CURRENT_TAG;
    CURRENT_TAG = TAG_HOME;
    loadHomeFragment();
    super.onBackPressed();
}
</code>```

答:
It is not possible to maintain entire fragment in back stack, There is no provision given by android teams.

You have to use onSaveInstanceState for saving current state/data when you are leaving fragment.

```<code>@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
    super.onSaveInstanceState(savedInstanceState);
    Log.i(TAG, " onSaveInstanceState.");
    savedInstanceState.putString("greeting", "Hello");
}
</code>```

After that when again coming on that fragment you have to use.

```<code>@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    String greeting = (savedInstanceState != null) ? savedInstanceState.getString("greeting") : "null";
    Log.i(TAG, " onCreate: " + greeting);
}
</code>```

Please let me if it dosen't work for you.

Body:
I want to save fragment state so I use fragment .add() and fragment .show() methods.
the part I use to add fragments in my mainActivity is

android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.main_content, fragment, CURRENT_TAG);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();

On back pressed in the fragment and getting back to it the get fragment by tag returns null

       if (getSupportFragmentManager().findFragmentByTag(CURRENT_TAG) != null) {
            drawerLayout.closeDrawers();
            Runnable mPendingRunnable = new Runnable() {
                @Override
                public void run() {
                    android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
                    fragmentTransaction.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out);
                    hideTransactions(CURRENT_TAG);
                    fragmentTransaction.show(getSupportFragmentManager().findFragmentByTag(CURRENT_TAG)).commit();
                }
            };

although onBackPressed the state of the fragment is right(TAG_PREV returns not null) in the on back pressed method

@Override
public void onBackPressed() {
    if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
        drawerLayout.closeDrawers();
        return;
    }
    if (CURRENT_TAG == TAG_HOME) {
        return;
    }
    navItemIndex = 0;
    TAG_PREV = CURRENT_TAG;
    CURRENT_TAG = TAG_HOME;
    loadHomeFragment();
    super.onBackPressed();
}

Body:
It is not possible to maintain entire fragment in back stack, There is no provision given by android teams.

You have to use onSaveInstanceState for saving current state/data when you are leaving fragment.

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
    super.onSaveInstanceState(savedInstanceState);
    Log.i(TAG, " onSaveInstanceState.");
    savedInstanceState.putString("greeting", "Hello");
}

After that when again coming on that fragment you have to use.

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    String greeting = (savedInstanceState != null) ? savedInstanceState.getString("greeting") : "null";
    Log.i(TAG, " onCreate: " + greeting);
}

Please let me if it dosen't work for you.


问:
Is it possible to create a 3D photo from a normal photo?
If I have understand well, 3D 360 photos are created from a panorama photo, so I guess it should be possible to create a 3D photo (non 360) from a normal photo. But how? I did not find anything in Google! Any idea of what should I search??

So far, if nothing available (I don't think so), I'll try to duplicate the same photo in each eye. One of the pictures a little bit moved to the right, and the other one moved a little bit to the left. But I think the distortion algorithm is much more complicated.

Note: I'm also receiving answers here: https://plus.google.com/u/0/115463690952639951338/posts/4KdqFcqUTT9

答: 2D lacks a dimension hence cannot be converted to 3D just like that, but there are clever ways for example Google Pixel even though doesn't have 2 camera can make it seem like the image is 3D by applying some Machine learning  algorithm that create the effect of perspective and depth by selective blurring.</p>


问:
Machine learning Algorithms used by Elastic x-pack plugin
Elastic X-pack plugin predicts the dynamic baseline for our data and according to that specifies the anomalies out of the box.

All these stuff are getting done behind the scene. My question is this how xpack learns from previous data and dynamically change the baseline. Does that use a specific algorithm?

Is there any document for this?

答: I found some good answers on this website which belongs to the Prelert the engine is applied by elastic for anomaly detection.