问:
Not sure how to proceed with this in my first ReactJS app
I've created a simple timer app in react which lets you input a number and start a countdown. Just for "learning react"-purposes I implemented an API to store timers that have been set. They're read on componentDidMount. You can delete them one by one using a button. The problem: Starting the timer is in a different component and doesnt know the state of the "RecentTimers" component. I'm unsure on how to properly do this with react.

This is the component that cares about the actual timer:

```<code>import React, { Component } from 'react';
import Axios from 'axios';
import ProgressBar from './ProgressBar';
import Input from './Input';
import Message from './Message';
import RecentTimers from './RecentTimers';

export default class Timer extends Component {
  constructor(props) {
    super(props);

    this.state = {
      running: false,
      secsStart: 0,
      secsRemaining: 0
    };

    this.startTimer = this.startTimer.bind(this);
    this.tick = this.tick.bind(this);
  }

  startTimer(startValue) {
    this.setState({
      running: true,
      secsStart: startValue,
      secsRemaining: startValue
    });

    this.timer = setInterval(this.tick, 1000);

    this.saveTimer(startValue);
  }

  saveTimer(startValue) {
    Axios.post('http://rest.learncode.academy/api/svartberg/timers', {
        timestamp: + new Date(),
        seconds: startValue
      })
      .then(function (response) {
        console.log(response);
      })
      .catch(function (error) {
        UIkit.notification({
          message: 'Couldn\'t save the timer.<br />' + error,
          status: 'danger',
          pos: 'bottom-right'
        });
      });
  }

  tick() {
    if (this.state.running) {
      if (this.state.secsRemaining > 0) {
        this.setState({
          secsRemaining: this.state.secsRemaining - 1
        });
      } else {
        this.setState({
          running: false
        });
        clearInterval(this.timer);
      }
    }
  }

  renderProgress() {
    return this.state.secsRemaining <= 0
      ? <Message>Der Timer ist abgelaufen.</Message>
      : <ProgressBar
          secsRemaining={this.state.secsRemaining}
          secsStart={this.state.secsStart}
        />;
  }

  render() {
    return (
      <div className="uk-container uk-container-center uk-margin-large-top uk-margin-large-bottom">
        <h1 className="uk-text-center">Simple Timer</h1>
        <Input startFunc={this.startTimer} status={this.state.running} />
        <div className="uk-text-center uk-margin-top">
          <span className="uk-text-lead">{this.state.secsRemaining}</span>{' '}
          seconds left.
        </div>
        { this.renderProgress() }
        <RecentTimers />
      </div>
    );
  }
}
</code>```

And this is the component that cares about the list of recently used timers:

```<code>import React, { Component } from 'react';
import Axios from 'axios';

import UIkit from 'uikit';
import Icons from 'uikit/dist/js/uikit-icons';

UIkit.use(Icons);

export default class RecentTimers extends Component {

  constructor() {
    super();
    this.state = {
      loading: true,
      recentTimers: []
    };
  }

  componentDidMount() {
    this.getRecentTimers();
  }

  getRecentTimers() {
    this.setState({ loading: true });

    Axios.get('http://rest.learncode.academy/api/svartberg/timers')
      .then((response) => {
        this.setState({
          loading: false,
          recentTimers: response.data.reverse()
        });
      })
      .catch(function (error) {
        UIkit.notification({
          message: 'Couldn\'t fetch recent timers.<br />' + error,
          status: 'danger',
          pos: 'bottom-right'
        });
      });
  }

  deleteRecentTimerItem(item) {
    Axios.delete('http://rest.learncode.academy/api/svartberg/timers/' + item.id)
      .then((response) => {
        this.getRecentTimers();

        UIkit.notification({
          message: 'Item deleted',
          status: 'success',
          pos: 'bottom-right'
        });
      })
      .catch(function (error) {
        UIkit.notification({
          message: 'Couldn\'t delete timer with ID ' + item.id + '.<br />' + error,
          status: 'danger',
          pos: 'bottom-right'
        });
      });
  }

  renderRecentTimerItems() {
    if (this.state.loading) {
      return <div className="uk-text-center"><span data-uk-spinner={''} /></div>;
    } else {
      return this.state.recentTimers.length > 0
        ? this.state.recentTimers.map((item, index) => (
          <li key={index}>
            {new Date(item.timestamp).toLocaleDateString()} - {new Date(item.timestamp).toLocaleTimeString()} <span className="uk-margin-small-left uk-margin-small-right">|</span>  {item.seconds} Secs.
            <span onClick={this.deleteRecentTimerItem.bind(this, item)} className="uk-float-right" style={{lineHeight: 'normal'}} data-uk-icon="icon: close"></span>
          </li>
        ))
        : <p>No recent timers.</p>;
    }
  }

  render() {
    return (
      <div>
        <hr />
        <div className="uk-card uk-card-default uk-card-body">
          <h3 className="uk-card-title uk-text-center">Recent Timers</h3>
          <ul className="uk-list uk-list-divider">
            { this.renderRecentTimerItems() }
          </ul>
        </div>
      </div>
    )
  }

}
</code>```

No idea how I tell my recent timers component that it needs to update because a new timer started and I want that timer in my list of recent timers.

答:
Pass the timer object in the props of your <RecentTimers timer={this.state.timer}> this.state.timer can be updated whenever your are starting a timer and use componentWillRecieveProps to update the state of RecentTimer component whenever there is an addition of a new timer in the timer list.

Whenever you are updating a component following function will be invoked.

```<code>1.componentWillReceiveProps()
2.shouldComponentUpdate()
3.componentWillUpdate()
4.render()
5.componentDidUpdate()
</code>```

You can use

```<code>componentWillReceiveProps(nextProps) {

   if(nextProps.timer){
     let recentTimer = this.state.recentTimers;
     this.setState({
        recentTimers : recentTimers.push(nextProps.timer);// this update your timers, But wont re-render the component.
     });
     //or save the timer
   }
}
</code>```

Or Use componentWillUpdate as this method will re-render your component,

```<code>componentWillUpdate(nextProps , nextState){
   //Code goes here.
}
</code>```

You can see this blog for more info of state handling.

Thanks,

Body:
I've created a simple timer app in react which lets you input a number and start a countdown. Just for "learning react"-purposes I implemented an API to store timers that have been set. They're read on componentDidMount. You can delete them one by one using a button. The problem: Starting the timer is in a different component and doesnt know the state of the "RecentTimers" component. I'm unsure on how to properly do this with react.

This is the component that cares about the actual timer:

import React, { Component } from 'react';
import Axios from 'axios';
import ProgressBar from './ProgressBar';
import Input from './Input';
import Message from './Message';
import RecentTimers from './RecentTimers';

export default class Timer extends Component {
  constructor(props) {
    super(props);

    this.state = {
      running: false,
      secsStart: 0,
      secsRemaining: 0
    };

    this.startTimer = this.startTimer.bind(this);
    this.tick = this.tick.bind(this);
  }

  startTimer(startValue) {
    this.setState({
      running: true,
      secsStart: startValue,
      secsRemaining: startValue
    });

    this.timer = setInterval(this.tick, 1000);

    this.saveTimer(startValue);
  }

  saveTimer(startValue) {
    Axios.post('http://rest.learncode.academy/api/svartberg/timers', {
        timestamp: + new Date(),
        seconds: startValue
      })
      .then(function (response) {
        console.log(response);
      })
      .catch(function (error) {
        UIkit.notification({
          message: 'Couldn\'t save the timer.
' + error,
          status: 'danger',
          pos: 'bottom-right'
        });
      });
  }

  tick() {
    if (this.state.running) {
      if (this.state.secsRemaining > 0) {
        this.setState({
          secsRemaining: this.state.secsRemaining - 1
        });
      } else {
        this.setState({
          running: false
        });
        clearInterval(this.timer);
      }
    }
  }

  renderProgress() {
    return this.state.secsRemaining <= 0
      ? <Message>Der Timer ist abgelaufen.</Message>
      : <ProgressBar
          secsRemaining={this.state.secsRemaining}
          secsStart={this.state.secsStart}
        />;
  }

  render() {
    return (

Simple Timer

        <Input startFunc={this.startTimer} status={this.state.running} />

          {this.state.secsRemaining}{' '}
          seconds left.

        { this.renderProgress() }
        <RecentTimers />

    );
  }
}

And this is the component that cares about the list of recently used timers:

import React, { Component } from 'react';
import Axios from 'axios';

import UIkit from 'uikit';
import Icons from 'uikit/dist/js/uikit-icons';

UIkit.use(Icons);

export default class RecentTimers extends Component {

  constructor() {
    super();
    this.state = {
      loading: true,
      recentTimers: []
    };
  }

  componentDidMount() {
    this.getRecentTimers();
  }

  getRecentTimers() {
    this.setState({ loading: true });

    Axios.get('http://rest.learncode.academy/api/svartberg/timers')
      .then((response) => {
        this.setState({
          loading: false,
          recentTimers: response.data.reverse()
        });
      })
      .catch(function (error) {
        UIkit.notification({
          message: 'Couldn\'t fetch recent timers.
' + error,
          status: 'danger',
          pos: 'bottom-right'
        });
      });
  }

  deleteRecentTimerItem(item) {
    Axios.delete('http://rest.learncode.academy/api/svartberg/timers/' + item.id)
      .then((response) => {
        this.getRecentTimers();

        UIkit.notification({
          message: 'Item deleted',
          status: 'success',
          pos: 'bottom-right'
        });
      })
      .catch(function (error) {
        UIkit.notification({
          message: 'Couldn\'t delete timer with ID ' + item.id + '.
' + error,
          status: 'danger',
          pos: 'bottom-right'
        });
      });
  }

  renderRecentTimerItems() {
    if (this.state.loading) {
      return

;
    } else {
      return this.state.recentTimers.length > 0
        ? this.state.recentTimers.map((item, index) => (

            {new Date(item.timestamp).toLocaleDateString()} - {new Date(item.timestamp).toLocaleTimeString()} |  {item.seconds} Secs.

        ))
        :
No recent timers.
;
    }
  }

  render() {
    return (

Recent Timers

            { this.renderRecentTimerItems() }

    )
  }

}

No idea how I tell my recent timers component that it needs to update because a new timer started and I want that timer in my list of recent timers.

Body:
Pass the timer object in the props of your <RecentTimers timer={this.state.timer}> this.state.timer can be updated whenever your are starting a timer and use componentWillRecieveProps to update the state of RecentTimer component whenever there is an addition of a new timer in the timer list.

Whenever you are updating a component following function will be invoked.

1.componentWillReceiveProps()
2.shouldComponentUpdate()
3.componentWillUpdate()
4.render()
5.componentDidUpdate()

You can use

componentWillReceiveProps(nextProps) {

   if(nextProps.timer){
     let recentTimer = this.state.recentTimers;
     this.setState({
        recentTimers : recentTimers.push(nextProps.timer);// this update your timers, But wont re-render the component.
     });
     //or save the timer
   }
}

Or Use componentWillUpdate as this method will re-render your component,

componentWillUpdate(nextProps , nextState){
   //Code goes here.
}

You can see this blog for more info of state handling.

Thanks,


来源: stackexchange

问:
Apache Spark - Why are executor being removed? What does 'Idle' mean?
With Dynamic Resource Allocation :

A Spark application removes an executor when it has been idle for
  more than spark.dynamicAllocation.executorIdleTimeout seconds.

And when I set the executor idle timeout property
 as followed spark.dynamicAllocation.executorIdleTimeout= 300 , it throws the following warning :

```<code>spark.ExecutorAllocationManager: Removing executor 0 because it has been idle for 300 seconds (new desired total will be 2)
</code>```

What does mean to be "Idle"? Does it means the worker use no CPU? Does a blocking call to database count as Idle?

答:
What does mean to be "Idle"?

To answer this question, I'd like to go back to the official documentation. So, like mentioned in the documentation that you have cited, the dynamic allocation mechanism provides Spark with the ability to adjust dynamically  the resources your application occupies based on the workload.

This means that your application may :

Request them again later when needed.

Give resources back to the cluster if they are no longer used: The executor state is considered as idle, which is the term to specify that it's sitting there doing nothing (and reserving resources)
i.e : in your case, it generated the following warning :

```<code>spark.ExecutorAllocationManager: Removing executor 0 because it has been idle for 300 seconds (new desired total will be 2)
</code>```

Does it means the worker uses no cpu?

An executor reserves CPU and memory. In case other applications need to use them, well it's reserved. Your resource manager can't allocate resources for your other applications. Thus freeing them can be prolific in case of multiple application sharing the same cluster.

Does a blocking call to database count as Idle?

A call to a database usually asks for resources, thus, the executor isn't idle when performing any kind of task (even this one).

To know more about the ExecutorAllocationManager, I advice you to look into it's code  here.

ContentLicense: CC BY-SA 3.0

Body:
With Dynamic Resource Allocation :

A Spark application removes an executor when it has been idle for
  more than spark.dynamicAllocation.executorIdleTimeout seconds.

And when I set the executor idle timeout property
 as followed spark.dynamicAllocation.executorIdleTimeout= 300 , it throws the following warning :

spark.ExecutorAllocationManager: Removing executor 0 because it has been idle for 300 seconds (new desired total will be 2)

What does mean to be "Idle"? Does it means the worker use no CPU? Does a blocking call to database count as Idle?

Body:
What does mean to be "Idle"?

To answer this question, I'd like to go back to the official documentation. So, like mentioned in the documentation that you have cited, the dynamic allocation mechanism provides Spark with the ability to adjust dynamically  the resources your application occupies based on the workload.

This means that your application may :

Request them again later when needed.

Give resources back to the cluster if they are no longer used: The executor state is considered as idle, which is the term to specify that it's sitting there doing nothing (and reserving resources)
i.e : in your case, it generated the following warning :

spark.ExecutorAllocationManager: Removing executor 0 because it has been idle for 300 seconds (new desired total will be 2)

Does it means the worker uses no cpu?

An executor reserves CPU and memory. In case other applications need to use them, well it's reserved. Your resource manager can't allocate resources for your other applications. Thus freeing them can be prolific in case of multiple application sharing the same cluster.

Does a blocking call to database count as Idle?

A call to a database usually asks for resources, thus, the executor isn't idle when performing any kind of task (even this one).

To know more about the ExecutorAllocationManager, I advice you to look into it's code  here.

ContentLicense: CC BY-SA 4.0


问:
Disable drag on Google Map Javascript custom controls
I want to create a Google map custom control using the Javascript API.

The control is an 'add waypoint' button.  The user is supposed to be able to drag from the control, causing a marker to appear at the mouse pointer, and drop this marker on to the map.

The intended behavior is nearly identical to the existing pegman feature.

The problem is that the Google map controls seem to interact with drag, even when the drag has been explicitly disabled, as seen below.

In the example code, The first time I click and drag, it works as intended.  The second time I click and drag, I get a 'no drag' icon and the control spawns a ghost of itself.  The third time I drag, it's working again.  On the next drag, there's a 'no drag'.  The sequence continues, with odd drags working, and even drags failing.

Here's what I believe to be the relevant section:

```<code><div id="map"></div>
<script>
    var spawning = false;
    var inProgress = false;
    var waypointSpawner;
    var targetLat;
    var targetLng;

    function initMap()
    {
        map = new google.maps.Map(document.getElementById('map'), {
            center: {lat: 0.0000, lng: 0.0000},
            zoom: 2
        });

        // Create the DIV to hold the control and call the CenterControl()
        // constructor passing in this DIV.
        var centerControlDiv = document.createElement('div');
        var centerControl = new CenterControl(centerControlDiv, map);

        centerControlDiv.index = 1;
        map.controls[google.maps.ControlPosition.LEFT_TOP].push(centerControlDiv);
    }

    function CenterControl(controlDiv, map) {

        // Set CSS for the control border.
        var controlUI = document.createElement('div');
        controlUI.style.backgroundColor = '#fff';
        controlUI.style.border = '2px solid #fff';
        controlUI.style.borderRadius = '3px';
        controlUI.style.boxShadow = '0 2px 6px rgba(0,0,0,.3)';
        controlUI.style.cursor = 'pointer';
        controlUI.style.marginBottom = '22px';
        controlUI.style.width = '40px';
        controlUI.style.height = '50px';
        controlUI.style.opacity = "0.7";
        controlUI.style.backgroundImage = "url('create_waypoint_icon.png')";
        controlUI.title = 'Add Waypoint';
        controlUI.draggable = "false";

    //controlDiv.draggable = "false";
    controlDiv.appendChild(controlUI);
    }
</code>```

I was unable to get the above code to work in jsfiddle, but there are a couple of other examples that illustrate the problem.

http://jsfiddle.net/maunovaha/jptLfhc8/

Attempting to drag and drop the blue and green squares in the top left of the map results in some unintended behavior.  Depending on your zoom level, and somewhat randomly, you will get a variety of different outcomes -

1 - Nothing happens.  The pointer remains as a finger and moves normally.

2 - The finger pointer changes to a 'no drag' but otherwise moves normally.

3 - The finger pointer changes to a 'no drag' and a blue-and green semi-transparent 'to-paste' widget.

4 - The finger pointer changes to a 'no drag', and either the blue or green half of the widget (depending on your selection) goes with it.

This behavior is also somewhat evident in the Google control example code:

https://developers.google.com/maps/documentation/javascript/examples/control-custom

In this instance, when the text is highlighted, you get the 'no drag' icon.  The parent control doesn't appear to be selectable, which is the desired goal.

I believe that the custom control is acquiring some kind of 'focus' status, and that clicking it again clears the focus.  This behavior is evident in the green/blue example.  Perhaps the control is being 'highlighted' somehow?

I attempted to implement the solutions given in How can I make a div unselectable? to no effect.  I also tried a variety of ways to make the div undraggable in the code, but this did not appear to have any impact.

I also tried simulating mouse clicks on other parts of the program, and double clicking on the control, to change the focus/highlight status, but it appears the API doesn't actually carry out the clicks, only generates events from them.  I couldn't find a way to cause a 'real' click.  Manually clicking, then clicking and dragging worked.

I also tried making the control draggable but it still has the 'no drag' mouse pointer even when dragging it about.

答:
If I understand correctly what you are saying, you want to be able to drag a marker onto the map, from outside, and place a point on that position.

I have the following solution which does that.

First we need to build the map:

```<code>function buildMap() {
        var g = google.maps;
        var mapOptions = {
        center: new g.LatLng(52.052491, 9.84375),
        zoom: 4,
        mapTypeId: g.MapTypeId.ROADMAP,
        streetViewControl: false,
        panControl: false
      };
      map = new g.Map(document.getElementById("map"), mapOptions);
      iw = new g.InfoWindow();
      g.event.addListener(map, "click", function() {
        if (iw) iw.close()
      });
      drag_area = document.getElementById("markers");
      var b = drag_area.getElementsByTagName("div");
      b[0].onmousedown = initDrag
      dummy = new DummyOView()
    }
</code>```

We create a standard map and add features such as infoWindows to display the lat lng when the marker is added.

In addition we get where the marker is held and onMouseDown call a function (soon to come).

We use b[0] as we are getting the first set of
 tags in the mark-up below, this is where the draggable icon is held:

```<code><div id="markers">
  <div id="m1" class="drag" style="left:0; background-image: url('https://maps.gstatic.com/mapfiles/ms/icons/ltblue-dot.png')">
  </div>
</div>
</code>```

The DummyOView is a map OverlayView which allows us to drag onto the map and grab the coords and position. More information on SO + credit to : More info

```<code>function DummyOView() {
  this.setMap(map);
  this.draw = function() {}
}

DummyOView.prototype = new google.maps.OverlayView();
</code>```

The initDrag function is where most of the work is done, this is quite a lengthy function so I did comment the code, any questions on clarification just add a comment.

```<code>//function that allows us to drag the marker from the div to the map
function initDrag(e) {
  //allows us to drag the marker and keep record of the clientX client Y coordinates
  var j = function(e) {
    var a = {};
    if (!e) var e = window.event;
    a.x = e.clientX;
    a.y = e.clientY
    return a
  };
  //function called whenever the mouse moves. this will keep track of the marker as we move around
  var k = function(e) {
    //check to ensure that the object is of class drag - otherwise we could drag everything
    if (obj && obj.className == "drag") {
      var i = j(e),
        deltaX = i.x - l.x,
        deltaY = i.y - l.y;
      obj.style.left = (obj.x + deltaX) + "px";
      obj.style.top = (obj.y + deltaY) + "px";
      obj.onmouseup = function() {
        //get the information to check to see if the dragObj is on the map on mouse up
        var a = map.getDiv(),
          mLeft = a.offsetLeft,
          mTop = a.offsetTop,
          mWidth = a.offsetWidth,
          mHeight = a.offsetHeight;
        var b = drag_area.offsetLeft,
          areaTop = drag_area.offsetTop,
          oWidth = obj.offsetWidth,
          oHeight = obj.offsetHeight;
        //check to see if obj is in bounds of map div X and Y
        var x = obj.offsetLeft + b + oWidth / 2;
        var y = obj.offsetTop + areaTop + oHeight / 2;
        if (x > mLeft && x < (mLeft + mWidth) && y > mTop && y < (mTop + mHeight)) {
          var c = 1;
          var mapTemp = google.maps;
          var point = new mapTemp.Point(x - mLeft - c, y - mTop + (oHeight / 2));
          var proj = dummy.getProjection();
          var latlng = proj.fromContainerPixelToLatLng(point);
          var backImage = obj.style.backgroundImage.slice(4, -1).replace(/"/g, "");
          createDraggedMarker(latlng, backImage);
          fillMarker(backImage)
        }
      }
    }
    return false
  };

  //assign the event to a windows event
  obj = e.target ? e.target : e.srcElement;
  //if the object where the event took place is not called drag cancel the event
  if (obj.className != "drag") {
    if (e.cancelable) e.preventDefault();
    obj = null;
    return
  } else {
    z_index += 1;
    obj.style.zIndex = z_index.toString();
    obj.x = obj.offsetLeft;
    obj.y = obj.offsetTop;

    var l = j(e); //get the initial position of the marker relative to the client

    document.onmousemove = k;
    //if we lift the mouse up outside the map div set to null and leave where it is
    document.onmouseup = function() {
      document.onmousemove = null;
      document.onmouseup = null;
      if (obj) obj = null
    }
  }
  return false
}
</code>```

Summarised this function is called whenever the mouse has been clicked and dragged. It registed the starting position and the positions of the map div and checks when the onmouseup to see if the current mouse position is over the map div. If so we create a marker on the map and re-add the marker icon to the div to allow redragging.

```<code>//when the marker is dragged onto the map
//we call this function to create a marker on the map
function createDraggedMarker(position, iconImage) {
  var mapLocal = google.maps;
  var icon = {
    url: iconImage,
    size: new mapLocal.Size(32, 32),
    anchor: new mapLocal.Point(15, 32)
  };
  var marker = new mapLocal.Marker({
    position: position,
    map: map,
    clickable: true,
    draggable: true,
    crossOnDrag: false,
    optimized: false,
    icon: icon,
    zIndex: highestOrder()
  });

  mapLocal.event.addListener(marker, "click", function() {
    actual = marker;
    var lat = actual.getPosition().lat();
    var lng = actual.getPosition().lng();
    var innerHtml = "<div class='infowindow'>" + lat.toFixed(6) + ", " + lng.toFixed(6) + "<\/div>";
    iw.setContent(innerHtml);
    iw.open(map, this)
  });
  mapLocal.event.addListener(marker, "dragstart", function() {
    if (actual == marker) iw.close();
    z_index += 1;
    marker.setZIndex(highestOrder())
  })
}
</code>```

Re-adding the marker to the div

```<code>//Used to replace the marker
//once we have moved it from its div
function fillMarker(a) {
  var div = document.createElement("div");
  div.style.backgroundImage = "url(" + a + ")";
  var padding;
  if (obj.id == "m1") {
    padding = "0px"
  }
  div.style.left = padding;
  div.id = obj.id;
  div.className = "drag";
  div.onmousedown = initDrag;
  drag_area.replaceChild(div, obj);
  obj = null
}
</code>```

JSfiddle you can use : https://jsfiddle.net/q3wjrpdw/7/

Any questions feel free to ask.

Body:
If I understand correctly what you are saying, you want to be able to drag a marker onto the map, from outside, and place a point on that position.

I have the following solution which does that.

First we need to build the map:

function buildMap() {
        var g = google.maps;
        var mapOptions = {
        center: new g.LatLng(52.052491, 9.84375),
        zoom: 4,
        mapTypeId: g.MapTypeId.ROADMAP,
        streetViewControl: false,
        panControl: false
      };
      map = new g.Map(document.getElementById("map"), mapOptions);
      iw = new g.InfoWindow();
      g.event.addListener(map, "click", function() {
        if (iw) iw.close()
      });
      drag_area = document.getElementById("markers");
      var b = drag_area.getElementsByTagName("div");
      b[0].onmousedown = initDrag
      dummy = new DummyOView()
    }

We create a standard map and add features such as infoWindows to display the lat lng when the marker is added.

In addition we get where the marker is held and onMouseDown call a function (soon to come).

We use b[0] as we are getting the first set of <div> tags in the mark-up below, this is where the draggable icon is held:

<div id="markers">
  <div id="m1" class="drag" style="left:0; background-image: url('https://maps.gstatic.com/mapfiles/ms/icons/ltblue-dot.png')">
  </div>
</div>

The DummyOView is a map OverlayView which allows us to drag onto the map and grab the coords and position. More information on SO + credit to : More info

function DummyOView() {
  this.setMap(map);
  this.draw = function() {}
}

DummyOView.prototype = new google.maps.OverlayView();

The initDrag function is where most of the work is done, this is quite a lengthy function so I did comment the code, any questions on clarification just add a comment.

//function that allows us to drag the marker from the div to the map
function initDrag(e) {
  //allows us to drag the marker and keep record of the clientX client Y coordinates
  var j = function(e) {
    var a = {};
    if (!e) var e = window.event;
    a.x = e.clientX;
    a.y = e.clientY
    return a
  };
  //function called whenever the mouse moves. this will keep track of the marker as we move around
  var k = function(e) {
    //check to ensure that the object is of class drag - otherwise we could drag everything
    if (obj && obj.className == "drag") {
      var i = j(e),
        deltaX = i.x - l.x,
        deltaY = i.y - l.y;
      obj.style.left = (obj.x + deltaX) + "px";
      obj.style.top = (obj.y + deltaY) + "px";
      obj.onmouseup = function() {
        //get the information to check to see if the dragObj is on the map on mouse up
        var a = map.getDiv(),
          mLeft = a.offsetLeft,
          mTop = a.offsetTop,
          mWidth = a.offsetWidth,
          mHeight = a.offsetHeight;
        var b = drag_area.offsetLeft,
          areaTop = drag_area.offsetTop,
          oWidth = obj.offsetWidth,
          oHeight = obj.offsetHeight;
        //check to see if obj is in bounds of map div X and Y
        var x = obj.offsetLeft + b + oWidth / 2;
        var y = obj.offsetTop + areaTop + oHeight / 2;
        if (x > mLeft && x < (mLeft + mWidth) && y > mTop && y < (mTop + mHeight)) {
          var c = 1;
          var mapTemp = google.maps;
          var point = new mapTemp.Point(x - mLeft - c, y - mTop + (oHeight / 2));
          var proj = dummy.getProjection();
          var latlng = proj.fromContainerPixelToLatLng(point);
          var backImage = obj.style.backgroundImage.slice(4, -1).replace(/"/g, "");
          createDraggedMarker(latlng, backImage);
          fillMarker(backImage)
        }
      }
    }
    return false
  };

  //assign the event to a windows event
  obj = e.target ? e.target : e.srcElement;
  //if the object where the event took place is not called drag cancel the event
  if (obj.className != "drag") {
    if (e.cancelable) e.preventDefault();
    obj = null;
    return
  } else {
    z_index += 1;
    obj.style.zIndex = z_index.toString();
    obj.x = obj.offsetLeft;
    obj.y = obj.offsetTop;

    var l = j(e); //get the initial position of the marker relative to the client

    document.onmousemove = k;
    //if we lift the mouse up outside the map div set to null and leave where it is
    document.onmouseup = function() {
      document.onmousemove = null;
      document.onmouseup = null;
      if (obj) obj = null
    }
  }
  return false
}

Summarised this function is called whenever the mouse has been clicked and dragged. It registed the starting position and the positions of the map div and checks when the onmouseup to see if the current mouse position is over the map div. If so we create a marker on the map and re-add the marker icon to the div to allow redragging.

//when the marker is dragged onto the map
//we call this function to create a marker on the map
function createDraggedMarker(position, iconImage) {
  var mapLocal = google.maps;
  var icon = {
    url: iconImage,
    size: new mapLocal.Size(32, 32),
    anchor: new mapLocal.Point(15, 32)
  };
  var marker = new mapLocal.Marker({
    position: position,
    map: map,
    clickable: true,
    draggable: true,
    crossOnDrag: false,
    optimized: false,
    icon: icon,
    zIndex: highestOrder()
  });

  mapLocal.event.addListener(marker, "click", function() {
    actual = marker;
    var lat = actual.getPosition().lat();
    var lng = actual.getPosition().lng();
    var innerHtml = "<div class='infowindow'>" + lat.toFixed(6) + ", " + lng.toFixed(6) + "<\/div>";
    iw.setContent(innerHtml);
    iw.open(map, this)
  });
  mapLocal.event.addListener(marker, "dragstart", function() {
    if (actual == marker) iw.close();
    z_index += 1;
    marker.setZIndex(highestOrder())
  })
}

Re-adding the marker to the div

//Used to replace the marker
//once we have moved it from its div
function fillMarker(a) {
  var div = document.createElement("div");
  div.style.backgroundImage = "url(" + a + ")";
  var padding;
  if (obj.id == "m1") {
    padding = "0px"
  }
  div.style.left = padding;
  div.id = obj.id;
  div.className = "drag";
  div.onmousedown = initDrag;
  drag_area.replaceChild(div, obj);
  obj = null
}

JSfiddle you can use : https://jsfiddle.net/q3wjrpdw/7/

Any questions feel free to ask.


问:
Open Excel File using OpenFileDialog in C# Windows Form
I am able to choose an Excel file, but after I clicked on Open, the excel file doesn't appear. What should I do? I'm still new with OpenFileDialog, it will be good if anyone can tell what I should add to make the excel file appear after clicking on Open.

Modified from http://www.c-sharpcorner.com/uploadfile/mahesh/openfiledialog-in-c-sharp/

This is my code:

```<code>private void BrowseButton_Click(object sender, EventArgs e)
    {
        OpenFileDialog openFileDialog1 = new OpenFileDialog();

        openFileDialog1.InitialDirectory = @"C:\";
        openFileDialog1.Title = "Browse Text Files";

        openFileDialog1.CheckFileExists = true;
        openFileDialog1.CheckPathExists = true;

        openFileDialog1.DefaultExt = "txt";
        openFileDialog1.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
        openFileDialog1.FilterIndex = 2;
        openFileDialog1.RestoreDirectory = true;

        openFileDialog1.ReadOnlyChecked = true;
        openFileDialog1.ShowReadOnly = true;

        if (openFileDialog1.ShowDialog() == DialogResult.OK)
        {
            string file = openFileDialog1.FileName;
            try
            {
                string text = File.ReadAllText(file);
                int size = text.Length;
            }
            catch (IOException)
            {
            }

        }
    }

public bool ThumbnailCallback()
   {
     return false;
   }

    private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
    {

    }
</code>```

After I clicked Open, only the file name appear, but not the excel file - https://i.stack.imgur.com/GXToy.jpg

答:
You need to set the filter to select excel files.

```<code>openFileDialog1.Filter = "Excel Worksheets|*.xls";
</code>```

You can refer the documentation here.

Body:
I am able to choose an Excel file, but after I clicked on Open, the excel file doesn't appear. What should I do? I'm still new with OpenFileDialog, it will be good if anyone can tell what I should add to make the excel file appear after clicking on Open.

Modified from http://www.c-sharpcorner.com/uploadfile/mahesh/openfiledialog-in-c-sharp/

This is my code:

private void BrowseButton_Click(object sender, EventArgs e)
    {
        OpenFileDialog openFileDialog1 = new OpenFileDialog();

        openFileDialog1.InitialDirectory = @"C:\";
        openFileDialog1.Title = "Browse Text Files";

        openFileDialog1.CheckFileExists = true;
        openFileDialog1.CheckPathExists = true;

        openFileDialog1.DefaultExt = "txt";
        openFileDialog1.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
        openFileDialog1.FilterIndex = 2;
        openFileDialog1.RestoreDirectory = true;

        openFileDialog1.ReadOnlyChecked = true;
        openFileDialog1.ShowReadOnly = true;

        if (openFileDialog1.ShowDialog() == DialogResult.OK)
        {
            string file = openFileDialog1.FileName;
            try
            {
                string text = File.ReadAllText(file);
                int size = text.Length;
            }
            catch (IOException)
            {
            }

        }
    }

public bool ThumbnailCallback()
   {
     return false;
   }

    private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
    {

    }

After I clicked Open, only the file name appear, but not the excel file - https://i.stack.imgur.com/GXToy.jpg

Body:
You need to set the filter to select excel files.

openFileDialog1.Filter = "Excel Worksheets|*.xls";

You can refer the documentation here.


问:
Google Go for Java platform?
JVM provides great performance - it's on the one hand. Golang sounds like a new paradigm and extremely productive - on the other hand. If we could bring together the best of two worlds - JVM performance and golang productivity - we could get a lot of benefits. Does anyone know any project that provides golang implementation in java? </p>

答:
A different route might be to use a JVM library which provides the most important features of Go, which are in my opinion and experience the lightweight Go-routines multiplexed on JVM threads, and channels for communication and synchronization.

There is one such library, Quasar, from Parallel Universe (see e.g. this blog post comparing Quasar and Go). Also, it works well with Kotlin, which is getting more popular now as an officially supported Android language, and providing much more compact (productive?) syntax than Java.

Title: Google Go for Java platform?


问:
CPython as a library for C (To execute Python code from C)
I'm not C expert so what I'm asking might be crazy.

Is it possible to compile CPython using an ARM c-compiler (like yagarto or arm-gcc)
and then call it from a C application to process lines of python code?

If so, what are the resources/documents I should be looking at?

答: Embedding Python in Another Application on Python.org</p>

ContentLicense: CC BY-SA 2.5


问:
jQuery.parseJSON() not decoding a valid Json string on a Windows server
I have this wordpress javascript function code running and working on a Linux server along with a php function "get_form_data".

```<code>jQuery.ajax({
              type: "POST",
              url: MyAjax.ajaxurl,
              data: {action: "get_form_data", id: id, cat_id: cat_id},

              success: function(r) {

                            //alert(r);
                            var response = jQuery.parseJSON(r);
               }
});
</code>```

I migrated the wordpress site to a Windows 8 Server with IIS and PHP and now it's throwing an error in the parseJSON line like this (it's only happening in the Windows environment):

SyntaxError: JSON.parse: unexpected character at line 2 column 1 of the JSON data

The string received from the PHP function is being retrieved without any problem and the Ajax code gets to the success state right before the string is parsed (by enabling the commented alert line), but once the Json parse function tries to decode it, it crashes. The Json string is encoded by the PHP function with json_encode().

This is the string received by the Ajax function, it's a valid string as far as I know.

["New Day","2","One Song","John","2014-12-08 13:04:56","1843","22"]

答:
Split the Return Data:

In c# asmx:
string _json = "";

_json = getJsonFunction(_dataSet.Tables[0]);
 _json += '`' + getJsonFunction(_dataSet.Tables[1]);

in Jquery:
Data = JSON.parse(res.d.split('`')[0]);

Body:
I have this wordpress javascript function code running and working on a Linux server along with a php function "get_form_data".

jQuery.ajax({
              type: "POST",
              url: MyAjax.ajaxurl,
              data: {action: "get_form_data", id: id, cat_id: cat_id},

              success: function(r) {

                            //alert(r);
                            var response = jQuery.parseJSON(r);
               }
});

I migrated the wordpress site to a Windows 8 Server with IIS and PHP and now it's throwing an error in the parseJSON line like this (it's only happening in the Windows environment):

SyntaxError: JSON.parse: unexpected character at line 2 column 1 of the JSON data

The string received from the PHP function is being retrieved without any problem and the Ajax code gets to the success state right before the string is parsed (by enabling the commented alert line), but once the Json parse function tries to decode it, it crashes. The Json string is encoded by the PHP function with json_encode().

This is the string received by the Ajax function, it's a valid string as far as I know.

["New Day","2","One Song","John","2014-12-08 13:04:56","1843","22"]


问:
Getting Post angular 2 toPromise HTTP
Hello I need to get some response after posting json object, using toPromise, its my code, respond is undefined:

```<code>export class ApiStorage{
constructor( @Inject(Http) private http: Http ){}
    rs(){
    this.http.post('http://0.0.0.0:80/student/outbound', this.json, headers)
            .toPromise()
            .then(response => {
                respond = JSON.stringify(response);
                return respond; //<- edited
            })
            .catch((error: any) => {
            ...
                });
    }
}
</code>```

then when in main component I use

```<code>send(){
    respondJSON = apistorage.rs();
    console.log(respondJSON);
    }
</code>```

respondJSON is undefined

答:
respond will always be undefined in your code, because you are making an asynchronous call to a webservice, which you do not await before logging to console.

```<code>export class ApiStorage{

    constructor( @Inject(Http) private http: Http ){}

    rs() {

        return this.http.post('http://0.0.0.0:80/student/outbound', this.json, headers)
            .toPromise()
            .then(response => {
                let respond = JSON.stringify(response));
                return respond;
            })
            .catch((error: any) => {
                ...
            });
    }
}

// rs now returns a promise, which can be used like this
// inside another function
send() {
    apistorage.rs().then(res => {
        console.log(res);
    }
}
</code>```

Title: Getting Post angular 2 toPromise HTTP

Body:
Hello I need to get some response after posting json object, using toPromise, its my code, respond is undefined:

export class ApiStorage{
constructor( @Inject(Http) private http: Http ){}
    rs(){
    this.http.post('http://0.0.0.0:80/student/outbound', this.json, headers)
            .toPromise()
            .then(response => {
                respond = JSON.stringify(response);
                return respond; //<- edited
            })
            .catch((error: any) => {
            ...
                });
    }
}

then when in main component I use

send(){
    respondJSON = apistorage.rs();
    console.log(respondJSON);
    }

respondJSON is undefined

Body:
respond will always be undefined in your code, because you are making an asynchronous call to a webservice, which you do not await before logging to console.

export class ApiStorage{

    constructor( @Inject(Http) private http: Http ){}

    rs() {

        return this.http.post('http://0.0.0.0:80/student/outbound', this.json, headers)
            .toPromise()
            .then(response => {
                let respond = JSON.stringify(response));
                return respond;
            })
            .catch((error: any) => {
                ...
            });
    }
}

// rs now returns a promise, which can be used like this
// inside another function
send() {
    apistorage.rs().then(res => {
        console.log(res);
    }
}


问:
What can be expressed in a compile-time constant (const val)?
The documentation for compile-time constants lists three requirements that the property needs to fulfill in order to declare it as a const val. These are:

Top-level or member of an object

Initialized with a value of type String or a primitive type

No custom getter

The "No custom getter" requirement leads me to believe that I cannot use any functions in a constant declaration, but this seems not to be the case. These compile:

```<code>const val bitmask = (5 shl 3) + 2
const val aComputedString = "Hello ${0x57.toChar()}orld${((1 shl 5) or 1).toChar()}"
const val comparedInt = 5.compareTo(6)
const val comparedString = "Hello".compareTo("World!")
const val toStringedInt = 5.compareTo(6).toString()
const val charFromString = "Hello World!".get(3)
</code>```

However, these will not compile:

```<code>// An extension function on Int.
const val coercedInt = 3.coerceIn(1..5)

// Using operator syntax to call the get-function.
const val charFromString = "Hello World!"[3]

// An immediate type is not a primitive.
const val stringFromImmediateList = "Hello World!".toList().toString()

// Using a function defined by yourself.
fun foo() = "Hello world!"
const val stringFromFunction = foo()
</code>```

What are the exact rules for compile-time constants?

Is there a list of functions I can use in a compile-time constant declaration?

答:
getter is not the method invocation, Indeed, it's a part of property declaration, for example, the code below can't be compiled.

```<code>const val charFromString get() = "foo"
//                       ^--- const using getter can't be compiled
</code>```

the aComputedString constant uses string template just as string concatination in java, for example:

```<code>static final String aComputedString = "Hello " + ((char) 0x57)
                                    + "orld" + ((char) ((1 << 5) | 1));
</code>```

and opeartors are optimized for primitive types since they have no methods in java, for example:

```<code>const val longValue = 1.toLong();
// java
static final long longValue = (long) 1 ;
</code>```

the code above your comparedString can working is that you are using kotlin.String rather java.lang.String, for the mapped type kotlin.String is also optimized, since there is no implementation in kotlin, if you try java.lang.String directly you can obtain the expected compiler error:

```<code>typealias JavaString = java.lang.String;
//         v--- error
const val comparedString = JavaString("Hello").compareTo("World!")
</code>```

the "Hello world!"[3] can't work because the indexed access operator's parameter type is a vararg, so the compiler can't optimize it since it don't know how many arguments of the get operator will be received, so it is invoked dynamically with a list of List<KtExpression> instead, for example:

```<code>const val third  = "Hello world!"[3] //error
// will generate java code as
static final String third  = "Hello world!".charAt(3) // error
</code>```

However, for the operators with fixed parameters with Basic Type will be optimized by compiler:

Note that these operations, as well as all the others, are optimized for Basic types and do not introduce overhead of function calls for them.

```<code>const val comparison = "Hello" > "World";// ok
</code>```

the String.get(n) can working because the kotlin.String is a mapper type, and it has no implementation, so the compiler know how to compute it, for example:

```<code> const val third = "Hello".get(3) // ok
 //                         ^
 // when you calling the `get` function, you never using `operator` at all.
 //  it just a function invocation
</code>```

the String.toList() can't assign to a constant variable since it is an extention method and have implementations. and kotlin const val only support primitive types and strings.

Body:
The documentation for compile-time constants lists three requirements that the property needs to fulfill in order to declare it as a const val. These are:

Top-level or member of an object

Initialized with a value of type String or a primitive type

No custom getter

The "No custom getter" requirement leads me to believe that I cannot use any functions in a constant declaration, but this seems not to be the case. These compile:

const val bitmask = (5 shl 3) + 2
const val aComputedString = "Hello ${0x57.toChar()}orld${((1 shl 5) or 1).toChar()}"
const val comparedInt = 5.compareTo(6)
const val comparedString = "Hello".compareTo("World!")
const val toStringedInt = 5.compareTo(6).toString()
const val charFromString = "Hello World!".get(3)

However, these will not compile:

// An extension function on Int.
const val coercedInt = 3.coerceIn(1..5)

// Using operator syntax to call the get-function.
const val charFromString = "Hello World!"[3]

// An immediate type is not a primitive.
const val stringFromImmediateList = "Hello World!".toList().toString()

// Using a function defined by yourself.
fun foo() = "Hello world!"
const val stringFromFunction = foo()

What are the exact rules for compile-time constants?

Is there a list of functions I can use in a compile-time constant declaration?

Body:
getter is not the method invocation, Indeed, it's a part of property declaration, for example, the code below can't be compiled.

const val charFromString get() = "foo"
//                       ^--- const using getter can't be compiled

the aComputedString constant uses string template just as string concatination in java, for example:

static final String aComputedString = "Hello " + ((char) 0x57)
                                    + "orld" + ((char) ((1 << 5) | 1));

and opeartors are optimized for primitive types since they have no methods in java, for example:

const val longValue = 1.toLong();
// java
static final long longValue = (long) 1 ;

the code above your comparedString can working is that you are using kotlin.String rather java.lang.String, for the mapped type kotlin.String is also optimized, since there is no implementation in kotlin, if you try java.lang.String directly you can obtain the expected compiler error:

typealias JavaString = java.lang.String;
//         v--- error
const val comparedString = JavaString("Hello").compareTo("World!")

the "Hello world!"[3] can't work because the indexed access operator's parameter type is a vararg, so the compiler can't optimize it since it don't know how many arguments of the get operator will be received, so it is invoked dynamically with a list of List<KtExpression> instead, for example:

const val third  = "Hello world!"[3] //error
// will generate java code as
static final String third  = "Hello world!".charAt(3) // error

However, for the operators with fixed parameters with Basic Type will be optimized by compiler:

Note that these operations, as well as all the others, are optimized for Basic types and do not introduce overhead of function calls for them.

const val comparison = "Hello" > "World";// ok

the String.get(n) can working because the kotlin.String is a mapper type, and it has no implementation, so the compiler know how to compute it, for example:

 const val third = "Hello".get(3) // ok
 //                         ^
 // when you calling the `get` function, you never using `operator` at all.
 //  it just a function invocation

the String.toList() can't assign to a constant variable since it is an extention method and have implementations. and kotlin const val only support primitive types and strings.


问:
passing function reference to a C pointer type, C will invoke the function
I have a simple question i.e. how can I pass objective-C function reference as a C function pointer so that C can invoke that function.

edit: Sorry for not providing the sample source here it is:

```<code>- (void)init {
      CLibStructure cLibObject;
      cLibObject.on_work_done = &cWorkDone;
}
</code>```

the function that will point to on_work_done will have this signature in C

```<code>static void cWorkDone(const char *workInfo);
</code>```

whereas in objective-C this is the signature that I made

```<code>- (void) workDoneWithStatusMessage:(const char *message);
</code>```

Now i want is to point cLib.on_work_done the pointer to objective-c function, if I point to standard C function it works.

答:
In short, you can't.  Not directly.

A method call is a combination of a target, the object to message, and the selector that identifies the method to call.

You need to bundle those up together somehow.   With Blocks it is easy enough.  With pure C APIs, it can typically be done with a context pointer or something like it.

Given that you posted no code, no examples, none of the API to be used, and none of the details about the C API itself, providing details is difficult.

Body:
I have a simple question i.e. how can I pass objective-C function reference as a C function pointer so that C can invoke that function.

edit: Sorry for not providing the sample source here it is:

- (void)init {
      CLibStructure cLibObject;
      cLibObject.on_work_done = &cWorkDone;
}

the function that will point to on_work_done will have this signature in C

static void cWorkDone(const char *workInfo);

whereas in objective-C this is the signature that I made

- (void) workDoneWithStatusMessage:(const char *message);

Now i want is to point cLib.on_work_done the pointer to objective-c function, if I point to standard C function it works.


问:
How to automate file handling in python
This is my code

```<code>f1 = open("file1.txt").read( ).splitlines( )
f2 = open("file2.txt").read( ).splitlines( )
print list(itertools.product(f1,f2))
</code>```

I want to run this for all files in the directory.How to do it using python. I am unable to implement suggestions given here using glob.

答:
```<code>import glob

#For any kind of file in that directory.

for file in list(glob.glob("*")):
    # do your work

#For specific kind of file in that directory. like all .py or .txt or .csv file.. etc.

for file in list(glob.glob("*.file extension")):
    # do your work
</code>```

Title: How to automate file handling in python

Body:
This is my code

f1 = open("file1.txt").read( ).splitlines( )
f2 = open("file2.txt").read( ).splitlines( )
print list(itertools.product(f1,f2))

I want to run this for all files in the directory.How to do it using python. I am unable to implement suggestions given here using glob.


问:
Django model unique_together on primary key and unique constraints
I have a model given below.

class mc(models.Model):
    ap=models.CharField(max_length=50,primary_key=True)
    de=models.CharField(max_length=50)
    STATUS=models.CharField(max_length=12,default='Y')
    class Meta:
        unique_together=(("ap","de"),)
        db_table='mc'
```

<p>I have written ap='1', de='2' to table mc.</p>

```+----+----+--------+
| ap | de | STATUS |
+----+----+--------+
| 1  | 2  | Y      |
+----+----+--------+
```

<p>Then i have tried to write ap='1' and de='3' but its just overwritten the previous one. Now the table contains</p>

```+----+----+--------+
| ap | de | STATUS |
+----+----+--------+
| 1  | 3  | Y      |
+----+----+--------+
```

<p>Then i tried to write ap='2',de='3' and its work. Since i have given unique_together, the compination of ap and de is not working.</p>

<p>But unique_together work if i haven't used 'primary_key' or 'unique' constraints on either of ap or de.</p>

<p>Will you please help me.? How to use unique_together on primary keys?</p>

<p>Actual problem is that ,i have another class mc1 which use a foreign key to the field ap.</p>

```class mc1(models.Model):

    test=models.ForeignKey(mc,on_delete=models.CASCADE,to_field='ap')
```

So mc.ap should be unique to define a foreignkey.

答:
Django does not support multiple-column primary keys. It has been a feature request for several years. Each model must have one primary key.

In your case, if ap is the primary key, then each value in ap must be unique. It is not possible to store both (ap=1, de=2) and (ap=1, de=3).

Perhaps you could add another field as the primary key. Then you will be able to have unique_together for ('ap', 'de').

Body:
I have a model given below.

class mc(models.Model):
    ap=models.CharField(max_length=50,primary_key=True)
    de=models.CharField(max_length=50)
    STATUS=models.CharField(max_length=12,default='Y')
    class Meta:
        unique_together=(("ap","de"),)
        db_table='mc'

I have written ap='1', de='2' to table mc.

+----+----+--------+
| ap | de | STATUS |
+----+----+--------+
| 1  | 2  | Y      |
+----+----+--------+

Then i have tried to write ap='1' and de='3' but its just overwritten the previous one. Now the table contains

+----+----+--------+
| ap | de | STATUS |
+----+----+--------+
| 1  | 3  | Y      |
+----+----+--------+

Then i tried to write ap='2',de='3' and its work. Since i have given unique_together, the compination of ap and de is not working.

But unique_together work if i haven't used 'primary_key' or 'unique' constraints on either of ap or de.

Will you please help me.? How to use unique_together on primary keys?

Actual problem is that ,i have another class mc1 which use a foreign key to the field ap.

class mc1(models.Model):

    test=models.ForeignKey(mc,on_delete=models.CASCADE,to_field='ap')

So mc.ap should be unique to define a foreignkey.


问:
Right way of using RxJava + Retrofit 2
I have such JSON:

```<code>{
"success":true,
"data":[
   {
      "id":"29",
     "name":"\u0420\u0435\u0441\u0442\u043e\u0440\u0430\u0446\u0456\u044f \u0411\u0430\u0447\u0435\u0432\u0441\u044c\u043a\u0438\u0445 \/ Baczewski Restaurant",
     "street":"\u0432\u0443\u043b.    \u0428\u0435\u0432\u0441\u044c\u043a\u0430, 8",
     "latitude":"49.842292845502",
     "longitude":"24.029848249565",
     "image":"https:\/\/i.onthe.io\/j9aocq72r2lfsmoh9.r500x500.01ff9fff.jpg"
     },
     ...
    ]
    }
</code>```

According  to  it  have  to  Classes (pojo) created  with  schema to pojo. First one provides  method  to  get data  from  data array - >

```<code>public List<Datum> getData() {
    return data;
}
</code>```

And the second  one  is a model  of this data.

While  using  only  retrofit  2.0  I perform a call, parse each object  from the  data array and add it to RecyclerView.Adapter

```<code>Call<PlaceList> call = service.list(1, offset, 10);
call.enqueue(new Callback<PlaceList>() {
        @Override
        public void onResponse(Call<PlaceList> call, Response<PlaceList> response) {
            final int size = response.body().getData().size();
            for (int i = 0; i < size; i++) {
                places.add(response.body().getData().get(i));
            }
            handler.post(new Runnable() {
                @Override
                public void run() {
                    if (offset == 0)
                        //   adapter.notifyItemRangeInserted(0, foodDataList.size());
                        placeRecyclerAdapter.notifyDataSetChanged();
                    else
                        placeRecyclerAdapter.notifyItemRangeChanged(places.size() - size, places.size());
                }
            });

        }

        @Override
        public void onFailure(Call<PlaceList> call, Throwable t) {

        }
    });
    _______________

    public interface Places {
@GET("places.getPlaces")
Call<PlaceList> list(
        @Query("type") int type,
        @Query("offset") int offset,
        @Query("limit") int limit);
       }
</code>```

So this a  usual  way  for  me. Now  I  want to do the same using RxJava.

Here is my interface:

```<code>public interface Places {
@GET("places.getPlaces")
Observable<PlaceList> list(@Query("type") int type,
                             @Query("offset") int offset,
                             @Query("limit") int limit);
}
</code>```

And this is how I perform call:

```<code>  Observable<PlaceList> call = service.list(1, offset, 10);
    subscription = call.subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<PlaceList>() {
                @Override
                public void onCompleted() {
                    System.out.println("onComplete");
                }

                @Override
                public void onError(Throwable e) {
                    System.out.println("onError");
                    e.printStackTrace();
                }

                @Override
                public void onNext(PlaceList data) {
                    placeRecyclerAdapter.addData(data.getData());
                }
            });
</code>```

Yeah, it's also works, but was it a right  way of using Rx? I tried to compare time needed for parsing, but didn't see any notable difference.
I'm just on my first day of studying RxJava, after  reading few articles. So what is the right way to feel the power of RxJava?

答:
You are using it correctly, RxJava has very much power which you can leverage in order to improve Performance.

Where to use?
1. On user events, like Button click, Key events
2. Respond to latency bound IO. Disk/network read/write
3. Events triggered by Hardware/sensors

Should not start Thread manually from Observable create.

Retrofit Network call with RxJava:
Use Single : As our API will not give data in a pieces or multiple times. Instead it will emit everything in just one call.
So, in case of Observable onCompleted() will follow as soon as onNext() happens.
So, it would be better to use Single for API calling.

Use Completable : Whenever we need to just update data to Server through API, and We do not bother about what should be the result. We just meant if service is successful or not.  In this cases we are not expecting to emit anything. So use of Completable is encouraged in the cases.

For progress view hide/show:
Bind this two events with doOnSubscribe() and doFinally().
This are two operators, so we can logically bind them with RxCall.

RxJava Error Handling:

onErrorResumeNext( ) — instructs an Observable to emit a sequence of items (which is another observable)if it encounters an error

onErrorReturn( ) — instructs an Observable to emit a particular item when it encounters an error

onExceptionResumeNext( ) — instructs an Observable to continue emitting items after it encounters an exception (but not another variety of throwable)

retry( ) — if a source Observable emits an error, resubscribe to it in the hopes that it will complete without error.
    Here we can also pass argument for How many times retry should happen.
    Like. retry(4). It will retry four times and after that if again error occures then will throw  an error.

retryWhen( ) — if a source Observable emits an error, pass that error to another Observable to determine whether to resubscribe to the source

RxAndroid for View Binding:

Think Reactive:
We can use RxJava for all view events including click event, scroll event, drag event.
In short, we can replace every Listeners with RxJava observables.

Available Libraries to use at View level:
RxBinding, RxSupport-v4, RxAppCompat-v7, RxRecyclerView, RxDesign, RxLeanBack.

RxBinding with MVP:
We will return Observable from View.
This observable will fetch to Presenter and will do Subscription at Presenter.

RxAdapter: we can use this for data change event in Adapter. Typically available for Android Listview.
RxRecyclerView: For recyclerview adapter data change events we can use this.

Title: Right way of using RxJava + Retrofit 2

Body:
I have such JSON:

{
"success":true,
"data":[
   {
      "id":"29",
     "name":"\u0420\u0435\u0441\u0442\u043e\u0440\u0430\u0446\u0456\u044f \u0411\u0430\u0447\u0435\u0432\u0441\u044c\u043a\u0438\u0445 \/ Baczewski Restaurant",
     "street":"\u0432\u0443\u043b.    \u0428\u0435\u0432\u0441\u044c\u043a\u0430, 8",
     "latitude":"49.842292845502",
     "longitude":"24.029848249565",
     "image":"https:\/\/i.onthe.io\/j9aocq72r2lfsmoh9.r500x500.01ff9fff.jpg"
     },
     ...
    ]
    }

According  to  it  have  to  Classes (pojo) created  with  schema to pojo. First one provides  method  to  get data  from  data array - >

public List<Datum> getData() {
    return data;
}

And the second  one  is a model  of this data.

While  using  only  retrofit  2.0  I perform a call, parse each object  from the  data array and add it to RecyclerView.Adapter

Call<PlaceList> call = service.list(1, offset, 10);
call.enqueue(new Callback<PlaceList>() {
        @Override
        public void onResponse(Call<PlaceList> call, Response<PlaceList> response) {
            final int size = response.body().getData().size();
            for (int i = 0; i < size; i++) {
                places.add(response.body().getData().get(i));
            }
            handler.post(new Runnable() {
                @Override
                public void run() {
                    if (offset == 0)
                        //   adapter.notifyItemRangeInserted(0, foodDataList.size());
                        placeRecyclerAdapter.notifyDataSetChanged();
                    else
                        placeRecyclerAdapter.notifyItemRangeChanged(places.size() - size, places.size());
                }
            });

        }

        @Override
        public void onFailure(Call<PlaceList> call, Throwable t) {

        }
    });
    _______________

    public interface Places {
@GET("places.getPlaces")
Call<PlaceList> list(
        @Query("type") int type,
        @Query("offset") int offset,
        @Query("limit") int limit);
       }

So this a  usual  way  for  me. Now  I  want to do the same using RxJava.

Here is my interface:

public interface Places {
@GET("places.getPlaces")
Observable<PlaceList> list(@Query("type") int type,
                             @Query("offset") int offset,
                             @Query("limit") int limit);
}

And this is how I perform call:

  Observable<PlaceList> call = service.list(1, offset, 10);
    subscription = call.subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<PlaceList>() {
                @Override
                public void onCompleted() {
                    System.out.println("onComplete");
                }

                @Override
                public void onError(Throwable e) {
                    System.out.println("onError");
                    e.printStackTrace();
                }

                @Override
                public void onNext(PlaceList data) {
                    placeRecyclerAdapter.addData(data.getData());
                }
            });

Yeah, it's also works, but was it a right  way of using Rx? I tried to compare time needed for parsing, but didn't see any notable difference.
I'm just on my first day of studying RxJava, after  reading few articles. So what is the right way to feel the power of RxJava?


问:
Caused by: org.springframework.beans.factory.CannotLoadBeanClassException:
```<code> Caused by: org.springframework.beans.factory.CannotLoadBeanClassException:
 Cannot find class

 [org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean]

 for bean with name 'sessionFactory' defined in ServletContext resource >
  [/WEB-INF/cardreaderapp-servlet.xml];
     nested exception is java.lang.ClassNotFoundException:
org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean
</code>```

答:
From the error log it is clear that jvm can't find the class

```<code>org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean
</code>```

Make sure the dependent jar is there in your project. Other wise if you are using maven make sure the corresponding dependency(spring-orm) are added in the pom.xml file.

```<code><dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-orm</artifactId>
    <version>3.1.1.RELEASE</version>
</dependency>
</code>```

Body:
From the error log it is clear that jvm can't find the class

org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean

Make sure the dependent jar is there in your project. Other wise if you are using maven make sure the corresponding dependency(spring-orm) are added in the pom.xml file.

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-orm</artifactId>
    <version>3.1.1.RELEASE</version>
</dependency>


问:
How to use Windows User Login to authenticate with Webservice
I have a client-server application (both Windows, client is WPF, non-UWP) and i want to do authentication via active directory. My idea is to take the credentials (or a token) from the windows machine that the client is on and send that information to the server (via webservice, IIS, asp.net). the server then checks with ad if the credentials are valid and does authorization...
So the key points would be:

extract credentials/token from client-windows

send it via vebservice to server (that part should be simple)

validation on server against active directory

How can I achieve that?

答:
If you want to check for a windows user authentication in a desktop application you can simpy use the

```<code>Environment.UserName
</code>```

Variable, it provides the username of the current logged in user.
if you want to check if it is an active directory user you can call a function like this:

```<code>public bool UserExists(string username)
{
   // create your domain context
   using (PrincipalContext domain = new PrincipalContext(ContextType.Domain))
   {
       // find the user
       UserPrincipal foundUser = UserPrincipal.FindByIdentity(domain, IdentityType.Name, username);

       return foundUser != null;
    }
}
</code>```

With your new request you can split the code above:

In the client you can get the AD username and domain using Environment variable, pass it to the server and check if the user exist using the UserExist() function

Body:
If you want to check for a windows user authentication in a desktop application you can simpy use the

Environment.UserName

Variable, it provides the username of the current logged in user.
if you want to check if it is an active directory user you can call a function like this:

public bool UserExists(string username)
{
   // create your domain context
   using (PrincipalContext domain = new PrincipalContext(ContextType.Domain))
   {
       // find the user
       UserPrincipal foundUser = UserPrincipal.FindByIdentity(domain, IdentityType.Name, username);

       return foundUser != null;
    }
}

With your new request you can split the code above:

In the client you can get the AD username and domain using Environment variable, pass it to the server and check if the user exist using the UserExist() function


问:
Linq with dot notation - which is better form or what's the difference between these two?
I've been reading Jon Skeet's C# In Depth: Second Edition and I noticed something slightly different in one of his examples from something I do myself.

He has something similar to the following:

```<code>var item = someObject.Where(user => user.Id == Id).Single();
</code>```

Whereas I've been doing the following:

```<code>var item = someObject.Single(user => user.Id == Id);
</code>```

Is there any real difference between the two? I know Jon Skeet is pretty much the c# god so I tend to think his knowledge in this area is better than mine so I might be misunderstanding something here. Hope someone can help.

答:
I typically think in terms of "filter then take a single value". On the other hand, when it comes to Count I'll often use the version with the predicate. For Any I can go either way pretty easily depending on my mood :)

Ultimately it's unlikely to make any significant difference - use whichever is easier to understand at the time. I certainly wasn't trying to avoid using the versions with predicates etc - and I give some examples using them on P499.

While there are some situations with "definitely more readable" versions, many other cases are pretty much equally readable either way.

Body:
I've been reading Jon Skeet's C# In Depth: Second Edition and I noticed something slightly different in one of his examples from something I do myself.

He has something similar to the following:

var item = someObject.Where(user => user.Id == Id).Single();

Whereas I've been doing the following:

var item = someObject.Single(user => user.Id == Id);

Is there any real difference between the two? I know Jon Skeet is pretty much the c# god so I tend to think his knowledge in this area is better than mine so I might be misunderstanding something here. Hope someone can help.


问:
how to handle redux saga error in the wrapper?
This is the Normal Way:

```<code>function* saga1() {
  try {
    // do stuff
  } catch (err) {
    // handle err
  }
}

function* saga2() {
  try {
  } catch (err) {
  }
}

function* wrapper() {
  yield [
    takeLatest('saga1', saga1),
    takeLatest('saga2', saga2),
  ];
}
</code>```

This is Expected Way:

```<code>function* saga1() {
}

function* saga2() {
}

function* wrapper() {
  try {
    takeLatest('saga1', saga1),
    takeLatest('saga2', saga2),
  } catch (err) {
    // handle errors
  }
}
</code>```

Is there anyway to achieve above way to handle errors? Using normal way sometimes leading to repeatedly handle same error.

答:
Easiest way for this case is fork as using parallel dynamic effect in saga. Of course, it is not real thread, but way to write sequence of asynchronous operations.

Let see your example in depth. Construction like yield [ takeA(), takeB() ] supposes that you delegate A&B operation to saga workflow with supplied callback. In other words, execution of wrapper is done for this moment, so try/catch is not appropriate.

Is alternative you can fork as parallel dynamic effect for two or more independent saga-processes, and make infinite loop in which of them.

Code:

```<code>function* proc1() {
  while(true) {
    yield call(() => new Promise(resolve => setTimeout(resolve, 1500)));
    throw new Error('Err1')
  }
}

function* proc2() {
  while(true) {
    yield call(() => new Promise(resolve => setTimeout(resolve, 2000)));
    throw new Error('Err2')
  }
}

function* watchLoadRequest() {
  try {
    yield [call(proc1), call(proc2)]
  } catch(err) {
    console.log('@@ERROR@@', err);
  }
}
</code>```

Of course, you should implement custom business login in parallel procedures. If you need a persistent/shared state between them, use object argument with appropriate fields.

Body:
This is the Normal Way:

function* saga1() {
  try {
    // do stuff
  } catch (err) {
    // handle err
  }
}

function* saga2() {
  try {
  } catch (err) {
  }
}

function* wrapper() {
  yield [
    takeLatest('saga1', saga1),
    takeLatest('saga2', saga2),
  ];
}

This is Expected Way:

function* saga1() {
}

function* saga2() {
}

function* wrapper() {
  try {
    takeLatest('saga1', saga1),
    takeLatest('saga2', saga2),
  } catch (err) {
    // handle errors
  }
}

Is there anyway to achieve above way to handle errors? Using normal way sometimes leading to repeatedly handle same error.

Body:
Easiest way for this case is fork as using parallel dynamic effect in saga. Of course, it is not real thread, but way to write sequence of asynchronous operations.

Let see your example in depth. Construction like yield [ takeA(), takeB() ] supposes that you delegate A&B operation to saga workflow with supplied callback. In other words, execution of wrapper is done for this moment, so try/catch is not appropriate.

Is alternative you can fork as parallel dynamic effect for two or more independent saga-processes, and make infinite loop in which of them.

Code:

function* proc1() {
  while(true) {
    yield call(() => new Promise(resolve => setTimeout(resolve, 1500)));
    throw new Error('Err1')
  }
}

function* proc2() {
  while(true) {
    yield call(() => new Promise(resolve => setTimeout(resolve, 2000)));
    throw new Error('Err2')
  }
}

function* watchLoadRequest() {
  try {
    yield [call(proc1), call(proc2)]
  } catch(err) {
    console.log('@@ERROR@@', err);
  }
}

Of course, you should implement custom business login in parallel procedures. If you need a persistent/shared state between them, use object argument with appropriate fields.


问:
.parent().remove() issue
I have a jQuery-based form where you can add extra people to the application.  I'm cloning the first fieldset and adding it onto the end up to a max of 3 additional people. When you've added 1 extra person then you have the option to remove that person.

However, my remove button isn't working.  It was, earlier, until I added the extra functions to the cloning to change the ids of other elements within the fieldset.

I'm using:

```<code>$(".remove").click(function() {
    $(this).parent().remove();
</code>```

which was working originally but now it's not and I can't figure out why.

I've taken out the lines that stop the first 'delete this person' just to show that the first one still works but the rest don't. (I'll be positioning the first one off stage eventually when it's fixed)

Probably easier to see it so I put it up here.

So essentially, any ideas why my 'delete this person' isn't working on everything but the first section?

答:
You can do this for delete the parent:

```<code> $(document).on("click", ".remove", function() {
      $(this).parent().remove();
 });
</code>```

or you can do this for delete all parents:

```<code> $(document).on("click", ".remove", function() {
      $(this).parents().remove();
 });
</code>```

Title: .parent().remove() issue

Body:
I have a jQuery-based form where you can add extra people to the application.  I'm cloning the first fieldset and adding it onto the end up to a max of 3 additional people. When you've added 1 extra person then you have the option to remove that person.

However, my remove button isn't working.  It was, earlier, until I added the extra functions to the cloning to change the ids of other elements within the fieldset.

I'm using:

$(".remove").click(function() {
    $(this).parent().remove();

which was working originally but now it's not and I can't figure out why.

I've taken out the lines that stop the first 'delete this person' just to show that the first one still works but the rest don't. (I'll be positioning the first one off stage eventually when it's fixed)

Probably easier to see it so I put it up here.

So essentially, any ideas why my 'delete this person' isn't working on everything but the first section?

Body:
You can do this for delete the parent:

 $(document).on("click", ".remove", function() {
      $(this).parent().remove();
 });

or you can do this for delete all parents:

 $(document).on("click", ".remove", function() {
      $(this).parents().remove();
 });


问:
Replace comma with newline and write to text file
I want to take value on the database and replace the comma with a newline and then write to a text file.

Example:

```<code>SELECT column FROM table WHERE ID = 6
Result: Monday,Tuesday,Wednesday,Thursday,Friday
</code>```

I want it to then remove the commas and write to a .txt file with newline.

Result:

```<code>Monday

Tuesday

Wednesday

Thursday

Friday
</code>```

Hope this makes sense.

答:
Use something like</p>

```<code>file_put_contents("file.txt", str_replace(",", "\r\n", $string));
</code>```

Body:
I want to take value on the database and replace the comma with a newline and then write to a text file.

Example:

SELECT column FROM table WHERE ID = 6
Result: Monday,Tuesday,Wednesday,Thursday,Friday

I want it to then remove the commas and write to a .txt file with newline.

Result:

Monday

Tuesday

Wednesday

Thursday

Friday

Hope this makes sense.

Body:
Use something like

file_put_contents("file.txt", str_replace(",", "\r\n", $string));


问:
Parse a file for all occurrences of a string and generate key-values in JSON

I have a file (https://pastebin.com/STgtBRS8) in which I need to search for all the occurrences of the word "silencedetect".

I then have to generate a JSON file that contains the key-values of “silence_start”, “silence_end”, and “silence_duration”.

The JSON file should look like something like this:

```<code>[
{
"id": 1,
"silence_start": -0.012381,
"silence_end": 2.2059,
"silence_duration": 2.21828
},
{
"id": 2,
"silence_start": 5.79261,
"silence_end": 6.91955,
"silence_duration": 1.12694,
}
]
</code>```

This is what I have tried:

```<code>with open('volume_data.csv', 'r') as myfile:
    data = myfile.read().replace('\n', '')

for line in data:
    if "silencedetect" in data:
        #read silence_start, silence_end, and silence_duration and put in json
</code>```

I am unable to associate the 3 key-value pairs with each "silencedetect". How can I parse the key-values and get them in JSON format ?

答:
Assuming your data is ordered, you can simply stream-parse it, no need for regex and loading of the whole file at all:

```<code>import json

parsed = []  # a list to hold our parsed values
with open("entries.dat", "r") as f:  # open the file for reading
    current_id = 1  # holds our ID
    entry = None  # holds the current parsed entry
    for line in f:  # ... go through the file line by line
        if line[:14] == "[silencedetect":  # parse the lines starting with [silencedetect
            if entry:  # we already picked up silence_start
                index = line.find("silence_end:")  # find where silence_end starts
                value = line[index + 12:line.find("|", index)].strip()  # the number after it
                entry["silence_end"] = float(value)  # store the silence_end
                # the following step is optional, instead of parsing you can just calculate
                # the silence_duration yourself with:
                # entry["silence_duration"] = entry["silence_end"] - entry["silence_start"]
                index = line.find("silence_duration:")  # find where silence_duration starts
                value = line[index + 17:].strip()  # grab the number after it
                entry["silence_duration"] = float(value)  # store the silence_duration
                # and now that we have everything...
                parsed.append(entry)  # add the entry to our parsed list
                entry = None  # blank out the entry for the next step
            else:  # find silence_start first
                index = line.find("silence_start:")  # find where silence_start, well, starts
                value = line[index + 14:].strip()  # grab the number after it
                entry = {"id": current_id}  # store the current ID...
                entry["silence_start"] = float(value)  # ... and the silence_start
                current_id += 1  # increase our ID value for the next entry

# Now that we have our data, we can easily turn it into JSON and print it out if needed
your_json = json.dumps(parsed, indent=4)  # holds the JSON, pretty-printed
print(your_json)  # let's print it...
</code>```

And you get:

```<code>[
    {
        "silence_end": 2.2059,
        "silence_duration": 2.21828,
        "id": 1,
        "silence_start": -0.012381
    },
    {
        "silence_end": 6.91955,
        "silence_duration": 1.12694,
        "id": 2,
        "silence_start": 5.79261
    },
    {
        "silence_end": 9.12544,
        "silence_duration": 0.59288,
        "id": 3,
        "silence_start": 8.53256
    },
    {
        "silence_end": 10.7276,
        "silence_duration": 1.0805,
        "id": 4,
        "silence_start": 9.64712
    },
    #
    # etc.
    #
    {
        "silence_end": 795.516,
        "silence_duration": 0.68576,
        "id": 189,
        "silence_start": 794.83
    }
]
</code>```

Keep in mind that JSON doesn't subscribe order of data (nor does Python dict before v3.5) so the id won't necessarily appear at the first place but the data validity is just the same.

I've purposefully separated the initial entry creation so you can use collections.OrderedDict as a drop-in replacement (i.e. entry = collections.OrderedDict({"id": current_id})) to preserve the order if that's what you wish.

Body:
I have a file (https://pastebin.com/STgtBRS8) in which I need to search for all the occurrences of the word "silencedetect".

I then have to generate a JSON file that contains the key-values of “silence_start”, “silence_end”, and “silence_duration”.

The JSON file should look like something like this:

[
{
"id": 1,
"silence_start": -0.012381,
"silence_end": 2.2059,
"silence_duration": 2.21828
},
{
"id": 2,
"silence_start": 5.79261,
"silence_end": 6.91955,
"silence_duration": 1.12694,
}
]

This is what I have tried:

with open('volume_data.csv', 'r') as myfile:
    data = myfile.read().replace('\n', '')

for line in data:
    if "silencedetect" in data:
        #read silence_start, silence_end, and silence_duration and put in json

I am unable to associate the 3 key-value pairs with each "silencedetect". How can I parse the key-values and get them in JSON format ?

Body:
Assuming your data is ordered, you can simply stream-parse it, no need for regex and loading of the whole file at all:

import json

parsed = []  # a list to hold our parsed values
with open("entries.dat", "r") as f:  # open the file for reading
    current_id = 1  # holds our ID
    entry = None  # holds the current parsed entry
    for line in f:  # ... go through the file line by line
        if line[:14] == "[silencedetect":  # parse the lines starting with [silencedetect
            if entry:  # we already picked up silence_start
                index = line.find("silence_end:")  # find where silence_end starts
                value = line[index + 12:line.find("|", index)].strip()  # the number after it
                entry["silence_end"] = float(value)  # store the silence_end
                # the following step is optional, instead of parsing you can just calculate
                # the silence_duration yourself with:
                # entry["silence_duration"] = entry["silence_end"] - entry["silence_start"]
                index = line.find("silence_duration:")  # find where silence_duration starts
                value = line[index + 17:].strip()  # grab the number after it
                entry["silence_duration"] = float(value)  # store the silence_duration
                # and now that we have everything...
                parsed.append(entry)  # add the entry to our parsed list
                entry = None  # blank out the entry for the next step
            else:  # find silence_start first
                index = line.find("silence_start:")  # find where silence_start, well, starts
                value = line[index + 14:].strip()  # grab the number after it
                entry = {"id": current_id}  # store the current ID...
                entry["silence_start"] = float(value)  # ... and the silence_start
                current_id += 1  # increase our ID value for the next entry

# Now that we have our data, we can easily turn it into JSON and print it out if needed
your_json = json.dumps(parsed, indent=4)  # holds the JSON, pretty-printed
print(your_json)  # let's print it...

And you get:

[
    {
        "silence_end": 2.2059,
        "silence_duration": 2.21828,
        "id": 1,
        "silence_start": -0.012381
    },
    {
        "silence_end": 6.91955,
        "silence_duration": 1.12694,
        "id": 2,
        "silence_start": 5.79261
    },
    {
        "silence_end": 9.12544,
        "silence_duration": 0.59288,
        "id": 3,
        "silence_start": 8.53256
    },
    {
        "silence_end": 10.7276,
        "silence_duration": 1.0805,
        "id": 4,
        "silence_start": 9.64712
    },
    #
    # etc.
    #
    {
        "silence_end": 795.516,
        "silence_duration": 0.68576,
        "id": 189,
        "silence_start": 794.83
    }
]

Keep in mind that JSON doesn't subscribe order of data (nor does Python dict before v3.5) so the id won't necessarily appear at the first place but the data validity is just the same.

I've purposefully separated the initial entry creation so you can use collections.OrderedDict as a drop-in replacement (i.e. entry = collections.OrderedDict({"id": current_id})) to preserve the order if that's what you wish.


问:
C/C++ program that prints its own source code as its output
Wikipedia says it's called a quine and someone gave the code below:

```<code>char*s="char*s=%c%s%c;main(){printf(s,34,s,34);}";main(){printf(s,34,s,34);}
</code>```

But, obviously you have to add

```<code>#include <stdio.h> //corrected from #include <stdlib.h>
</code>```

so that the printf() could work.

Literally, since the above program did not print #include <stdio.h>, it is not a solution (?)

I am confused about the literal requirement of "print its own source code", and any purpose of this kind of problems, especially at interviews.

答:
Quine (Basic self-relicating code in c++`// Self replicating basic code

[http://www.nyx.net/~gthompso/quine.htm#links]
[https://pastebin.com/2UkGbRPF#links]

// Self replicating basic code

```<code>#include <iostream>     //1 line
#include <string>       //2 line
using namespace std;        //3 line
                //4 line
int main(int argc, char* argv[])    //5th line
{
        char q = 34;            //7th line
        string l[] = {      //8th line  ---- code will pause here and will resume later in 3rd for loop
 " ",
 "#include <iostream>       //1 line   ",
 "#include <string>     //2 line    ",
 "using namespace std;      //3 line    ",
 "              //4 line    ",
 "int main(int argc, char* argv[])  //5th line  ",
 "{",
 "        char q = 34;          //7th line  ",
 "        string l[] = {        //8th line  ",
 "        };                //9th resume printing end part of code  ",      //3rd loop starts printing from here
 "        for(int i = 0; i < 9; i++)        //10th first half code ",
 "                cout << l[i] << endl;     //11th line",
 "        for(int i = 0; i < 18; i++)   //12th whole code ",
 "                cout << l[0] + q + l[i] + q + ',' << endl;    13th line",
 "        for(int i = 9; i < 18; i++)   //14th last part of code",
 "                cout << l[i] << endl;     //15th line",
 "        return 0;         //16th line",
 "}             //17th line",
        };                                          //9th resume printing end part of code
        for(int i = 0; i < 9; i++)      //10th first half code
                cout << l[i] << endl;       //11th line
        for(int i = 0; i < 18; i++) //12th whole code
                cout << l[0] + q + l[i] + q + ',' << endl;  13th line
        for(int i = 9; i < 18; i++) //14th last part of code
                cout << l[i] << endl;       //15th line
        return 0;           //16th line
}               //17th line
</code>```

Body:
Wikipedia says it's called a quine and someone gave the code below:

char*s="char*s=%c%s%c;main(){printf(s,34,s,34);}";main(){printf(s,34,s,34);}

But, obviously you have to add

#include <stdio.h> //corrected from #include <stdlib.h>

so that the printf() could work.

Literally, since the above program did not print #include <stdio.h>, it is not a solution (?)

I am confused about the literal requirement of "print its own source code", and any purpose of this kind of problems, especially at interviews.

Body:
Quine (Basic self-relicating code in c++`// Self replicating basic code

[http://www.nyx.net/~gthompso/quine.htm#links]
[https://pastebin.com/2UkGbRPF#links]

// Self replicating basic code

#include <iostream>     //1 line
#include <string>       //2 line
using namespace std;        //3 line
                //4 line
int main(int argc, char* argv[])    //5th line
{
        char q = 34;            //7th line
        string l[] = {      //8th line  ---- code will pause here and will resume later in 3rd for loop
 " ",
 "#include <iostream>       //1 line   ",
 "#include <string>     //2 line    ",
 "using namespace std;      //3 line    ",
 "              //4 line    ",
 "int main(int argc, char* argv[])  //5th line  ",
 "{",
 "        char q = 34;          //7th line  ",
 "        string l[] = {        //8th line  ",
 "        };                //9th resume printing end part of code  ",      //3rd loop starts printing from here
 "        for(int i = 0; i < 9; i++)        //10th first half code ",
 "                cout << l[i] << endl;     //11th line",
 "        for(int i = 0; i < 18; i++)   //12th whole code ",
 "                cout << l[0] + q + l[i] + q + ',' << endl;    13th line",
 "        for(int i = 9; i < 18; i++)   //14th last part of code",
 "                cout << l[i] << endl;     //15th line",
 "        return 0;         //16th line",
 "}             //17th line",
        };                                          //9th resume printing end part of code
        for(int i = 0; i < 9; i++)      //10th first half code
                cout << l[i] << endl;       //11th line
        for(int i = 0; i < 18; i++) //12th whole code
                cout << l[0] + q + l[i] + q + ',' << endl;  13th line
        for(int i = 9; i < 18; i++) //14th last part of code
                cout << l[i] << endl;       //15th line
        return 0;           //16th line
}               //17th line


问:
How to prevent function call of multiple time to a single time
I have a situation where i want to call a function only a single time but it is firing multiple time how to prevent that.

http://jsfiddle.net/pdzTW/224/

```<code>function howManyTimesIwasCalled(value){
  console.log('i have called so many time '+value);
}

$(document).ready(function() {
  alert('please scroll output window and check the console');

  $(document).scroll(function() {
    var cutoff = $(window).scrollTop() + 200;

    $('div').each(function(e) {
      if ($(this).offset().top + $(this).height() > cutoff) {
        $('div').removeClass('current');
        $(this).addClass('current');
        howManyTimesIwasCalled($(this).data('value'));

        //callGoogleMapHere(data..);

        return false; // stops the iteration after the first one on
      }
  });
});
</code>```

答:
The scroll event and resize event fire multiple times as a user does this. To help prevent this. Use a global boolean to check if the function has fired.</p>

```<code>var tmp = 0;
$.fn.scrollStopped = function(callback) {
  $(this).scroll(function(){
    if(tmp == 0){
      var self = this, $this = $(self);
      if ($this.data('scrollTimeout')) {
        clearTimeout($this.data('scrollTimeout'));
      }
      $this.data('scrollTimeout', setTimeout(callback,300,self));
      tmp = 1;
    }
  });
};

$(window).scrollStopped(function(){
    console.log('Test')
  tmp=0;
})
</code>```

Body:
I have a situation where i want to call a function only a single time but it is firing multiple time how to prevent that.

http://jsfiddle.net/pdzTW/224/

function howManyTimesIwasCalled(value){
  console.log('i have called so many time '+value);
}

$(document).ready(function() {
  alert('please scroll output window and check the console');

  $(document).scroll(function() {
    var cutoff = $(window).scrollTop() + 200;

    $('div').each(function(e) {
      if ($(this).offset().top + $(this).height() > cutoff) {
        $('div').removeClass('current');
        $(this).addClass('current');
        howManyTimesIwasCalled($(this).data('value'));

        //callGoogleMapHere(data..);

        return false; // stops the iteration after the first one on
      }
  });
});

Body:
The scroll event and resize event fire multiple times as a user does this. To help prevent this. Use a global boolean to check if the function has fired.

var tmp = 0;
$.fn.scrollStopped = function(callback) {
  $(this).scroll(function(){
    if(tmp == 0){
      var self = this, $this = $(self);
      if ($this.data('scrollTimeout')) {
        clearTimeout($this.data('scrollTimeout'));
      }
      $this.data('scrollTimeout', setTimeout(callback,300,self));
      tmp = 1;
    }
  });
};

$(window).scrollStopped(function(){
    console.log('Test')
  tmp=0;
})