问:
How to remove this loop to call div elements separately?
Here's the code I'm using for the audio players:

https://codepen.io/katzkode/pen/ZbxYYG

What it does:

Creates multiple audio players at once (by using a single div element) for each song using a loop.

Loop:

```<code>/* createAudioElements
 * create audio elements for each file in files */
function createAudioElements() {
    for (f in files) {
        var audioString = "<audio id=\"audio-" + f + "\" class=\"audio\" preload=\"true\"><source src=\"http://www.alexkatz.me/codepen/music/" + files[f] + "\"></audio>";
        $("#audio-players").append(audioString);
    }
}

/* createAudioPlayers
 * create audio players for each file in files */
function createAudioPlayers() {
    for (f in files) {
        var playerString = "<div id=\"audioplayer-" + f + "\" class=\"audioplayer\"><button id=\"playbutton-" + f + "\" class=\"play playbutton\"></button><div id=\"timeline-" + f + "\" class=\"timeline\"><div id=\"playhead-" + f + "\" class=\"playhead\"></div></div></div>";
        $("#audio-players").append(playerString);
    }
}
</code>```

var files:

```<code>var files = ["interlude.mp3", // 0
            "chooseyourweapon.mp3", // 1
            "interlude.mp3", // 2
            "scriptures.mp3" // 3
            ];
</code>```

Is invoked in HTML when I use:

```<code><div id="audio-players"></div>
</code>```

What I'm trying to accomplish:

Remove the loop so I could insert any player separately and tweak them separately however I want like this: https://puu.sh/ynD4q/6ab2ba7816.png

I want to use this code to invoke the desired audio player:

```<code><audio id="audio-0" class="audio" preload="true">
    <source src="http://www.alexkatz.me/codepen/music/interlude.mp3">
</audio>
<div id="audioplayer-0" class="audioplayer">
    <button id="playbutton-0" class="play playbutton"></button>
    <div id="timeline-0" class="timeline">
        <div id="playhead-0" class="playhead"></div>
    </div>
</div>
</code>```

When I try to use it, the play / stop / change position buttons stop working.

It's driving me crazy, I just started learning jQuery. Thank you a lot!

答:
Change files array to the settings object and add object for each of the files with elementId and src properties:

```<code>var settings = [
    {"elementId" : "audio-player-1", "src" : "http://www.alexkatz.me/codepen/music/interlude.mp3"},
    {"elementId" : "audio-player-2", "src" : "http://www.alexkatz.me/codepen/music/chooseyourweapon.mp3"},
    {"elementId" : "audio-player-3", "src" : "http://www.alexkatz.me/codepen/music/scriptures.mp3"}
];
</code>```

It's very usable, because you can add any property you want. And with src attribute you can add audio files from any website that allows it.

Then in createAudioElements set new src attribute to settings[f].src.

Afterwards in createAudioElements and createAudioPlayers functions change the selector name (to which the rows gathered in the loop are added) to the dynamically generated from the relevant elementId property $("#" + files[f].elementId).

// Event listener for DOM
document.addEventListener("DOMContentLoaded", theDOMHasLoaded, false);

// array of audio files (stored in a folder called music)
var settings = [{
    "elementId": "audio-player-1",
    "src": "http://www.alexkatz.me/codepen/music/interlude.mp3"
  },
  {
    "elementId": "audio-player-2",
    "src": "http://www.alexkatz.me/codepen/music/chooseyourweapon.mp3"
  },
  {
    "elementId": "audio-player-3",
    "src": "http://www.alexkatz.me/codepen/music/scriptures.mp3"
  }
];

///////////////////////////////////////////////
// Find and store audio info
///////////////////////////////////////////////

// array for AudioObjects
var audioList = [];
// components and the index for their AudioObject
var componentDict = {};
// store AudioObject that is currently playing
var playingAudio = null;
// store playhead id if one is being dragged
var onplayhead = null;

/* AudioObject Constructor */
function AudioObject(audio, duration) {
  this.audio = audio;
  this.id = audio.id;
  this.duration = duration;
}
/* bindAudioPlayer
 * Store audioplayer components in correct AudioObject
 * num identifes correct audioplayer
 */
AudioObject.prototype.bindAudioPlayer = function(num) {
  this.audioplayer = document.getElementById("audioplayer-" + num);
  this.playbutton = document.getElementById("playbutton-" + num);
  this.timeline = document.getElementById("timeline-" + num);
  this.playhead = document.getElementById("playhead-" + num);
  this.timelineWidth = this.timeline.offsetWidth - this.playhead.offsetWidth
}

/* addEventListeners() */
AudioObject.prototype.addEventListeners = function() {
  this.audio.addEventListener("timeupdate", AudioObject.prototype.timeUpdate, false);
  this.audio.addEventListener("durationchange", AudioObject.prototype.durationChange, false);
  this.timeline.addEventListener("click", AudioObject.prototype.timelineClick, false);
  this.playbutton.addEventListener("click", AudioObject.prototype.pressPlay, false);
  // Makes playhead draggable
  this.playhead.addEventListener('mousedown', AudioObject.prototype.mouseDown, false);
  window.addEventListener('mouseup', mouseUp, false);
}

/* populateAudioList */
function populateAudioList() {
  var audioElements = document.getElementsByClassName("audio");
  for (i = 0; i < audioElements.length; i++) {
    audioList.push(
      new AudioObject(audioElements[i], 0)
    );
    audioList[i].bindAudioPlayer(i);
    audioList[i].addEventListeners();
  }
}

/* populateComponentDictionary()
 * {key=element id : value=index of audioList} */
function populateComponentDictionary() {
  for (i = 0; i < audioList.length; i++) {
    componentDict[audioList[i].audio.id] = i;
    componentDict[audioList[i].playbutton.id] = i;
    componentDict[audioList[i].timeline.id] = i;
    componentDict[audioList[i].playhead.id] = i;
  }
}

///////////////////////////////////////////////
// Update Audio Player
///////////////////////////////////////////////

/* durationChange
 * set duration for AudioObject */
AudioObject.prototype.durationChange = function() {
  var ao = audioList[getAudioListIndex(this.id)];
  ao.duration = this.duration;
}

/* pressPlay()
 * call play() for correct AudioObject
 */
AudioObject.prototype.pressPlay = function() {
  var index = getAudioListIndex(this.id);
  audioList[index].play();
}

/* play()
 * play or pause selected audio, if there is a song playing pause it
 */
AudioObject.prototype.play = function() {
  if (this == playingAudio) {
    playingAudio = null;
    this.audio.pause();
    changeClass(this.playbutton, "playbutton play");
  }
  // else check if playing audio exists and pause it, then start this
  else {
    if (playingAudio != null) {
      playingAudio.audio.pause();
      changeClass(playingAudio.playbutton, "playbutton play");
    }
    this.audio.play();
    playingAudio = this;
    changeClass(this.playbutton, "playbutton pause");
  }
}

/* timelineClick()
 * get timeline's AudioObject
 */
AudioObject.prototype.timelineClick = function(event) {
  var ao = audioList[getAudioListIndex(this.id)];
  ao.audio.currentTime = ao.audio.duration * clickPercent(event, ao.timeline, ao.timelineWidth);
}

/* mouseDown */
AudioObject.prototype.mouseDown = function(event) {
  onplayhead = this.id;
  var ao = audioList[getAudioListIndex(this.id)];
  window.addEventListener('mousemove', AudioObject.prototype.moveplayhead, true);
  ao.audio.removeEventListener('timeupdate', AudioObject.prototype.timeUpdate, false);
}

/* mouseUp EventListener
 * getting input from all mouse clicks */
function mouseUp(e) {
  if (onplayhead != null) {
    var ao = audioList[getAudioListIndex(onplayhead)];
    window.removeEventListener('mousemove', AudioObject.prototype.moveplayhead, true);
    // change current time
    ao.audio.currentTime = ao.audio.duration * clickPercent(e, ao.timeline, ao.timelineWidth);
    ao.audio.addEventListener('timeupdate', AudioObject.prototype.timeUpdate, false);
  }
  onplayhead = null;
}

/* mousemove EventListener
 * Moves playhead as user drags */
AudioObject.prototype.moveplayhead = function(e) {
  var ao = audioList[getAudioListIndex(onplayhead)];
  var newMargLeft = e.clientX - getPosition(ao.timeline);

  if (newMargLeft >= 0 && newMargLeft <= ao.timelineWidth) {
    document.getElementById(onplayhead).style.marginLeft = newMargLeft + "px";
  }
  if (newMargLeft < 0) {
    playhead.style.marginLeft = "0px";
  }
  if (newMargLeft > ao.timelineWidth) {
    playhead.style.marginLeft = ao.timelineWidth + "px";
  }
}

/* timeUpdate
 * Synchronizes playhead position with current point in audio
 * this is the html audio element
 */
AudioObject.prototype.timeUpdate = function() {
  // audio element's AudioObject
  var ao = audioList[getAudioListIndex(this.id)];
  var playPercent = ao.timelineWidth * (ao.audio.currentTime / ao.duration);
  ao.playhead.style.marginLeft = playPercent + "px";
  // If song is over
  if (ao.audio.currentTime == ao.duration) {
    changeClass(ao.playbutton, "playbutton play");
    ao.audio.currentTime = 0;
    ao.audio.pause();
    playingAudio = null;
  }
}

///////////////////////////////////////////////
// Utility Methods
///////////////////////////////////////////////

/* changeClass
 * overwrites element's class names */
function changeClass(element, newClasses) {
  element.className = newClasses;
}

/* getAudioListIndex
 * Given an element's id, find the index in audioList for the correct AudioObject */
function getAudioListIndex(id) {
  return componentDict[id];
}

/* clickPercent()
 * returns click as decimal (.77) of the total timelineWidth */
function clickPercent(e, timeline, timelineWidth) {
  return (event.clientX - getPosition(timeline)) / timelineWidth;
}

// getPosition
// Returns elements left position relative to top-left of viewport
function getPosition(el) {
  return el.getBoundingClientRect().left;
}
///////////////////////////////////////////////
// GENERATE HTML FOR AUDIO ELEMENTS AND PLAYERS
///////////////////////////////////////////////

/* createAudioElements
 * create audio elements for each file in settings */
function createAudioElements() {
  for (f in settings) {
    var audioString = "<audio id=\"audio-" + f + "\" class=\"audio\" preload=\"true\"><source src=\"" + settings[f].src + "\"></audio>";
    $("#" + settings[f].elementId).append(audioString);
  }
}

/* createAudioPlayers
 * create audio players for each file in settings */
function createAudioPlayers() {
  for (f in settings) {
    var playerString = "
<button id=\"playbutton-" + f + "\" class=\"play playbutton\">" +
      "</button>

";
    $("#" + settings[f].elementId).append(playerString);
  }
}

/* theDOMHasLoaded()
 * Execute when DOM is loaded */
function theDOMHasLoaded(e) {
  // Generate HTML for audio elements and audio players
  createAudioElements();
  createAudioPlayers();

  // Populate Audio List
  populateAudioList();
  populateComponentDictionary();
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.audioplayer {
  width: 480px;
  height: 60px;
  margin: 50px auto auto auto;
  border: solid;
}

.playbutton {
  height: 60px;
  width: 60px;
  border: none;
  float: left;
  outline: none;
}

.play {
  background: url('http://www.alexkatz.me/codepen/img/play.png');
}

.pause {
  background: url('http://www.alexkatz.me/codepen/img/pause.png');
}

.play,
.pause {
  background-size: 50% 50%;
  background-repeat: no-repeat;
  background-position: center;
}

.timeline {
  width: 400px;
  height: 20px;
  margin-top: 20px;
  float: left;
  border-radius: 15px;
  background: rgba(0, 0, 0, .3);
}

.playhead {
  width: 18px;
  height: 18px;
  border-radius: 50%;
  margin-top: 1px;
  background: rgba(0, 0, 0, 1);
  cursor: pointer;
}</code>```

player 1

player 2

player 3

```

Body:
Here's the code I'm using for the audio players:

https://codepen.io/katzkode/pen/ZbxYYG

What it does:

Creates multiple audio players at once (by using a single div element) for each song using a loop.

Loop:

/* createAudioElements
 * create audio elements for each file in files */
function createAudioElements() {
    for (f in files) {
        var audioString = "<audio id=\"audio-" + f + "\" class=\"audio\" preload=\"true\"><source src=\"http://www.alexkatz.me/codepen/music/" + files[f] + "\"></audio>";
        $("#audio-players").append(audioString);
    }
}

/* createAudioPlayers
 * create audio players for each file in files */
function createAudioPlayers() {
    for (f in files) {
        var playerString = "
<button id=\"playbutton-" + f + "\" class=\"play playbutton\"></button>

";
        $("#audio-players").append(playerString);
    }
}

var files:

var files = ["interlude.mp3", // 0
            "chooseyourweapon.mp3", // 1
            "interlude.mp3", // 2
            "scriptures.mp3" // 3
            ];

Is invoked in HTML when I use:

What I'm trying to accomplish:

Remove the loop so I could insert any player separately and tweak them separately however I want like this: https://puu.sh/ynD4q/6ab2ba7816.png

I want to use this code to invoke the desired audio player:

<audio id="audio-0" class="audio" preload="true">
    <source src="http://www.alexkatz.me/codepen/music/interlude.mp3">
</audio>

    <button id="playbutton-0" class="play playbutton"></button>

When I try to use it, the play / stop / change position buttons stop working.

It's driving me crazy, I just started learning jQuery. Thank you a lot!

Body:
Change files array to the settings object and add object for each of the files with elementId and src properties:

var settings = [
    {"elementId" : "audio-player-1", "src" : "http://www.alexkatz.me/codepen/music/interlude.mp3"},
    {"elementId" : "audio-player-2", "src" : "http://www.alexkatz.me/codepen/music/chooseyourweapon.mp3"},
    {"elementId" : "audio-player-3", "src" : "http://www.alexkatz.me/codepen/music/scriptures.mp3"}
];

It's very usable, because you can add any property you want. And with src attribute you can add audio files from any website that allows it.

Then in createAudioElements set new src attribute to settings[f].src.

Afterwards in createAudioElements and createAudioPlayers functions change the selector name (to which the rows gathered in the loop are added) to the dynamically generated from the relevant elementId property $("#" + files[f].elementId).

// Event listener for DOM
document.addEventListener("DOMContentLoaded", theDOMHasLoaded, false);

// array of audio files (stored in a folder called music)
var settings = [{
    "elementId": "audio-player-1",
    "src": "http://www.alexkatz.me/codepen/music/interlude.mp3"
  },
  {
    "elementId": "audio-player-2",
    "src": "http://www.alexkatz.me/codepen/music/chooseyourweapon.mp3"
  },
  {
    "elementId": "audio-player-3",
    "src": "http://www.alexkatz.me/codepen/music/scriptures.mp3"
  }
];

///////////////////////////////////////////////
// Find and store audio info
///////////////////////////////////////////////

// array for AudioObjects
var audioList = [];
// components and the index for their AudioObject
var componentDict = {};
// store AudioObject that is currently playing
var playingAudio = null;
// store playhead id if one is being dragged
var onplayhead = null;

/* AudioObject Constructor */
function AudioObject(audio, duration) {
  this.audio = audio;
  this.id = audio.id;
  this.duration = duration;
}
/* bindAudioPlayer
 * Store audioplayer components in correct AudioObject
 * num identifes correct audioplayer
 */
AudioObject.prototype.bindAudioPlayer = function(num) {
  this.audioplayer = document.getElementById("audioplayer-" + num);
  this.playbutton = document.getElementById("playbutton-" + num);
  this.timeline = document.getElementById("timeline-" + num);
  this.playhead = document.getElementById("playhead-" + num);
  this.timelineWidth = this.timeline.offsetWidth - this.playhead.offsetWidth
}

/* addEventListeners() */
AudioObject.prototype.addEventListeners = function() {
  this.audio.addEventListener("timeupdate", AudioObject.prototype.timeUpdate, false);
  this.audio.addEventListener("durationchange", AudioObject.prototype.durationChange, false);
  this.timeline.addEventListener("click", AudioObject.prototype.timelineClick, false);
  this.playbutton.addEventListener("click", AudioObject.prototype.pressPlay, false);
  // Makes playhead draggable
  this.playhead.addEventListener('mousedown', AudioObject.prototype.mouseDown, false);
  window.addEventListener('mouseup', mouseUp, false);
}

/* populateAudioList */
function populateAudioList() {
  var audioElements = document.getElementsByClassName("audio");
  for (i = 0; i < audioElements.length; i++) {
    audioList.push(
      new AudioObject(audioElements[i], 0)
    );
    audioList[i].bindAudioPlayer(i);
    audioList[i].addEventListeners();
  }
}

/* populateComponentDictionary()
 * {key=element id : value=index of audioList} */
function populateComponentDictionary() {
  for (i = 0; i < audioList.length; i++) {
    componentDict[audioList[i].audio.id] = i;
    componentDict[audioList[i].playbutton.id] = i;
    componentDict[audioList[i].timeline.id] = i;
    componentDict[audioList[i].playhead.id] = i;
  }
}

///////////////////////////////////////////////
// Update Audio Player
///////////////////////////////////////////////

/* durationChange
 * set duration for AudioObject */
AudioObject.prototype.durationChange = function() {
  var ao = audioList[getAudioListIndex(this.id)];
  ao.duration = this.duration;
}

/* pressPlay()
 * call play() for correct AudioObject
 */
AudioObject.prototype.pressPlay = function() {
  var index = getAudioListIndex(this.id);
  audioList[index].play();
}

/* play()
 * play or pause selected audio, if there is a song playing pause it
 */
AudioObject.prototype.play = function() {
  if (this == playingAudio) {
    playingAudio = null;
    this.audio.pause();
    changeClass(this.playbutton, "playbutton play");
  }
  // else check if playing audio exists and pause it, then start this
  else {
    if (playingAudio != null) {
      playingAudio.audio.pause();
      changeClass(playingAudio.playbutton, "playbutton play");
    }
    this.audio.play();
    playingAudio = this;
    changeClass(this.playbutton, "playbutton pause");
  }
}

/* timelineClick()
 * get timeline's AudioObject
 */
AudioObject.prototype.timelineClick = function(event) {
  var ao = audioList[getAudioListIndex(this.id)];
  ao.audio.currentTime = ao.audio.duration * clickPercent(event, ao.timeline, ao.timelineWidth);
}

/* mouseDown */
AudioObject.prototype.mouseDown = function(event) {
  onplayhead = this.id;
  var ao = audioList[getAudioListIndex(this.id)];
  window.addEventListener('mousemove', AudioObject.prototype.moveplayhead, true);
  ao.audio.removeEventListener('timeupdate', AudioObject.prototype.timeUpdate, false);
}

/* mouseUp EventListener
 * getting input from all mouse clicks */
function mouseUp(e) {
  if (onplayhead != null) {
    var ao = audioList[getAudioListIndex(onplayhead)];
    window.removeEventListener('mousemove', AudioObject.prototype.moveplayhead, true);
    // change current time
    ao.audio.currentTime = ao.audio.duration * clickPercent(e, ao.timeline, ao.timelineWidth);
    ao.audio.addEventListener('timeupdate', AudioObject.prototype.timeUpdate, false);
  }
  onplayhead = null;
}

/* mousemove EventListener
 * Moves playhead as user drags */
AudioObject.prototype.moveplayhead = function(e) {
  var ao = audioList[getAudioListIndex(onplayhead)];
  var newMargLeft = e.clientX - getPosition(ao.timeline);

  if (newMargLeft >= 0 && newMargLeft <= ao.timelineWidth) {
    document.getElementById(onplayhead).style.marginLeft = newMargLeft + "px";
  }
  if (newMargLeft < 0) {
    playhead.style.marginLeft = "0px";
  }
  if (newMargLeft > ao.timelineWidth) {
    playhead.style.marginLeft = ao.timelineWidth + "px";
  }
}

/* timeUpdate
 * Synchronizes playhead position with current point in audio
 * this is the html audio element
 */
AudioObject.prototype.timeUpdate = function() {
  // audio element's AudioObject
  var ao = audioList[getAudioListIndex(this.id)];
  var playPercent = ao.timelineWidth * (ao.audio.currentTime / ao.duration);
  ao.playhead.style.marginLeft = playPercent + "px";
  // If song is over
  if (ao.audio.currentTime == ao.duration) {
    changeClass(ao.playbutton, "playbutton play");
    ao.audio.currentTime = 0;
    ao.audio.pause();
    playingAudio = null;
  }
}

///////////////////////////////////////////////
// Utility Methods
///////////////////////////////////////////////

/* changeClass
 * overwrites element's class names */
function changeClass(element, newClasses) {
  element.className = newClasses;
}

/* getAudioListIndex
 * Given an element's id, find the index in audioList for the correct AudioObject */
function getAudioListIndex(id) {
  return componentDict[id];
}

/* clickPercent()
 * returns click as decimal (.77) of the total timelineWidth */
function clickPercent(e, timeline, timelineWidth) {
  return (event.clientX - getPosition(timeline)) / timelineWidth;
}

// getPosition
// Returns elements left position relative to top-left of viewport
function getPosition(el) {
  return el.getBoundingClientRect().left;
}
///////////////////////////////////////////////
// GENERATE HTML FOR AUDIO ELEMENTS AND PLAYERS
///////////////////////////////////////////////

/* createAudioElements
 * create audio elements for each file in settings */
function createAudioElements() {
  for (f in settings) {
    var audioString = "<audio id=\"audio-" + f + "\" class=\"audio\" preload=\"true\"><source src=\"" + settings[f].src + "\"></audio>";
    $("#" + settings[f].elementId).append(audioString);
  }
}

/* createAudioPlayers
 * create audio players for each file in settings */
function createAudioPlayers() {
  for (f in settings) {
    var playerString = "<div id=\"audioplayer-" + f + "\" class=\"audioplayer\"><button id=\"playbutton-" + f + "\" class=\"play playbutton\">" +
      "</button><div id=\"timeline-" + f + "\" class=\"timeline\"><div id=\"playhead-" + f + "\" class=\"playhead\"></div></div></div>";
    $("#" + settings[f].elementId).append(playerString);
  }
}

/* theDOMHasLoaded()
 * Execute when DOM is loaded */
function theDOMHasLoaded(e) {
  // Generate HTML for audio elements and audio players
  createAudioElements();
  createAudioPlayers();

  // Populate Audio List
  populateAudioList();
  populateComponentDictionary();
}

.audioplayer {
  width: 480px;
  height: 60px;
  margin: 50px auto auto auto;
  border: solid;
}

.playbutton {
  height: 60px;
  width: 60px;
  border: none;
  float: left;
  outline: none;
}

.play {
  background: url('http://www.alexkatz.me/codepen/img/play.png');
}

.pause {
  background: url('http://www.alexkatz.me/codepen/img/pause.png');
}

.play,
.pause {
  background-size: 50% 50%;
  background-repeat: no-repeat;
  background-position: center;
}

.timeline {
  width: 400px;
  height: 20px;
  margin-top: 20px;
  float: left;
  border-radius: 15px;
  background: rgba(0, 0, 0, .3);
}

.playhead {
  width: 18px;
  height: 18px;
  border-radius: 50%;
  margin-top: 1px;
  background: rgba(0, 0, 0, 1);
  cursor: pointer;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3>player 1</h3>
<div id="audio-player-1"></div>
<h3>player 2</h3>
<div id="audio-player-2"></div>
<h3>player 3</h3>
<div id="audio-player-3"></div>


来源: stackexchange

问:
Converting a 2d array into a 1d array
just curious on how to convert a 2d array into a 1d array. </p>

```<code>For example if my array was:

int[][] arr = {{2,3,4},
               {5,6,7}};

lets say I wanted it just to be transferred to a 1d array such as:

int[] arr = {2,3,4,5,6,7};
</code>```

答:
In Java 8 and integer array you can use:

```<code>int[][] arr2d = new int[][] { { 1, 2, 3 }, { 4, 5 }, {6, 7} };
int[] arr1d = Arrays.stream(arr2d).flatMapToInt(Arrays::stream).toArray();
</code>```

For Java 7 or object array:

```<code>Object[][] obj2d = new Object[][] {};

List<Object> list = new ArrayList<>();
for (Object[] arr : obj2d) {
    for (Object obj : arr) {
        list.add(obj);
    }
}

Object[] obj1d = list.toArray(new Object[] {});
</code>```

ContentLicense: CC BY-SA 3.0

Title: Converting a 2d array into a 1d array

Body:
just curious on how to convert a 2d array into a 1d array.

For example if my array was:

int[][] arr = {{2,3,4},
               {5,6,7}};

lets say I wanted it just to be transferred to a 1d array such as:

int[] arr = {2,3,4,5,6,7};

Body:
In Java 8 and integer array you can use:

int[][] arr2d = new int[][] { { 1, 2, 3 }, { 4, 5 }, {6, 7} };
int[] arr1d = Arrays.stream(arr2d).flatMapToInt(Arrays::stream).toArray();

For Java 7 or object array:

Object[][] obj2d = new Object[][] {};

List<Object> list = new ArrayList<>();
for (Object[] arr : obj2d) {
    for (Object obj : arr) {
        list.add(obj);
    }
}

Object[] obj1d = list.toArray(new Object[] {});


问:
GSSF callback called thousands of times for audio
I'm using two GSSF filters, one to send BGRA frames and another to send PCM 16bit 48KHz audio samples to directshow graph.

The image filter callback is called at the right frequency, more or less 30ms apart since I'm working in 29.97fps.
But for audio, once the graph starts the audio callback is called more than 5000 times.

Video Setup:

```<code>BitmapInfoHeader bmi = new BitmapInfoHeader();
bmi.Size = Marshal.SizeOf(typeof(BitmapInfoHeader));
bmi.Width = width; //1920
bmi.Height = height * -1; //1080
bmi.Planes = 1;
bmi.BitCount = (short)bpp; //32
bmi.Compression = 0;
bmi.ImageSize = (bmi.BitCount / 8) * bmi.Width * bmi.Height; //8294400
bmi.XPelsPerMeter = 0;
bmi.YPelsPerMeter = 0;
bmi.ClrUsed = 0;
bmi.ClrImportant = 0;

int hr = ssi.SetMediaTypeFromBitmap(bmi, (long)fps); // (long)(10000000 / 29.97)
DsError.ThrowExceptionForHR(hr);
</code>```

Audio Setup

```<code>WaveFormatEx wfex = new WaveFormatEx();
wfex.wFormatTag = 1; //PCM
wfex.nSamplesPerSec = samplerate; //48000;
wfex.wBitsPerSample = (ushort)bps; //16
wfex.nChannels = (ushort)numChannels; //2
wfex.nAvgBytesPerSec = samplerate * (bps * numChannels / 8); //192000
wfex.nBlockAlign = (ushort)(numChannels * bps / 8); //4
wfex.cbSize = 0;

//Keep Data
bytesPerSample = wfex.nAvgBytesPerSec;
frequency = samplerate;
channels = numChannels;
bits = bps;

AMMediaType amt = new AMMediaType();
amt.majorType = MediaType.Audio;
amt.subType = MediaSubType.PCM;
amt.formatType = FormatType.WaveEx;
amt.temporalCompression = false;
amt.fixedSizeSamples = true;
amt.sampleSize = wfex.nBlockAlign;
amt.formatSize = Marshal.SizeOf(wfex);
amt.formatPtr = Marshal.AllocCoTaskMem(amt.formatSize);
Marshal.StructureToPtr(wfex, amt.formatPtr, false);

int hr = ssa.SetMediaTypeEx(amt, wfex.nAvgBytesPerSec);
DsError.ThrowExceptionForHR(hr);

Tools.FreeAMMediaType(amt);
</code>```

I'm setting Timestamps like this:

For Video:

```<code>// fps is (long)(10000000/29.97)
DsLong rtStart = new DsLong(frameNumber * fps);
DsLong rtStop = new DsLong(rtStart + fps);
int hr = pSample.SetTime(rtStart, rtStop);
frameNumber++;
</code>```

For Audio:

```<code>//size is the number os audio samples written in bytes
//bits = 16
//channles = 2
//frequency = 48000
//timeUnit = 10000000
// lastTime starts from 0
long sampleCount = size * 8 / bits / channels;
long frameLength = timeUnit * sampleCount / frequency;
DsLong rtStart = new DsLong(lastTime);
lastTime = rtStart + frameLength;
DsLong rtStop = new DsLong(lastTime);
int hr = pSample.SetTime(rtStart, rtStop);
</code>```

I haven't posted the full code because is mostly the same as the example of GSSF. But I can post whatever you feel is necessary.

Anyone has any idea why is this happening?

Thank you

答:
I've stopped working on this but I thought I could give it a try again and I found the "problem". If anyone else has this problem, here it goes...

The thing is, like RomanR said, I should throttle the requests, but I couldn't figure out what was going on since I add several request of audio and few of video.

So I kept digging and found out the culprit. Since I was encoding audio in Mpeg Layer II, this paricular codec requests 1152 samples per channel at a time, even you you have 1920 samples to deliver. So I wasn't feeding the samples the right way.
I created a sample manager which delivers the right number of samples and times them accordingly.

Body:
I'm using two GSSF filters, one to send BGRA frames and another to send PCM 16bit 48KHz audio samples to directshow graph.

The image filter callback is called at the right frequency, more or less 30ms apart since I'm working in 29.97fps.
But for audio, once the graph starts the audio callback is called more than 5000 times.

Video Setup:

BitmapInfoHeader bmi = new BitmapInfoHeader();
bmi.Size = Marshal.SizeOf(typeof(BitmapInfoHeader));
bmi.Width = width; //1920
bmi.Height = height * -1; //1080
bmi.Planes = 1;
bmi.BitCount = (short)bpp; //32
bmi.Compression = 0;
bmi.ImageSize = (bmi.BitCount / 8) * bmi.Width * bmi.Height; //8294400
bmi.XPelsPerMeter = 0;
bmi.YPelsPerMeter = 0;
bmi.ClrUsed = 0;
bmi.ClrImportant = 0;

int hr = ssi.SetMediaTypeFromBitmap(bmi, (long)fps); // (long)(10000000 / 29.97)
DsError.ThrowExceptionForHR(hr);

Audio Setup

WaveFormatEx wfex = new WaveFormatEx();
wfex.wFormatTag = 1; //PCM
wfex.nSamplesPerSec = samplerate; //48000;
wfex.wBitsPerSample = (ushort)bps; //16
wfex.nChannels = (ushort)numChannels; //2
wfex.nAvgBytesPerSec = samplerate * (bps * numChannels / 8); //192000
wfex.nBlockAlign = (ushort)(numChannels * bps / 8); //4
wfex.cbSize = 0;

//Keep Data
bytesPerSample = wfex.nAvgBytesPerSec;
frequency = samplerate;
channels = numChannels;
bits = bps;

AMMediaType amt = new AMMediaType();
amt.majorType = MediaType.Audio;
amt.subType = MediaSubType.PCM;
amt.formatType = FormatType.WaveEx;
amt.temporalCompression = false;
amt.fixedSizeSamples = true;
amt.sampleSize = wfex.nBlockAlign;
amt.formatSize = Marshal.SizeOf(wfex);
amt.formatPtr = Marshal.AllocCoTaskMem(amt.formatSize);
Marshal.StructureToPtr(wfex, amt.formatPtr, false);

int hr = ssa.SetMediaTypeEx(amt, wfex.nAvgBytesPerSec);
DsError.ThrowExceptionForHR(hr);

Tools.FreeAMMediaType(amt);

I'm setting Timestamps like this:

For Video:

// fps is (long)(10000000/29.97)
DsLong rtStart = new DsLong(frameNumber * fps);
DsLong rtStop = new DsLong(rtStart + fps);
int hr = pSample.SetTime(rtStart, rtStop);
frameNumber++;

For Audio:

//size is the number os audio samples written in bytes
//bits = 16
//channles = 2
//frequency = 48000
//timeUnit = 10000000
// lastTime starts from 0
long sampleCount = size * 8 / bits / channels;
long frameLength = timeUnit * sampleCount / frequency;
DsLong rtStart = new DsLong(lastTime);
lastTime = rtStart + frameLength;
DsLong rtStop = new DsLong(lastTime);
int hr = pSample.SetTime(rtStart, rtStop);

I haven't posted the full code because is mostly the same as the example of GSSF. But I can post whatever you feel is necessary.

Anyone has any idea why is this happening?

Thank you


问:
How can interpreter detect being called from a script as opposed to command line?
As "is known", a script my-script-file which starts with

```<code>#!/path/to/interpreter -arg1 val1 -arg2 val2
</code>```

is executed by exec calling /path/to/interpreter with 2(!) arguments:

-arg1 val1 -arg2 val2

my-script-file

(and not, as one might naively expect, with 5 arguments

-arg1

val1

-arg2

val2

my-script-file

as has been explained in many previous questions, e.g.,
https://stackoverflow.com/a/4304187/850781).

My problem is from the POV of an interpreter developer, not script writer.

How do I detect from inside the interpreter executable that I was called from shebang as opposed to the command line?

Then I will be able to decide whether I need to split my first argument
by space to go from "-arg1 val1 -arg2 val2" to ["-arg1", "val1", "-arg2", "val2"] or not.

The main issue here is script files named with spaces in them.
If I always split the 1st argument, I will fail like this:

```<code>$ my-interpreter "weird file name with spaces"
my-interpreter: "weird": No such file or directory
</code>```

答:
On Linux, with GNU libc or musl libc, you can use the aux-vector to distinguish the two cases.

Here is some sample code:

```<code>#define _GNU_SOURCE 1
#include <stdio.h>
#include <errno.h>
#include <sys/auxv.h>
#include <sys/stat.h>

int
main (int argc, char* argv[])
{
  printf ("argv[0] = %s\n", argv[0]);
  /* https://www.gnu.org/software/libc/manual/html_node/Error-Messages.html */
  printf ("program_invocation_name = %s\n", program_invocation_name);
  /* http://man7.org/linux/man-pages/man3/getauxval.3.html */
  printf ("auxv[AT_EXECFN] = %s\n", (const char *) getauxval (AT_EXECFN));
  /* Determine whether the last two are the same. */
  struct stat statbuf1, statbuf2;
  if (stat (program_invocation_name, &statbuf1) >= 0
      && stat ((const char *) getauxval (AT_EXECFN), &statbuf2) >= 0)
    printf ("same? %d\n", statbuf1.st_dev == statbuf2.st_dev && statbuf1.st_ino == statbuf2.st_ino);
}
</code>```

Result for a direct invocation:

```<code>$ ./a.out
argv[0] = ./a.out
program_invocation_name = ./a.out
auxv[AT_EXECFN] = ./a.out
same? 1
</code>```

Result for an invocation through a script that starts with #!/home/bruno/a.out:

```<code>$ ./a.script
argv[0] = /home/bruno/a.out
program_invocation_name = /home/bruno/a.out
auxv[AT_EXECFN] = ./a.script
same? 0
</code>```

This approach is, of course, highly unportable: Only Linux has the getauxv function. And there are surely cases where it does not work well.

Body:
As "is known", a script my-script-file which starts with

#!/path/to/interpreter -arg1 val1 -arg2 val2

is executed by exec calling /path/to/interpreter with 2(!) arguments:

-arg1 val1 -arg2 val2

my-script-file

(and not, as one might naively expect, with 5 arguments

-arg1

val1

-arg2

val2

my-script-file

as has been explained in many previous questions, e.g.,
https://stackoverflow.com/a/4304187/850781).

My problem is from the POV of an interpreter developer, not script writer.

How do I detect from inside the interpreter executable that I was called from shebang as opposed to the command line?

Then I will be able to decide whether I need to split my first argument
by space to go from "-arg1 val1 -arg2 val2" to ["-arg1", "val1", "-arg2", "val2"] or not.

The main issue here is script files named with spaces in them.
If I always split the 1st argument, I will fail like this:

$ my-interpreter "weird file name with spaces"
my-interpreter: "weird": No such file or directory

Body:
On Linux, with GNU libc or musl libc, you can use the aux-vector to distinguish the two cases.

Here is some sample code:

#define _GNU_SOURCE 1
#include <stdio.h>
#include <errno.h>
#include <sys/auxv.h>
#include <sys/stat.h>

int
main (int argc, char* argv[])
{
  printf ("argv[0] = %s\n", argv[0]);
  /* https://www.gnu.org/software/libc/manual/html_node/Error-Messages.html */
  printf ("program_invocation_name = %s\n", program_invocation_name);
  /* http://man7.org/linux/man-pages/man3/getauxval.3.html */
  printf ("auxv[AT_EXECFN] = %s\n", (const char *) getauxval (AT_EXECFN));
  /* Determine whether the last two are the same. */
  struct stat statbuf1, statbuf2;
  if (stat (program_invocation_name, &statbuf1) >= 0
      && stat ((const char *) getauxval (AT_EXECFN), &statbuf2) >= 0)
    printf ("same? %d\n", statbuf1.st_dev == statbuf2.st_dev && statbuf1.st_ino == statbuf2.st_ino);
}

Result for a direct invocation:

$ ./a.out
argv[0] = ./a.out
program_invocation_name = ./a.out
auxv[AT_EXECFN] = ./a.out
same? 1

Result for an invocation through a script that starts with #!/home/bruno/a.out:

$ ./a.script
argv[0] = /home/bruno/a.out
program_invocation_name = /home/bruno/a.out
auxv[AT_EXECFN] = ./a.script
same? 0

This approach is, of course, highly unportable: Only Linux has the getauxv function. And there are surely cases where it does not work well.


问:
3D pointer seg error
I want to stick 2D arrays in a 3D array together, first i defined the 3D array in the following way

```<code>int ***grid;
    grid=new int **[number];
</code>```

then I want to assign the 2D arrays to the 3D construct

```<code>for(i=0;i<number;i++)
        grid[i]=rk4tillimpact2dens(...);
</code>```

with

```<code>int** rk4tillimpact2dens(...
...
  static int** grid;
    grid=new int*[600];
    for(i=0;i<600;i++)
        grid[i]=new int[600];
    memset(grid,0x0,sizeof(grid));
...
  return(grid);
}
</code>```

so far no problem, everything works fine, but when I want to access the 3D array afterwards I get a seg fault. Like that e.g.

```<code>printf("%d",grid[1][1][1]);
</code>```

What is my mistake?

Best,
  Hannes

答:
Oh, sorry, it was typo in my question, I did

```<code>printf("%d",grid[1][1][1]);
</code>```

it's not working :(. But even

```<code>printf("%d",&grid[1][1][1]);
</code>```

or

```<code>printf("%d",*grid[1][1][1]);
</code>```

would not work. The strange thing is, that there are no errors unless I try to access the array

Title: 3D pointer seg error

Body:
I want to stick 2D arrays in a 3D array together, first i defined the 3D array in the following way

int ***grid;
    grid=new int **[number];

then I want to assign the 2D arrays to the 3D construct

for(i=0;i<number;i++)
        grid[i]=rk4tillimpact2dens(...);

with

int** rk4tillimpact2dens(...
...
  static int** grid;
    grid=new int*[600];
    for(i=0;i<600;i++)
        grid[i]=new int[600];
    memset(grid,0x0,sizeof(grid));
...
  return(grid);
}

so far no problem, everything works fine, but when I want to access the 3D array afterwards I get a seg fault. Like that e.g.

printf("%d",grid[1][1][1]);

What is my mistake?

Best,
  Hannes

Body:
Oh, sorry, it was typo in my question, I did

printf("%d",grid[1][1][1]);

it's not working :(. But even

printf("%d",&grid[1][1][1]);

or

printf("%d",*grid[1][1][1]);

would not work. The strange thing is, that there are no errors unless I try to access the array


问:
What's wrong with the prime number generator?
I wrote a code. The goal was to find the prime numbers up to 1000. It compiles and runs, but it seems that the table is blank at the end. What is the reason for this? How do I fix it? Thanks.</p>

```<code>#include <iostream>
#include <cmath>
#include <fstream>
using namespace std;

int primes[20];
bool prime;
int main()
{
    int i;
for(i=2;i<=1000;i++){
prime=true;
int ii;
   for (ii=1;ii<=sizeof(primes);ii++){
       if (i/ii==floor(i/ii)){
                             prime=false;
                             }
       }
       if (prime==true){
       primes[sizeof(primes+1)]=i;
   }
}
for (i=1;i<=20;i++){
cout << primes[i] << endl;
system("pause");
}
}
</code>```

答:
The way I generate all numbers up to N is as follows:

```<code>std::vector< int > lowestFactors( N+1, 1 );
for( int n = 2; n * n <= N; ++n )
{
    if( lowestFactors[ n ] != 1 )
        continue; // our number is not prime

    for( int m = n; m * n <= N; ++m )
    {
        if( lowestFactors[ m ] != 1 && lowestFactors[m] != n )
          continue;

        lowestFactors[m * n ] = n;
    }
}
</code>```

each cell will now contain in lowestFactors:
- 1 if it is prime
- its lowest factor if not prime.
- 0 and 1 don't count.

You can also initialise all of lowestFactors with their own values, and can size it N-1 subtracting 2 when you access a number

ContentLicense: CC BY-SA 2.5

Body:
I wrote a code. The goal was to find the prime numbers up to 1000. It compiles and runs, but it seems that the table is blank at the end. What is the reason for this? How do I fix it? Thanks.

#include <iostream>
#include <cmath>
#include <fstream>
using namespace std;

int primes[20];
bool prime;
int main()
{
    int i;
for(i=2;i<=1000;i++){
prime=true;
int ii;
   for (ii=1;ii<=sizeof(primes);ii++){
       if (i/ii==floor(i/ii)){
                             prime=false;
                             }
       }
       if (prime==true){
       primes[sizeof(primes+1)]=i;
   }
}
for (i=1;i<=20;i++){
cout << primes[i] << endl;
system("pause");
}
}

Body:
The way I generate all numbers up to N is as follows:

std::vector< int > lowestFactors( N+1, 1 );
for( int n = 2; n * n <= N; ++n )
{
    if( lowestFactors[ n ] != 1 )
        continue; // our number is not prime

    for( int m = n; m * n <= N; ++m )
    {
        if( lowestFactors[ m ] != 1 && lowestFactors[m] != n )
          continue;

        lowestFactors[m * n ] = n;
    }
}

each cell will now contain in lowestFactors:
- 1 if it is prime
- its lowest factor if not prime.
- 0 and 1 don't count.

You can also initialise all of lowestFactors with their own values, and can size it N-1 subtracting 2 when you access a number


问:
Making linkage between two objects in crystal report
For example, I have 2 list, consits of these data

```<code>List1               List2

Group1              Group1's value1
blank               Group1's value2
blank               Group1's value3
blank               Group1's value4
Group2              Group2's value1
Group3              Group3's value1
</code>```

When transfered to report, they became.

```<code>oList1 = Group1 + chr(10) + blank + chr(10) + blank + chr(10) + blank + chr(10) + Group2 + chr(10) + Group3
oList1 = Group1's value1  + chr(10) + Group1's value2  + chr(10) + Group1's value3  + chr(10) + Group1's value4  + chr(10) + Group2's value1  + chr(10) + Group3's value1
</code>```

The report's layout (header section) :

Expected result :

But if one of the value's length exceeds the text object's width, the result will be like below :

Is there any workaround to solve this? I'm thinking calculating the display size of the text to determine how many lines it would take to display on the report. But that feels risky!

答:
I would just put the Group and Value as separate column in the report. Put it in the Details section, like below:

Then, I will set the Value to be able to grow, if it exceeds the report width:

That would eliminate the issue.

Body:
For example, I have 2 list, consits of these data

List1               List2

Group1              Group1's value1
blank               Group1's value2
blank               Group1's value3
blank               Group1's value4
Group2              Group2's value1
Group3              Group3's value1

When transfered to report, they became.

oList1 = Group1 + chr(10) + blank + chr(10) + blank + chr(10) + blank + chr(10) + Group2 + chr(10) + Group3
oList1 = Group1's value1  + chr(10) + Group1's value2  + chr(10) + Group1's value3  + chr(10) + Group1's value4  + chr(10) + Group2's value1  + chr(10) + Group3's value1

The report's layout (header section) :

Expected result :

But if one of the value's length exceeds the text object's width, the result will be like below :

Is there any workaround to solve this? I'm thinking calculating the display size of the text to determine how many lines it would take to display on the report. But that feels risky!


问:
openssl_verify does not have OPENSSL_ALGO_SHA256 definition in openssl.php in eclipse php project
I am trying to use openssl_verify with OPENSSL_ALGO_SHA256 in a php project using eclipse PDT. But I am not able to verify as OPENSSL_ALGO_SHA256 is not defined in openssl.php file in Core API. I create project by specifying PHP 5.4 as it is mentioned in PHP Documentation
that this flag was added in PHP 5.4.8. I am not sure what I am doing wrong here.
Can anybody tell me how to get this working?

Thanks

答:
Try string:

```<code>"sha256WithRSAEncryption"
</code>```

instead of the constant:

```<code>OPENSSL_ALGO_SHA256
</code>```

(Source)

Body:
Try string:

"sha256WithRSAEncryption"

instead of the constant:

OPENSSL_ALGO_SHA256

(Source)


问:
What is the difference between RDF and OWL?
I am trying to grasp the concept of Semantic Web. I am finding it hard to understand what exactly is the difference between RDF and OWL. Is OWL an extension of RDF or these two are totally different technologies? </p>

答:
The Resource Description Framework (RDF) is a powerful formal knowledge representation language and a fundamental standard of the Semantic Web. It has its own vocabulary that defines core concepts and relations (e.g., rdf:type corresponds to the isA relationship), and a data model that enables machine-interpretable statements in the form of subject-predicate-object (resource-property-value) triples, called RDF triples, such as picture-depicts-book. The extension of the RDF vocabulary with concepts required to create controlled vocabularies and basic ontologies is called RDF Schema or RDF Vocabulary Description Language (RDFS). RDFS makes it possible to write statements about classes and resources, and express taxonomical structures, such as via superclass-subclass relationships.

Complex knowledge domains require more capabilities than what is available in RDFS, which led to the introduction of OWL. OWL supports relationships between classes (union, intersection, disjointness, equivalence), property cardinality constraints (minimum, maximum, exact number, e.g., every person has exactly one father), rich typing of properties, characteristics of properties and special properties (transitive, symmetric, functional, inverse functional, e.g., A ex:hasAncestor B and B ex:hasAncestor C implies that A ex:hasAncestor C), specifying that a given property is a unique key for instances of a particular class, and domain and range restrictions for properties.


问:
lastnames to firstnames dictionary
So I'm given a dictionary containing people's friend's circle, and I'm supposed to create a dictionary organizing these people based on their lastnames i.e. a lastname to firstname dictionary.

```<code>people_and_friends = {'Jay Pritchett': ['Claire Dunphy', 'Gloria Pritchett', 'Manny Delgado'], 'Claire Dunphy': ['Jay Pritchett', 'Mitchell Pritchett', 'Phil Dunphy'], 'Manny Delgado': ['Gloria Pritchett', 'Jay Pritchett', 'Luke Dunphy'], 'Mitchell Pritchett': ['Cameron Tucker', 'Claire Dunphy', 'Luke Dunphy'], 'Alex Dunphy': ['Luke Dunphy'], 'Cameron Tucker': ['Gloria Pritchett', 'Mitchell Pritchett'], 'Haley Gwendolyn Dunphy': ['Dylan D-Money', 'Gilbert D-Cat'], 'Phil Dunphy': ['Claire Dunphy', 'Luke Dunphy'], 'Dylan D-Money': ['Chairman D-Cat', 'Haley Gwendolyn Dunphy'], 'Gloria Pritchett': ['Cameron Tucker', 'Jay Pritchett', 'Manny Delgado'], 'Luke Dunphy': ['Alex Dunphy', 'Manny Delgado', 'Mitchell Pritchett', 'Phil Dunphy']}
</code>```

This is the code I have so far which isolates the lastnames of the individuals in the first dictionary:

```<code>lastnames_to_firstnames = {}

for people in person_and_friends:
    family = person[person.rfind(' '):].strip()
    if not family in lastnames_to_firstnames:
        lastnames_to_firstnames[family_name] = person_and_friends[people]
</code>```

The lastnames_to_firstnames should look like this:

```<code>lastname_firstname = {'Pritchett':['Jay', 'Gloria', 'Mitchell'],
'Dunphy':['Alex', 'Claire', 'Haley Gwendolyn', 'Luke', 'Phil'],
'Delgado':['Manny'],'Tucker':['Cameron'],'D-Money':['Dylan'], 'D-Car':
['Chairman']}
</code>```

I can't figure out how to organize the values of the first dictionary. Any help?

答:
Use a defaultdict

```<code>from collections import defaultdict

d = defaultdict(list)

people_and_friends = {'Joseph Hazelton': ['Penny Patrick', 'Paul Paulson'],
                     'Gilbert Gunderson': ['Philip Patrick', 'Jenny Paulson'],
                     'Helena Anderson': ['Penny Patrick', 'Dylan D-Money']}

for k, v in people_and_friends.items():
    for first, last in map(str.split, (k, *v)):
        d[last].append(first)
</code>```

Edit:

As TitanFighter points out below, if you want to avoid duplicate name pairing, you can use a set instead by replacing

```<code>d = defaultdict(set)
</code>```

and

```<code>d[last].add(first)
</code>```

Edit the Second:

If you can't use defaultdict you can roll your own like this

```<code>d = {}

people_and_friends = {'Joseph Hazelton': ['Penny Patrick', 'Paul Paulson'],
                     'Gilbert Gunderson': ['Philip Patrick', 'Jenny Paulson'],
                     'Helena Anderson': ['Penny Patrick', 'Dylan D-Money']}

for k, v in people_and_friends.items():
    for first, last in map(str.split, (k, *v)):
        if last in d:
            d[last].append(first)
        else:
            d[last] = [first]
</code>```

3dit:

The problem is that some people in your dictionary have three names: Haley Gwendolyn Dunphy.  So what we'll do is collect all of the names except for the last one into a list, then join that list again into a string

```<code>d = {}

for k, v in people_and_friends.items():
    for *first, last in map(str.split, (k, *v)):
        first = ' '.join(first)
        if last in d:
            d[last].add(first)
        else:
            d[last] = {first}
</code>```

Title: lastnames to firstnames dictionary

Body:
So I'm given a dictionary containing people's friend's circle, and I'm supposed to create a dictionary organizing these people based on their lastnames i.e. a lastname to firstname dictionary.

people_and_friends = {'Jay Pritchett': ['Claire Dunphy', 'Gloria Pritchett', 'Manny Delgado'], 'Claire Dunphy': ['Jay Pritchett', 'Mitchell Pritchett', 'Phil Dunphy'], 'Manny Delgado': ['Gloria Pritchett', 'Jay Pritchett', 'Luke Dunphy'], 'Mitchell Pritchett': ['Cameron Tucker', 'Claire Dunphy', 'Luke Dunphy'], 'Alex Dunphy': ['Luke Dunphy'], 'Cameron Tucker': ['Gloria Pritchett', 'Mitchell Pritchett'], 'Haley Gwendolyn Dunphy': ['Dylan D-Money', 'Gilbert D-Cat'], 'Phil Dunphy': ['Claire Dunphy', 'Luke Dunphy'], 'Dylan D-Money': ['Chairman D-Cat', 'Haley Gwendolyn Dunphy'], 'Gloria Pritchett': ['Cameron Tucker', 'Jay Pritchett', 'Manny Delgado'], 'Luke Dunphy': ['Alex Dunphy', 'Manny Delgado', 'Mitchell Pritchett', 'Phil Dunphy']}

This is the code I have so far which isolates the lastnames of the individuals in the first dictionary:

lastnames_to_firstnames = {}

for people in person_and_friends:
    family = person[person.rfind(' '):].strip()
    if not family in lastnames_to_firstnames:
        lastnames_to_firstnames[family_name] = person_and_friends[people]

The lastnames_to_firstnames should look like this:

lastname_firstname = {'Pritchett':['Jay', 'Gloria', 'Mitchell'],
'Dunphy':['Alex', 'Claire', 'Haley Gwendolyn', 'Luke', 'Phil'],
'Delgado':['Manny'],'Tucker':['Cameron'],'D-Money':['Dylan'], 'D-Car':
['Chairman']}

I can't figure out how to organize the values of the first dictionary. Any help?

Body:
Use a defaultdict

from collections import defaultdict

d = defaultdict(list)

people_and_friends = {'Joseph Hazelton': ['Penny Patrick', 'Paul Paulson'],
                     'Gilbert Gunderson': ['Philip Patrick', 'Jenny Paulson'],
                     'Helena Anderson': ['Penny Patrick', 'Dylan D-Money']}

for k, v in people_and_friends.items():
    for first, last in map(str.split, (k, *v)):
        d[last].append(first)

Edit:

As TitanFighter points out below, if you want to avoid duplicate name pairing, you can use a set instead by replacing

d = defaultdict(set)

and

d[last].add(first)

Edit the Second:

If you can't use defaultdict you can roll your own like this

d = {}

people_and_friends = {'Joseph Hazelton': ['Penny Patrick', 'Paul Paulson'],
                     'Gilbert Gunderson': ['Philip Patrick', 'Jenny Paulson'],
                     'Helena Anderson': ['Penny Patrick', 'Dylan D-Money']}

for k, v in people_and_friends.items():
    for first, last in map(str.split, (k, *v)):
        if last in d:
            d[last].append(first)
        else:
            d[last] = [first]

3dit:

The problem is that some people in your dictionary have three names: Haley Gwendolyn Dunphy.  So what we'll do is collect all of the names except for the last one into a list, then join that list again into a string

d = {}

for k, v in people_and_friends.items():
    for *first, last in map(str.split, (k, *v)):
        first = ' '.join(first)
        if last in d:
            d[last].add(first)
        else:
            d[last] = {first}


问:
Pair items in two lists
i have two lists:

```<code>foo = ['learn.py', 'work.py','entertain.py','else']
bar = ['A.learn.py', '3.entertain.py','&work.py']
</code>```

The result i want is

```<code>('learn.py', 'A.learn.py'), ('work.py', '&work.py'),
('entertain.py','3.entertain.py'), ('else','else')]
</code>```

Here follows my codes:

```<code>zoo = []
for j in bar:
    for i in foo:
        if i in j:
            zoo.append((i,j))
In [3]: zoo
Out[3]: [('learn.py', 'A.learn.py'), ('work.py', '&work.py')]
</code>```

or,

```<code>zoo = []
for i in foo:
    for j in bar:
        if i in j:
            zoo.append((i,j))
In [5]: zoo
Out[5]: [('learn.py', 'A.learn.py'), ('work.py', '&work.py')]
</code>```

How to solve such a problem?

答:
If I understand correctly, bar contains elements which themselves contain an element from foo, correct? Note the reason why entertain.py is not included in your current list is because it's misspelled in bar. This should work:

```<code>foo = ['learn.py', 'work.py','entertain.py','else']
bar = ['A.learn.py', '3.entertain.py','&work.py']
zoo = []
for i in foo:
    item = next((item for item in bar if i in item), None)
    if item:
        zoo.append((i, item))
    else:
        zoo.append((i,i))
</code>```

Title: Pair items in two lists

Body:
i have two lists:

foo = ['learn.py', 'work.py','entertain.py','else']
bar = ['A.learn.py', '3.entertain.py','&work.py']

The result i want is

('learn.py', 'A.learn.py'), ('work.py', '&work.py'),
('entertain.py','3.entertain.py'), ('else','else')]

Here follows my codes:

zoo = []
for j in bar:
    for i in foo:
        if i in j:
            zoo.append((i,j))
In [3]: zoo
Out[3]: [('learn.py', 'A.learn.py'), ('work.py', '&work.py')]

or,

zoo = []
for i in foo:
    for j in bar:
        if i in j:
            zoo.append((i,j))
In [5]: zoo
Out[5]: [('learn.py', 'A.learn.py'), ('work.py', '&work.py')]

How to solve such a problem?

Body:
If I understand correctly, bar contains elements which themselves contain an element from foo, correct? Note the reason why entertain.py is not included in your current list is because it's misspelled in bar. This should work:

foo = ['learn.py', 'work.py','entertain.py','else']
bar = ['A.learn.py', '3.entertain.py','&work.py']
zoo = []
for i in foo:
    item = next((item for item in bar if i in item), None)
    if item:
        zoo.append((i, item))
    else:
        zoo.append((i,i))


问:
Getting local file in iOS using react native
I'm trying to grab an audio file that's been saved locally and upload using firebase. I've tried using react-native-fetch-blob as follows:

import RNFetchBlob from 'react-native-fetch-blob'

const fs = RNFetchBlob.fs

but I'm getting the error:

Error: file not exists

Even though I'm using the same path I get back after storing the file. So I have:

console.log('Full path is ' + fullPath) // Gives /var/mobile/Containers/Data/Application/2446[...]E1A9/Documents/myfile.mp4

but then I when I try

fs.readFile(RNFetchBlob.wrap(fullPath), 'base64').then((data) => ...

I get the "file not exists" error.

Does someone have example code of reading a (binary) file as a blob and using it, especially to upload to firebase storage? All of the examples I've found are grabbing the file from an external URL.

答:
On iOS platform the directory path will be changed every time you access to the file system. So if you need read file on iOS, you need to get dir path first and concat file name with it.</p>

```<code>// fileUri is a string like "file:///var/mobile/Containers/Data/Application/9B754FAA-2588-4FEC-B0F7-6D890B7B4681/Documents/filename"
if (Platform.OS === 'ios') {
  let arr = fileUri.split('/')
  const dirs = RNFetchBlob.fs.dirs
  filePath = `${dirs.DocumentDir}/${arr[arr.length - 1]}`
} else {
  filePath = audioDataUri
}
</code>```

Body:
On iOS platform the directory path will be changed every time you access to the file system. So if you need read file on iOS, you need to get dir path first and concat file name with it.

// fileUri is a string like "file:///var/mobile/Containers/Data/Application/9B754FAA-2588-4FEC-B0F7-6D890B7B4681/Documents/filename"
if (Platform.OS === 'ios') {
  let arr = fileUri.split('/')
  const dirs = RNFetchBlob.fs.dirs
  filePath = `${dirs.DocumentDir}/${arr[arr.length - 1]}`
} else {
  filePath = audioDataUri
}


问:
Azure AD graph API using on-premise domain
I am trying to access the Azure AD graph API. I have successfully added users to my test environment (ADFS) and changed their domain to {mytestdomain}.onmicrosoft.com. The password synchronization using Azure AD Connect works.

Now I have setup the production environment (including ADFS) accordingly and I am now synchronizing the users, but obviously can't change the domains to {mydomain}.onmicrosoft.com. The users now have {mydomain}.net and I am synchronizing the users to a verified domain in Azure AD.

When trying to access
https://login.microsoftonline.com/{mydomain}.net/oauth2/token
using the following (yes, I know that grant_type is not recommended, but that's not the point)

```<code>grant_type: password
username: {user}@{mydomain}.net
password: XXXX
resource: https://graph.windows.net
client_id: {Guid}
</code>```

I get:

AADSTS70002: Error validating credentials.

  AADSTS50126: Invalid username or password

If I use an administrator like admin@{mydomain}.onmicrosoft.com it works fine.

In the Azure portal I have tried changing the primary domain from {mydomain}.onmicrosoft.com to {mydomain}.net, but it does not make a difference.

It says in the management portal:

"To configure {mydomain} for federated sign-on to your Azure Active Directory, run Azure AD Connect on your local network."

Does that apply when using the graph API as well? Do I have to setup federation on my local network or is there another way around?

答:
In the azure portal I have tried changing the primary domain from
  {mydomain}.onmicrosoft.com to {mydomain}.net, but it does not make a
  difference.

I'm not clear the details of your Syncing steps. Besides verified you custom domain in Azure AD, you also need some other configurations, like Azure AD sign-in configuration. You can see more details in this document.

Does that apply when using the graph api as well? Do I have to setup
  federation on my local network or is there another way around?

Yes, Since you're using ADFS, you need to use Federated SSO (with Active Directory Federation Services (AD FS)) to allows your users to sign in to both cloud and on-premises resources by using the same passwords.

You can also see more details about Azure AD Connect user sign-in options in this official document.

Hope it helps!

Body:
I am trying to access the Azure AD graph API. I have successfully added users to my test environment (ADFS) and changed their domain to {mytestdomain}.onmicrosoft.com. The password synchronization using Azure AD Connect works.

Now I have setup the production environment (including ADFS) accordingly and I am now synchronizing the users, but obviously can't change the domains to {mydomain}.onmicrosoft.com. The users now have {mydomain}.net and I am synchronizing the users to a verified domain in Azure AD.

When trying to access
https://login.microsoftonline.com/{mydomain}.net/oauth2/token
using the following (yes, I know that grant_type is not recommended, but that's not the point)

grant_type: password
username: {user}@{mydomain}.net
password: XXXX
resource: https://graph.windows.net
client_id: {Guid}

I get:

AADSTS70002: Error validating credentials.

  AADSTS50126: Invalid username or password

If I use an administrator like admin@{mydomain}.onmicrosoft.com it works fine.

In the Azure portal I have tried changing the primary domain from {mydomain}.onmicrosoft.com to {mydomain}.net, but it does not make a difference.

It says in the management portal:

"To configure {mydomain} for federated sign-on to your Azure Active Directory, run Azure AD Connect on your local network."

Does that apply when using the graph API as well? Do I have to setup federation on my local network or is there another way around?


问:
Which design patterns improve performance?
Always the first thing i hear when we talk about design pattern is like a documented solution to common architectural issues.

I am curious to know which design patterns are good solutions to improve performance of an application in general.

答:
Object Pool Pattern

The object pool pattern is a software creational design pattern that
  uses a set of initialized objects kept ready to use – a "pool" –
  rather than allocating and destroying them on demand.

Object pools are primarily used for performance: in some
  circumstances, object pools significantly improve performance.


问:
How to remove top space from Top of TableView?
In my View controller i have 1 tableview with different Data.

Top Blue colour is View & bottom Blue colour is TabBar.

in Home Screen there's top View & in Trending screen i Hide it by changing it's constraint to 0.

Home and 2. Trending

When i scroll tableview to see new posts & when i click on Trending View i load new data in TableView & scroll tableview to top with the code.

```<code>dispatch_async(dispatch_get_main_queue(), ^{
        [self.tblVW setContentOffset:CGPointZero animated:NO];
        [self.tblVW reloadData];
    });
</code>```

but it will not move to top of tableview.

There's a space at top & when i touch tableview it will scroll to top.

答:
In a grouped tableview,If you want to remove the default header in the top area, try setting:

```<code>tableView.tableHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: 0.1))
</code>```

Grouped TableView:

Before:

After:

Body:
In my View controller i have 1 tableview with different Data.

Top Blue colour is View & bottom Blue colour is TabBar.

in Home Screen there's top View & in Trending screen i Hide it by changing it's constraint to 0.

Home and 2. Trending

When i scroll tableview to see new posts & when i click on Trending View i load new data in TableView & scroll tableview to top with the code.

dispatch_async(dispatch_get_main_queue(), ^{
        [self.tblVW setContentOffset:CGPointZero animated:NO];
        [self.tblVW reloadData];
    });

but it will not move to top of tableview.

There's a space at top & when i touch tableview it will scroll to top.

Body:
In a grouped tableview,If you want to remove the default header in the top area, try setting:

tableView.tableHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: 0.1))

Grouped TableView:

Before:

After:


问:
How to setup jenkins git url for single project from repository
I am working on jenkins android setup,my bitbucket repository contains libraries and android project.I want to generate apk for that android project using jenkins for that i need to serve git url but if i take clone it contains all projects.So how can i take only android project git url to setup in jenkins</p>

答: Just download the GIT Plugin in jenkins. Then configure your newly created Job, in SCM, click Git and paste the URL there. Also, Create a new repo if you want just the smaller part of to get the android files in jenkins. To generate apk in jenkins job, Invoke gradle script in buid trigger then in tasks add packageDebug.


问:
What does assignment to *this do (*this = val)?
I was browsing Qt sources, and noticed this

```<code>QUuid &operator=(const GUID &guid)
{
    *this = QUuid(guid);
    return *this;
}
</code>```

I've never seen assignment to "this" before. What does assignment to "this" do?

答: It just invokes QUuid &operator=(const QUuid& quUid);.

Body:
I was browsing Qt sources, and noticed this

QUuid &operator=(const GUID &guid)
{
    *this = QUuid(guid);
    return *this;
}

I've never seen assignment to "this" before. What does assignment to "this" do?


问:
window.close() => "Scripts may close only the windows that were opened by it." & Outlook behavior
I have a link in my webpage to close window in javascript :

```<code><a href="#" onclick="window.close()">Close the window</a>
</code>```

But when I click it, I have this error in console :

```<code>Scripts may close only the windows that were opened by it.
</code>```

I have done a search on google, and now, I know why. This is the normal behavior (for security reasons I think).

But when I send the link of my page via Outlook, and then, I click to close the page : It works ! Why ???

答:
It may be clear as the error explained. You should use 1 variable to open and then close window, try:</p>

```<code><button onclick="openWin()">Open "myWindow"</button>
<button onclick="closeWin()">Close "myWindow"</button>

<script>
var myWindow;

function openWin() {
    myWindow = window.open("", "myWindow", "width=200,height=100");
    myWindow.document.write("<p>This is 'myWindow'</p>");
}

function closeWin() {
    myWindow.close();
}
</script>
</code>```

Body:
I have a link in my webpage to close window in javascript :

Close the window

But when I click it, I have this error in console :

Scripts may close only the windows that were opened by it.

I have done a search on google, and now, I know why. This is the normal behavior (for security reasons I think).

But when I send the link of my page via Outlook, and then, I click to close the page : It works ! Why ???

Body:
It may be clear as the error explained. You should use 1 variable to open and then close window, try:

<button onclick="openWin()">Open "myWindow"</button>
<button onclick="closeWin()">Close "myWindow"</button>

<script>
var myWindow;

function openWin() {
    myWindow = window.open("", "myWindow", "width=200,height=100");
    myWindow.document.write("<p>This is 'myWindow'</p>");
}

function closeWin() {
    myWindow.close();
}
</script>


问:
At the Pods code , how to get the file under the Resources?

In the file XYShareBtnView.m ,I want to get image in the Resources,how can I do this? TKS!

I want to make a pod , But I do not know How to get the Resource.

答:
There isn't a need for you to pass the path of the image. Just try accessing the image normally using the name of the image.

Objective-C:

```<code>UIImage *img = [UIImage imageNamed:@"anyImageName"];
</code>```

Swift:

```<code>UIImage(string:"imagename")
</code>```

Body:
There isn't a need for you to pass the path of the image. Just try accessing the image normally using the name of the image.

Objective-C:

UIImage *img = [UIImage imageNamed:@"anyImageName"];

Swift:

UIImage(string:"imagename")


问:
Setting default value based on database in DJango
Good evening,

I am new to Django and am working on a sort of ticketing app.  My app has three models, Ticket, Status, & Notes.

When displaying the ticket details, I have a form to add a Note.  What I want to do is to add to the form a drop down that is set to the current status value of the ticket.  When creating the form, how do I pass in the current status value to the form and use it as the default value?

Thanks.

答:
You can set it when calling the form constructor in your view:</p>

```<code>form = NoteForm(initial={'status': ticket.status})
</code>```

Body:
You can set it when calling the form constructor in your view:

form = NoteForm(initial={'status': ticket.status})


问:
Simple Chase Game Movement Using Bresenham’s Line Algorithm
I'm creating a game where I'm trying to use Bresenham's line algorithm(http://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm ) to have enemies chase a player on a 2D map. The concept of the game is similar to the one found below. The pseudo code below is from http://herselfsai.com/2007/07/simple-predator-prey-chase-algorithms.html

```<code>prey current position ( xp, yp )
predator current position ( xP, yP )

x = x position to move to
y = y position to move to
dx = xp – xP
dy = yp – yP
Adx = AbsoluteValue ( dx )
Ady = AbsoluteValue (dy )

if ( xp > xP ) stepX = 1 else stepX = -1
if ( yp > yP ) stepY = 1 else stepY = -1

if ( Ady > Adx ){ //the y distance from prey is larger than the x distance

fraction = 2*dx – dy;

if (( yP != yp ) && ( fraction > 0 )){
x += stepX
}

y += stepY

}else{

fraction = 2*dy – dx;

if (( xP != xp ) && ( fraction > 0 )){
   y += stepY
}

x += stepX
}
</code>```

Enemies chase the player around the map but the it's ether in 0, 45, 90, etc degree angles and not straight line. Also, in my code the enemies also have random speed(between 0 and 5) and are sometimes over shooting the player, then trying to correct and over shoot again and again. That might be a separate issue.

I sure just not fully grasping the concept of the algorithm. What is the correct way to implement this?

Thanks in advance.

答:
Bresenham’s Line Algorithm is an easy to understand and easy to calculate algorithm to make your characters move through a route that's closest to eye to a straight line.

The algorithm will work for your case if cost of going 45 degrees is the same as 90 or 0 degree. Otherwise the route Bresenham takes won't be the fastest.

Body:
I'm creating a game where I'm trying to use Bresenham's line algorithm(http://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm ) to have enemies chase a player on a 2D map. The concept of the game is similar to the one found below. The pseudo code below is from http://herselfsai.com/2007/07/simple-predator-prey-chase-algorithms.html

prey current position ( xp, yp )
predator current position ( xP, yP )

x = x position to move to
y = y position to move to
dx = xp – xP
dy = yp – yP
Adx = AbsoluteValue ( dx )
Ady = AbsoluteValue (dy )

if ( xp > xP ) stepX = 1 else stepX = -1
if ( yp > yP ) stepY = 1 else stepY = -1

if ( Ady > Adx ){ //the y distance from prey is larger than the x distance

fraction = 2*dx – dy;

if (( yP != yp ) && ( fraction > 0 )){
x += stepX
}

y += stepY

}else{

fraction = 2*dy – dx;

if (( xP != xp ) && ( fraction > 0 )){
   y += stepY
}

x += stepX
}

Enemies chase the player around the map but the it's ether in 0, 45, 90, etc degree angles and not straight line. Also, in my code the enemies also have random speed(between 0 and 5) and are sometimes over shooting the player, then trying to correct and over shoot again and again. That might be a separate issue.

I sure just not fully grasping the concept of the algorithm. What is the correct way to implement this?

Thanks in advance.


问:
Turn postgres date representation into ISO 8601 string
I'm trying to format a Postgres date representation into a ISO 8601 string. I'm assuming that there is a Postgres function that can do it, but I found the documentation short on examples.

My query is

```<code>SELECT
  now()::timestamp
</code>```

which returns

```<code>[{{2016, 8, 9}, {3, 56, 55, 754181}}]
</code>```

I'm trying to get the date into a format that looks more like
2016-8-9T03:56:55+00:00.

What changes do I need to make to my query to make that happen? Thanks for your help.

答:
Set the timezone session variable to whatever timezone you want the output to be in, then use to_char(now(), 'YYYY-MM-DD"T"HH24:MI:SSOF')

If you use at time zone '...' be aware that this will strip off any timezone information, and assume that the user already knows the timezone.

If you use at time zone 'UTC' then the output should always be the UTC time, with correct time zone information (no offset).

```<code>set timezone='UTC';

select to_char(now(), 'YYYY-MM-DD"T"HH24:MI:SSOF');

2017-11-17T02:02:26+00  /* UTC time */

select to_char(now() at time zone 'Australia/Sydney', 'YYYY-MM-DD"T"HH24:MI:SSOF');

2017-11-17T13:02:26+00  /* Local Sydney time, but note timezone is incorrect. */

set timezone='Australia/Sydney';

select to_char(now(), 'YYYY-MM-DD"T"HH24:MI:SSOF');

2017-11-17T13:02:26+11  /* Local Sydney time with correct time zone! */

select to_char(now() at time zone 'Australia/Sydney', 'YYYY-MM-DD"T"HH24:MI:SSOF');

2017-11-17T13:02:26+00  /* Still local Sydney time, but time zone info has been removed. */

select to_char(now() at time zone 'UTC', 'YYYY-MM-DD"T"HH24:MI:SSOF');

2017-11-17T02:02:26+00  /* Correct UTC time with correct offset. */
</code>```

This blog post gives quite a detailed explanation.

Body:
I'm trying to format a Postgres date representation into a ISO 8601 string. I'm assuming that there is a Postgres function that can do it, but I found the documentation short on examples.

My query is

SELECT
  now()::timestamp

which returns

[{{2016, 8, 9}, {3, 56, 55, 754181}}]

I'm trying to get the date into a format that looks more like
2016-8-9T03:56:55+00:00.

What changes do I need to make to my query to make that happen? Thanks for your help.

Body:
Set the timezone session variable to whatever timezone you want the output to be in, then use to_char(now(), 'YYYY-MM-DD"T"HH24:MI:SSOF')

If you use at time zone '...' be aware that this will strip off any timezone information, and assume that the user already knows the timezone.

If you use at time zone 'UTC' then the output should always be the UTC time, with correct time zone information (no offset).

set timezone='UTC';

select to_char(now(), 'YYYY-MM-DD"T"HH24:MI:SSOF');

2017-11-17T02:02:26+00  /* UTC time */

select to_char(now() at time zone 'Australia/Sydney', 'YYYY-MM-DD"T"HH24:MI:SSOF');

2017-11-17T13:02:26+00  /* Local Sydney time, but note timezone is incorrect. */

set timezone='Australia/Sydney';

select to_char(now(), 'YYYY-MM-DD"T"HH24:MI:SSOF');

2017-11-17T13:02:26+11  /* Local Sydney time with correct time zone! */

select to_char(now() at time zone 'Australia/Sydney', 'YYYY-MM-DD"T"HH24:MI:SSOF');

2017-11-17T13:02:26+00  /* Still local Sydney time, but time zone info has been removed. */

select to_char(now() at time zone 'UTC', 'YYYY-MM-DD"T"HH24:MI:SSOF');

2017-11-17T02:02:26+00  /* Correct UTC time with correct offset. */

This blog post gives quite a detailed explanation.


问:
Is there a way to calc(div's height - some unit)?
Say there's a div.outer. Inside this div, there are some images and paragraphs. div.outer's height is dynamic because its height is the sum of its children height. However, is there a way to subtract some unit from div.outer's height? Like calc(div's height - 50px)? I happen to need this for some cases.

答:
you can't use of pure css,because for use of calc,we need to height of outside div,and we can't access to it with css.

```<code>$(document).ready(function(){
  var outerHeight = $('.outer').height();
  $('.outer').height(outerHeight - 40);
})
</code>```

$(document).ready(function(){
  var outerHeight = $('.outer').height();
  $('.outer').height(outerHeight - 40);
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.outer {
   background-color: blue;
}</code>```

This is test

This is test

This is test

This is test

```

Body:
you can't use of pure css,because for use of calc,we need to height of outside div,and we can't access to it with css.

$(document).ready(function(){
  var outerHeight = $('.outer').height();
  $('.outer').height(outerHeight - 40);
})

$(document).ready(function(){
  var outerHeight = $('.outer').height();
  $('.outer').height(outerHeight - 40);
})

.outer {
   background-color: blue;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div class="outer">
  <div class="inside">
     <p>This is test</p>
     <p>This is test</p>
     <p>This is test</p>
     <p>This is test</p>
  </div>
</div>


问:
Locking view on QGraphicsView
I'm creating a schematics edit where, simply put, the user can draw lines and rectangles. For this i am using a subclassed QGraphicsView with reimplemented event handlers.
Now, when drawing lines, the view shifts in order to put the centerpoint of all drawn lines together in the middle of the application window (i guess?). For this is very annoying in a drawing program, how can i fix this?

MWE:

```<code>#include <QApplication>
#include <QMainWindow>
#include <QGraphicsView>
#include <QMouseEvent>

class view : public QGraphicsView
{
public:
    view(QGraphicsScene* scene, QWidget* parent = 0) : QGraphicsView::QGraphicsView(scene, parent) { }

    void mousePressEvent(QMouseEvent* event)
    {
        static QPointF p;
        static bool active = false;
        if(!active)
        {
            p = mapToScene(event->pos());
            active = true;
        }
        else
        {
            QPointF p2 = mapToScene(event->pos());
            active = false;
            draw_line(p, p2);
        }
    }

    void draw_line(QPointF p1, QPointF p2)
    {
        QPen pen;
        pen.setWidth(2);
        this->scene()->addLine(p1.x(), p1.y(), p2.x(), p2.y(), pen);
    }
};

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QMainWindow w;
    QGraphicsScene* scene = new QGraphicsScene;
    view* mview = new view(scene);
    w.setCentralWidget(mview);
    w.show();

    return a.exec();
}
</code>```

答:
The problem is caused because you have not set sceneRect to QGraphicsScene, according to the docs:

sceneRect : QRectF

This property holds the scene rectangle; the bounding rectangle of the
  scene

The scene rectangle defines the extent of the scene. It is primarily
  used by QGraphicsView to determine the view's default scrollable area,
  and by QGraphicsScene to manage item indexing.

If unset, or if set to a null QRectF, sceneRect() will return the
  largest bounding rect of all items on the scene since the scene was
  created (i.e., a rectangle that grows when items are added to or moved
  in the scene, but never shrinks).

So every time you add a new line if it is larger than the previous QGraphicsScene try to adapt to that size giving the feeling that is moving the center.

For example in your case:

```<code>view(QGraphicsScene* scene, QWidget* parent = 0) :
QGraphicsView::QGraphicsView(scene, parent)
{
    scene->setSceneRect(QRectF(rect()));
    //scene->setSceneRect(0, 0, 640, 480)
}
</code>```

Title: Locking view on QGraphicsView

Body:
I'm creating a schematics edit where, simply put, the user can draw lines and rectangles. For this i am using a subclassed QGraphicsView with reimplemented event handlers.
Now, when drawing lines, the view shifts in order to put the centerpoint of all drawn lines together in the middle of the application window (i guess?). For this is very annoying in a drawing program, how can i fix this?

MWE:

#include <QApplication>
#include <QMainWindow>
#include <QGraphicsView>
#include <QMouseEvent>

class view : public QGraphicsView
{
public:
    view(QGraphicsScene* scene, QWidget* parent = 0) : QGraphicsView::QGraphicsView(scene, parent) { }

    void mousePressEvent(QMouseEvent* event)
    {
        static QPointF p;
        static bool active = false;
        if(!active)
        {
            p = mapToScene(event->pos());
            active = true;
        }
        else
        {
            QPointF p2 = mapToScene(event->pos());
            active = false;
            draw_line(p, p2);
        }
    }

    void draw_line(QPointF p1, QPointF p2)
    {
        QPen pen;
        pen.setWidth(2);
        this->scene()->addLine(p1.x(), p1.y(), p2.x(), p2.y(), pen);
    }
};

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QMainWindow w;
    QGraphicsScene* scene = new QGraphicsScene;
    view* mview = new view(scene);
    w.setCentralWidget(mview);
    w.show();

    return a.exec();
}

Body:
The problem is caused because you have not set sceneRect to QGraphicsScene, according to the docs:

sceneRect : QRectF

This property holds the scene rectangle; the bounding rectangle of the
  scene

The scene rectangle defines the extent of the scene. It is primarily
  used by QGraphicsView to determine the view's default scrollable area,
  and by QGraphicsScene to manage item indexing.

If unset, or if set to a null QRectF, sceneRect() will return the
  largest bounding rect of all items on the scene since the scene was
  created (i.e., a rectangle that grows when items are added to or moved
  in the scene, but never shrinks).

So every time you add a new line if it is larger than the previous QGraphicsScene try to adapt to that size giving the feeling that is moving the center.

For example in your case:

view(QGraphicsScene* scene, QWidget* parent = 0) :
QGraphicsView::QGraphicsView(scene, parent)
{
    scene->setSceneRect(QRectF(rect()));
    //scene->setSceneRect(0, 0, 640, 480)
}


问:
VBA - Type mismatch on declaration of Excel.Range
I am trying to declare a range of cells as an Excel.Range variable in the BeforeSave() event of  my excel workbook.
The background is, that the values in this range are mandatory inputs and I want to validate that they are all filled on saving.

If I want to execute the function I get the error message

Runtime Error "13": Type Mismatch

Here's the code I tried.

```<code>Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
    Dim r1 As Range
    Set r1 = Range("G11:G14")

        If Cells(10, 1).Value = "" Then
            MsgBox "Cell requires user input", vbInformation, "Please filled up the mandatory cells"
            Cancel = True
            Exit Sub
        ElseIf r1.Value = "" Then // runtime error "13": Type Mismatch
            MsgBox "Please make sure you had filled in all the Questionnire Answers.", vbInformation, "Missing Answer"
            Cancel = True
            Exit Sub
        End If
        Cancel = False
End Sub
</code>```

I am relatively new to VBA so please feel free to point out my mistake.
Thanks in advance!

答: I suspect it's because you need to qualify your range definition to say Set r1 = ThisWorkbook.Range("G11:G14"). Also, I believe that the .Value property of a multi-cell range will return the value in the top leftmost cell.

Body:
I am trying to declare a range of cells as an Excel.Range variable in the BeforeSave() event of  my excel workbook.
The background is, that the values in this range are mandatory inputs and I want to validate that they are all filled on saving.

If I want to execute the function I get the error message

Runtime Error "13": Type Mismatch

Here's the code I tried.

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
    Dim r1 As Range
    Set r1 = Range("G11:G14")

        If Cells(10, 1).Value = "" Then
            MsgBox "Cell requires user input", vbInformation, "Please filled up the mandatory cells"
            Cancel = True
            Exit Sub
        ElseIf r1.Value = "" Then // runtime error "13": Type Mismatch
            MsgBox "Please make sure you had filled in all the Questionnire Answers.", vbInformation, "Missing Answer"
            Cancel = True
            Exit Sub
        End If
        Cancel = False
End Sub

I am relatively new to VBA so please feel free to point out my mistake.
Thanks in advance!


问:
Reading a particular column in csv file using numpy in python
How to read string column only using numpy in python?

csv file:

```<code>1,2,3,"Hello"
3,3,3,"New"
4,5,6,"York"
</code>```

How to get array like:

```<code>["Hello","york","New"]
</code>```

without using pandas and sklearn.

答:
I give the column name as a,b,c,d in csv

```<code>import numpy as np
ary=np.genfromtxt(r'yourcsv.csv',delimiter=',',dtype=None)
ary.T[-1]
Out[139]:
array([b'd', b'Hello', b'New', b'York'],
      dtype='|S5')
</code>```

Body:
How to read string column only using numpy in python?

csv file:

1,2,3,"Hello"
3,3,3,"New"
4,5,6,"York"

How to get array like:

["Hello","york","New"]

without using pandas and sklearn.

Body:
I give the column name as a,b,c,d in csv

import numpy as np
ary=np.genfromtxt(r'yourcsv.csv',delimiter=',',dtype=None)
ary.T[-1]
Out[139]:
array([b'd', b'Hello', b'New', b'York'],
      dtype='|S5')


问:
parsing text file in pyspark
i am trying to convert the below text file to a hive table using pyspark.

so my text file looks like the below

```<code>nethandle: 129
orgid: csu
netname: east

nethandle: 908
orgid: dmo
netname: west

nethandle: 987
orgid: csu
netname: west
</code>```

my code is the below

```<code>lines=sc.textFile("/tmp/sample/sam.txt")
parts=lines.flatMap(lambda l:tuple(l.split(""))
for j in parts.collect():
    print(j)
</code>```

but the result i am getting the same as input. But i am expecting something like this

```<code>[129,csu,east]
[908,dmo,west]
[987,csu,east]
</code>```

could u plz help me in this.i am not sure how to use lambda function...thanks in advance.

答:
OK so here's an idea that may work. Pyspark offers a .zipWithIndex() function that is like python's built-in enumerate. You could use this to add an index to each row, and then since each record is 4 lines (including a blank line) you could take the mod-4 of each index and make that the record key. aggregateByKey() should let you group those.

Something like this (I don't have spark installed and can't test this right now):

```<code>sc = pyspark.SparkContext()
lines = sc.textFile("/tmp/sample/sam.txt")
parts = lines.zipWithIndex() \
    .map(lambda row: (row[0] % 4, row[1].split(": ")[-1])) \
    .aggregateByKey([], lambda a, b: a + [b], lambda a, b: a + b)
print(parts.collect())
</code>```

I'm going to show the same code again, without using lambda, to help you see how to write lambdas:

```<code>def add_key_and_split_line(index, line):
    key = index % 4
    value = line.split(": ")[-1]
    return key, value

def join_list_to_val(a, b):
    return a + [b]

def join_list_to_list(a, b):
    return a + b

sc = pyspark.SparkContext()
lines = sc.textFile("/tmp/sample/sam.txt")
parts = lines.zipWithIndex() \
    .map(add_key_and_split_line) \
    .aggregateByKey([], join_list_to_val, join_list_to_list)
print(parts.collect())
</code>```

Title: parsing text file in pyspark

Body:
i am trying to convert the below text file to a hive table using pyspark.

so my text file looks like the below

nethandle: 129
orgid: csu
netname: east

nethandle: 908
orgid: dmo
netname: west

nethandle: 987
orgid: csu
netname: west

my code is the below

lines=sc.textFile("/tmp/sample/sam.txt")
parts=lines.flatMap(lambda l:tuple(l.split(""))
for j in parts.collect():
    print(j)

but the result i am getting the same as input. But i am expecting something like this

[129,csu,east]
[908,dmo,west]
[987,csu,east]

could u plz help me in this.i am not sure how to use lambda function...thanks in advance.

Body:
OK so here's an idea that may work. Pyspark offers a .zipWithIndex() function that is like python's built-in enumerate. You could use this to add an index to each row, and then since each record is 4 lines (including a blank line) you could take the mod-4 of each index and make that the record key. aggregateByKey() should let you group those.

Something like this (I don't have spark installed and can't test this right now):

sc = pyspark.SparkContext()
lines = sc.textFile("/tmp/sample/sam.txt")
parts = lines.zipWithIndex() \
    .map(lambda row: (row[0] % 4, row[1].split(": ")[-1])) \
    .aggregateByKey([], lambda a, b: a + [b], lambda a, b: a + b)
print(parts.collect())

I'm going to show the same code again, without using lambda, to help you see how to write lambdas:

def add_key_and_split_line(index, line):
    key = index % 4
    value = line.split(": ")[-1]
    return key, value

def join_list_to_val(a, b):
    return a + [b]

def join_list_to_list(a, b):
    return a + b

sc = pyspark.SparkContext()
lines = sc.textFile("/tmp/sample/sam.txt")
parts = lines.zipWithIndex() \
    .map(add_key_and_split_line) \
    .aggregateByKey([], join_list_to_val, join_list_to_list)
print(parts.collect())


问:
PHP - How can I add an item to a sub array, then sort the parent array by a new order?
I want to add an item to a sub array and sort the array by a new order.

Here is my data:

```<code>$number = '112';
$user = 2;
</code>```

And this is my array:

```<code>array(
1 => array(111, 109, 108),
2 => array(110, 107, 105),
3 => array(99, 97, 96)
)
</code>```

I want to add a value in this array and sort it by a new order. So, my array needs to end up like this:

```<code>array(
2 => array(112, 110, 107, 105),
1 => array(111, 109, 108),
3 => array(99, 97, 96)
)
</code>```

How can I do this quickly?

答:
Assuming there would be a case where there's a number in the user's array greater than $number

```<code>$number = '112';
$user = 2;

$array = array(
1 => array(111, 109, 108),
2 => array(110, 107, 105),
3 => array(99, 97, 96)
);

$array[$user][] = $number; // add number to user's array
rsort($array[$user]);      // sort highest to lowest
$array = array($user => $array[$user]) + $array; // move the newly modified array to first element

echo '```';
print_r($array);
```

Body:
I want to add an item to a sub array and sort the array by a new order.

Here is my data:

$number = '112';
$user = 2;

And this is my array:

array(
1 => array(111, 109, 108),
2 => array(110, 107, 105),
3 => array(99, 97, 96)
)

I want to add a value in this array and sort it by a new order. So, my array needs to end up like this:

array(
2 => array(112, 110, 107, 105),
1 => array(111, 109, 108),
3 => array(99, 97, 96)
)

How can I do this quickly?

Body:
Assuming there would be a case where there's a number in the user's array greater than $number

$number = '112';
$user = 2;

$array = array(
1 => array(111, 109, 108),
2 => array(110, 107, 105),
3 => array(99, 97, 96)
);

$array[$user][] = $number; // add number to user's array
rsort($array[$user]);      // sort highest to lowest
$array = array($user => $array[$user]) + $array; // move the newly modified array to first element

echo '<pre>';
print_r($array);


问:
How to rank a list with multiple conditions on c#
I am trying to figure out how to rank a list with multiple conditions:

This is my list:

Let me explain the list above:

a. 'AreaCode' is an unique ID for each group of the list.

b. I will rank the list based on highest value of Rank 1 (highlighted with yellow).

c. If Rank 1 has same value, I will find highest value of Rank 2 (highlighted by green).

d. If Rank 2 has same value, I will find highest value of Rank 3 (highlighted by blue).

e. In this case, there are same value for Rank 1 (7 and 7), so I will find the highest value for Rank 2, however the Rank 2 value also same (4 and 4), so I will find the highest value for Rank 3 (1 and 2).

f. So 'Ranking' column is the result that I want to achieve, which is a list with these value:
 [1, 1, 1, 3, 3, 3, 2, 2, 2, 2, 2, 2, 1, 1, 1, 3, 3, 3].

Last time I can do but with simple scenario (there are no Rank 1, Rank 2 or Rank 3) using this code:

```<code>var rankings = myIndexList.GroupBy(x => x)
.OrderByDescending(g => g.Key)
.Select((g, i) => new { Key = g.Key, Rank = i + 1 })
.ToDictionary(x => x.Key, x => x.Rank);

var output = myIndexList.Select(x => new { Col1 = x, Rank = rankings[x] })
.ToList();
</code>```

Any ideas to achieve the result on 'Ranking' column?

Thank You!

答:
I recommend this.</p>

```<code>public class Item
{
    public string Name { get; set; }
    public int Value { get; set; }
}

/////
var list = new List<(Item Col1, int Rank)>();

var nameGroup = items.GroupBy(i => i.Name);
var sorted = nameGroup.OrderBy(i => i.Key);

foreach (var group in sorted)
{
    int ranking = 1;
    foreach (var item in group.OrderByDescending(i => i.Value))
    {
        list.Add((Col1: item, Rank: ranking++));
    }
}
</code>```

Body:
I am trying to figure out how to rank a list with multiple conditions:

This is my list:

Let me explain the list above:

a. 'AreaCode' is an unique ID for each group of the list.

b. I will rank the list based on highest value of Rank 1 (highlighted with yellow).

c. If Rank 1 has same value, I will find highest value of Rank 2 (highlighted by green).

d. If Rank 2 has same value, I will find highest value of Rank 3 (highlighted by blue).

e. In this case, there are same value for Rank 1 (7 and 7), so I will find the highest value for Rank 2, however the Rank 2 value also same (4 and 4), so I will find the highest value for Rank 3 (1 and 2).

f. So 'Ranking' column is the result that I want to achieve, which is a list with these value:
 [1, 1, 1, 3, 3, 3, 2, 2, 2, 2, 2, 2, 1, 1, 1, 3, 3, 3].

Last time I can do but with simple scenario (there are no Rank 1, Rank 2 or Rank 3) using this code:

var rankings = myIndexList.GroupBy(x => x)
.OrderByDescending(g => g.Key)
.Select((g, i) => new { Key = g.Key, Rank = i + 1 })
.ToDictionary(x => x.Key, x => x.Rank);

var output = myIndexList.Select(x => new { Col1 = x, Rank = rankings[x] })
.ToList();

Any ideas to achieve the result on 'Ranking' column?

Thank You!

Body:
I recommend this.

public class Item
{
    public string Name { get; set; }
    public int Value { get; set; }
}

/////
var list = new List<(Item Col1, int Rank)>();

var nameGroup = items.GroupBy(i => i.Name);
var sorted = nameGroup.OrderBy(i => i.Key);

foreach (var group in sorted)
{
    int ranking = 1;
    foreach (var item in group.OrderByDescending(i => i.Value))
    {
        list.Add((Col1: item, Rank: ranking++));
    }
}


问:
Adding a point every time a div is a certain color, and has been clicked on
So I am trying to create a game with divs that change color, and give the user a point every time they click on a div that is flashing with color. The user will only get a point if the div is flashing that color, so that condition must be satisfied, I know that for sure. The points will display in another div below the colored divs. I have gotten the divs to change color on an interval, however, I cannot get the point system to work, despite creating an if statement that checks the conditions for background color and whether or not the div has been clicked on. Here is my code:</p>

```<code><!DOCTYPE html>
<HTML>

<HEAD>
<STYLE>
.container {
 border: 1px solid black;
 min-width: 100%;
 min-height: 50px;
margin: auto;
 }
   .bigbox {
   min-width: 100%;
   min-height: 100px;
   overflow: scroll;
   border: 1px solid black;
   }
   #bluebox {
   width: 100px;
    height: 100px;
    border: 4px solid black;
    background-color: grey;
    display: inline-block;
   }
 #redbox {
 width: 100px;
 height: 100px;
 border: 4px solid black;
 background-color: grey;
 display: inline-block;
 }
#yellowbox {
width: 100px;
height: 100px;
border: 4px solid black;
background-color: grey;
display: inline-block;
}
  #greenbox {
   width: 100px;
   height: 100px;
   border: 4px solid black;
   background-color: grey;
  display: inline-block;
  }
 </STYLE>
<SCRIPT>
var score = 0;

  function start_game() {
   setTimeout(function() {
 document.getElementById("redbox").style.backgroundColor = "red";
  }, 1000);

   setTimeout(function()
   {document.getElementById("redbox").style.backgroundColor = "grey";
    }, 2000);

   setTimeout(function() {
   document.getElementById("greenbox").style.backgroundColor = "green";
    }, 2000);
   setTimeout(function() {
  document.getElementById("greenbox").style.backgroundColor = "grey";
   }, 3000);

     setTimeout(function() {
   document.getElementById("bluebox").style.backgroundColor = "blue";
    }, 3000);
    setTimeout(function() {
   document.getElementById("bluebox").style.backgroundColor = "grey";
   }, 4000);

   setTimeout(function() {
    document.getElementById("yellowbox").style.backgroundColor = "yellow";
    }, 4000);
  setTimeout(function() {
   document.getElementById("yellowbox").style.backgroundColor = "grey";
   }, 5000);

   setInterval(function(){ start_game() }, 5500);

   if(document.getElementById("redbox").style.backgroundColor = "red" &&
   document.getElementById("redbox").clicked == true) {
   document.getElementById("score").innerHTML =  score + 1;
    alert("You got a point!");
    }

  }

 </SCRIPT>
 <TITLE> Game </TITLE>
 </HEAD>

 <BODY>
 <DIV class="container">
 <CENTER>
 <DIV id="redbox"> </DIV>
<DIV id="greenbox"> </DIV>
<DIV id="bluebox"> </DIV>
<DIV id="yellowbox"> </DIV>
</CENTER>
</DIV>

 <BR><BR>

  <DIV class="container" style= "background-color: grey;"> <CENTER> <BR>
  <button onclick="start_game()"> Start game </button> </CENTER> </DIV>
  <BR><BR>

  <DIV class="bigbox">
  Press "Start Game" to begin. <br>
  Score <p id="score"> 0 </p>

 </DIV>

</HTML>
</code>```

答:
This is because there is no property called clicked in a div. The proper way is to add an event listener to each div. I will give you an example for one of the divs

```<code>document.getElementById("redbox").addEventListener("click", function(e) {
  //e.target is the same div we added the event listener to
  if(e.target.style.backgroundColor == "red") {
    document.getElementById("score").innerHTML =  score + 1;
    alert("You got a point!");
  }
});
</code>```

The above runs every time a user clicks on that particular div. The function we are passing as the second argument is the event handler for the click event on that div.

As you have probably already guessed, you will have to add an event listener to every div in order to detect if they were clicked.

Body:
So I am trying to create a game with divs that change color, and give the user a point every time they click on a div that is flashing with color. The user will only get a point if the div is flashing that color, so that condition must be satisfied, I know that for sure. The points will display in another div below the colored divs. I have gotten the divs to change color on an interval, however, I cannot get the point system to work, despite creating an if statement that checks the conditions for background color and whether or not the div has been clicked on. Here is my code:

<!DOCTYPE html>

 <TITLE> Game </TITLE>

  <button onclick="start_game()"> Start game </button>

  Press "Start Game" to begin.

  Score
 0

Body:
This is because there is no property called clicked in a div. The proper way is to add an event listener to each div. I will give you an example for one of the divs

document.getElementById("redbox").addEventListener("click", function(e) {
  //e.target is the same div we added the event listener to
  if(e.target.style.backgroundColor == "red") {
    document.getElementById("score").innerHTML =  score + 1;
    alert("You got a point!");
  }
});

The above runs every time a user clicks on that particular div. The function we are passing as the second argument is the event handler for the click event on that div.

As you have probably already guessed, you will have to add an event listener to every div in order to detect if they were clicked.