问:
Maven and adding JARs to system scope
I have a JAR in my Android project and I want it to be added to final APK.
Okay, here I go:

    <dependency>
        <groupId>com.loopj.android.http</groupId>
        <artifactId>android-async-http</artifactId>
        <version>1.3.2</version>
        <type>jar</type>
        <scope>system</scope>
        <systemPath>${project.basedir}/libs/android-async-http-1.3.2.jar</systemPath>
    </dependency>
```

<p>But when I am running <code>mvn package</code> I am getting a warning:</p>

```[WARNING] Some problems were encountered while building the effective model for **apk:1.0
[WARNING] 'dependencies.dependency.systemPath' for com.loopj.android.http:android-async-http:jar should not point at files within the project directory, ${project.basedir}/libs/android-async-http-1.3.2.jar will be unresolvable by dependent projects @ line 36, column 25
```

And in the final APK there are no JARs.

How do I fix that?

答:
```<code><plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    <configuration>
        <includeSystemScope>true</includeSystemScope>
    </configuration>
</plugin>
</code>```

Try this.

Title: Maven and adding JARs to system scope

Body:
I have a JAR in my Android project and I want it to be added to final APK.
Okay, here I go:

    <dependency>
        <groupId>com.loopj.android.http</groupId>
        <artifactId>android-async-http</artifactId>
        <version>1.3.2</version>
        <type>jar</type>
        <scope>system</scope>
        <systemPath>${project.basedir}/libs/android-async-http-1.3.2.jar</systemPath>
    </dependency>

But when I am running mvn package I am getting a warning:

[WARNING] Some problems were encountered while building the effective model for **apk:1.0
[WARNING] 'dependencies.dependency.systemPath' for com.loopj.android.http:android-async-http:jar should not point at files within the project directory, ${project.basedir}/libs/android-async-http-1.3.2.jar will be unresolvable by dependent projects @ line 36, column 25

And in the final APK there are no JARs.

How do I fix that?

Body:
<plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    <configuration>
        <includeSystemScope>true</includeSystemScope>
    </configuration>
</plugin>

Try this.


来源: stackexchange

问:
Prevent "overscrolling" of web page
In Chrome for Mac, one can "overscroll" a page (for lack of a better word), as shown in the screenshot below, to see "what's behind", similar to the iPad or iPhone.

I've noticed that some pages have it disabled, like gmail and the "new tab" page.

How can I disable "overscrolling"? Are there other ways in which I can control "overscrolling"?

答:
In Chrome 63+, Firefox 59+ and Opera 50+ you can do this in CSS:

```<code>body {
  overscroll-behavior-y: none;
}
</code>```

This disables the rubberbanding effect on iOS shown in the screenshot of the question. It however also disables pull-to-refresh, glow effects and scroll chaining.

You can however elect to implement your own effect or functionality upon over-scrolling. If you for instance want to blur the page and add a neat animation:

```<code><style>
  body.refreshing #inbox {
    filter: blur(1px);
    touch-action: none; /* prevent scrolling */
  }
  body.refreshing .refresher {
    transform: translate3d(0,150%,0) scale(1);
    z-index: 1;
  }
  .refresher {
    --refresh-width: 55px;
    pointer-events: none;
    width: var(--refresh-width);
    height: var(--refresh-width);
    border-radius: 50%;
    position: absolute;
    transition: all 300ms cubic-bezier(0,0,0.2,1);
    will-change: transform, opacity;
    ...
  }
</style>

<div class="refresher">
  <div class="loading-bar"></div>
  <div class="loading-bar"></div>
  <div class="loading-bar"></div>
  <div class="loading-bar"></div>
</div>

<section id="inbox"><!-- msgs --></section>

<script>
  let _startY;
  const inbox = document.querySelector('#inbox');

  inbox.addEventListener('touchstart', e => {
    _startY = e.touches[0].pageY;
  }, {passive: true});

  inbox.addEventListener('touchmove', e => {
    const y = e.touches[0].pageY;
    // Activate custom pull-to-refresh effects when at the top of the container
    // and user is scrolling up.
    if (document.scrollingElement.scrollTop === 0 && y > _startY &&
        !document.body.classList.contains('refreshing')) {
      // refresh inbox.
    }
  }, {passive: true});
</script>
</code>```

Browser Support

As of this writing Chrome 63+, Firefox 59+ and Opera 50+ support it. Edge publically supported it while Safari is an unknown. Track progress here and current browser compatibility at MDN documentation

More information

Chrome 63 release video

Chrome 63 release post - contains links and details to everything I wrote above.

overscroll-behavior CSS spec

MDN documentation

ContentLicense: CC BY-SA 3.0

Title: Prevent "overscrolling" of web page

Body:
In Chrome 63+, Firefox 59+ and Opera 50+ you can do this in CSS:

body {
  overscroll-behavior-y: none;
}

This disables the rubberbanding effect on iOS shown in the screenshot of the question. It however also disables pull-to-refresh, glow effects and scroll chaining.

You can however elect to implement your own effect or functionality upon over-scrolling. If you for instance want to blur the page and add a neat animation:

<style>
  body.refreshing #inbox {
    filter: blur(1px);
    touch-action: none; /* prevent scrolling */
  }
  body.refreshing .refresher {
    transform: translate3d(0,150%,0) scale(1);
    z-index: 1;
  }
  .refresher {
    --refresh-width: 55px;
    pointer-events: none;
    width: var(--refresh-width);
    height: var(--refresh-width);
    border-radius: 50%;
    position: absolute;
    transition: all 300ms cubic-bezier(0,0,0.2,1);
    will-change: transform, opacity;
    ...
  }
</style>

<div class="refresher">
  <div class="loading-bar"></div>
  <div class="loading-bar"></div>
  <div class="loading-bar"></div>
  <div class="loading-bar"></div>
</div>

<section id="inbox"><!-- msgs --></section>

<script>
  let _startY;
  const inbox = document.querySelector('#inbox');

  inbox.addEventListener('touchstart', e => {
    _startY = e.touches[0].pageY;
  }, {passive: true});

  inbox.addEventListener('touchmove', e => {
    const y = e.touches[0].pageY;
    // Activate custom pull-to-refresh effects when at the top of the container
    // and user is scrolling up.
    if (document.scrollingElement.scrollTop === 0 && y > _startY &&
        !document.body.classList.contains('refreshing')) {
      // refresh inbox.
    }
  }, {passive: true});
</script>

Browser Support

As of this writing Chrome 63+, Firefox 59+ and Opera 50+ support it. Edge publically supported it while Safari is an unknown. Track progress here and current browser compatibility at MDN documentation

More information

Chrome 63 release video

Chrome 63 release post - contains links and details to everything I wrote above.

overscroll-behavior CSS spec

MDN documentation


问:
Precision Matlab and Python (numpy)
I'm converting a Matlab script to Python and I am getting different results in the 10**-4 order.

In matlab:

```<code>f_mean=f_mean+nanmean(f);
f = f - nanmean(f);

f_t  = gradient(f);
f_tt = gradient(f_t);

if n_loop==1
  theta = atan2( sum(f.*f_tt), sum(f.^2) );
end

theta = -2.2011167e+03
</code>```

In Python:

```<code>f_mean = f_mean + np.nanmean(vel)

vel = vel - np.nanmean(vel)

firstDerivative = np.gradient(vel)
secondDerivative = np.gradient(firstDerivative)

if numberLoop == 1:
    theta = np.arctan2(np.sum(vel * secondDerivative),
                       np.sum([vel**2]))
</code>```

Although first and secondDerivative give the same results in Python and Matlab, f_mean is slightly different: -0.0066412 (Matlab) and -0.0066414 (Python); and so theta: -0.4126186 (M) and -0.4124718 (P). It is a small difference, but in the end leads to different results in my scripts.

I know some people asked about this difference, but always regarding std, which I get, but not regarding mean values. I wonder why it is.

答:
One possible source of the initial difference you describe (between means) could be numpy's use of pairwise summation which on large arrays will typically be appreciably more accurate than the naive method:

```<code>a = np.random.uniform(-1, 1, (10**6,))
a = np.r_[-a, a]
# so the sum should be zero

a.sum()
# 7.815970093361102e-14

# use cumsum to get naive summation:
a.cumsum()[-1]
# -1.3716805469243809e-11
</code>```

Edit (thanks @sascha): for the last word and as a "provably exact" reference you could use math.fsum:

```<code>import math
math.fsum(a)
# 0.0
</code>```

Don't have matlab, so can't check what they are doing.

Title: Precision Matlab and Python (numpy)

Body:
I'm converting a Matlab script to Python and I am getting different results in the 10**-4 order.

In matlab:

f_mean=f_mean+nanmean(f);
f = f - nanmean(f);

f_t  = gradient(f);
f_tt = gradient(f_t);

if n_loop==1
  theta = atan2( sum(f.*f_tt), sum(f.^2) );
end

theta = -2.2011167e+03

In Python:

f_mean = f_mean + np.nanmean(vel)

vel = vel - np.nanmean(vel)

firstDerivative = np.gradient(vel)
secondDerivative = np.gradient(firstDerivative)

if numberLoop == 1:
    theta = np.arctan2(np.sum(vel * secondDerivative),
                       np.sum([vel**2]))

Although first and secondDerivative give the same results in Python and Matlab, f_mean is slightly different: -0.0066412 (Matlab) and -0.0066414 (Python); and so theta: -0.4126186 (M) and -0.4124718 (P). It is a small difference, but in the end leads to different results in my scripts.

I know some people asked about this difference, but always regarding std, which I get, but not regarding mean values. I wonder why it is.

Body:
One possible source of the initial difference you describe (between means) could be numpy's use of pairwise summation which on large arrays will typically be appreciably more accurate than the naive method:

a = np.random.uniform(-1, 1, (10**6,))
a = np.r_[-a, a]
# so the sum should be zero

a.sum()
# 7.815970093361102e-14

# use cumsum to get naive summation:
a.cumsum()[-1]
# -1.3716805469243809e-11

Edit (thanks @sascha): for the last word and as a "provably exact" reference you could use math.fsum:

import math
math.fsum(a)
# 0.0

Don't have matlab, so can't check what they are doing.


问:
how to measure the page time load?
I want to know how much time a specific code in my App takes ?!!!
Thank you </p>

答:
You could use the Stopwatch class:</p>

```<code>var watch = Stopwatch.StartNew();
// Run your code here
watch.Stop();
long milliseconds = watch.ElapsedMilliseconds;
</code>```

ContentLicense: CC BY-SA 2.5

Title: how to measure the page time load?

Body:
You could use the Stopwatch class:

var watch = Stopwatch.StartNew();
// Run your code here
watch.Stop();
long milliseconds = watch.ElapsedMilliseconds;


问:
TF26180: An item with this ID already exists in the input Array
I am using below flat query to get bug details for array of work item ids passed as argument.
 Below query works perfectly fine, but it throws error in some cases   "TF26180: An item with this ID already exists in the input Array"
 Reason is, ids array has duplicate ids, which is expected in my case. Is there any way to ignore this check or by pass this ?

```<code>                 var flatQuery = new Query(_store, detailsWiql.ToString(), ids);
                 WorkItemCollection workitems = flatQuery.RunQuery();

                foreach (WorkItem wi in workitems)
                 {

                    WorkItemType worktype = wi.Type;
                     worktypename = worktype.Name;
   }
</code>```

Thanks in advance

答:
I don't think we can ignore or by pass this check, the exception is defined in Microsoft.TeamFoundation.WorkItemTracking.Common assembly.  See https://www.powershellgallery.com/packages/PSPlus.Tfs/0.0.1.104/Content/Microsoft.TeamFoundation.WorkItemTracking.Common.xml

There is a doubt here, why you have duplicated work items?
Generally,  the work item ID is unique in TFS server.
I suggest you delete the duplicated work items first, backup them if needed, then create new work items to track the related tasks/features.

UPDATE:

As a workaround, you can try using the WIQL query with REST API to get the IDs first, See A flat query. The write code to serach work item details with ID in loop. See Get a workitem with REST API.

Besides, you can have a try with the Wiql Editor, it can query the basic work item information directly.

Body:
I am using below flat query to get bug details for array of work item ids passed as argument.
 Below query works perfectly fine, but it throws error in some cases   "TF26180: An item with this ID already exists in the input Array"
 Reason is, ids array has duplicate ids, which is expected in my case. Is there any way to ignore this check or by pass this ?

                 var flatQuery = new Query(_store, detailsWiql.ToString(), ids);
                 WorkItemCollection workitems = flatQuery.RunQuery();

                foreach (WorkItem wi in workitems)
                 {

                    WorkItemType worktype = wi.Type;
                     worktypename = worktype.Name;
   }

Thanks in advance


问:
Regex replace for commas in the thousands
I have a Javascript function I'm using to loop through a bunch of inputs on a page and convert them to a thousands-compatible comma system. In short, regardless of what the user types into the field, they'll get a friendly thousands-separated number back.

```<code>Input: 5000
Return: 5,000
</code>```

Here's how the function breaks down

```<code>function add_commas()
{
    $('.field-group .field input[type=text]').each(function()
    {
        // format number
        $(this).val(function(index, value) {
            return value
            .replace(/\D/g, "")
            .replace(/\B(?=(\d{3})+(?!\d))/g, ",")
            ;
        });
    });
}
</code>```

Everything's working right except for one thing. Here's another example of the data being passed in and what's returned:

```<code>Input: 9.5
Return: 95
</code>```

Note the whole number.

I'm wondering if there's a way to ignore or leave off the decimal if it didn't have one, but keep it and treat it respectfully if there is one. Here's the input/output as I would hope for:

```<code>Input: 5000
Return: 5,000

Input: 9.5
Return: 9.5

Input: 1000.50
Return: 1,000.50
</code>```

Hopefully this was clear, but please do let me know if you require more information about the issue at hand. Thank you!

答:
Change the first replace because it is removing the dot in the string</p>

```<code>.replace(/[^0-9\.]/g, "")
</code>```

Body:
I have a Javascript function I'm using to loop through a bunch of inputs on a page and convert them to a thousands-compatible comma system. In short, regardless of what the user types into the field, they'll get a friendly thousands-separated number back.

Input: 5000
Return: 5,000

Here's how the function breaks down

function add_commas()
{
    $('.field-group .field input[type=text]').each(function()
    {
        // format number
        $(this).val(function(index, value) {
            return value
            .replace(/\D/g, "")
            .replace(/\B(?=(\d{3})+(?!\d))/g, ",")
            ;
        });
    });
}

Everything's working right except for one thing. Here's another example of the data being passed in and what's returned:

Input: 9.5
Return: 95

Note the whole number.

I'm wondering if there's a way to ignore or leave off the decimal if it didn't have one, but keep it and treat it respectfully if there is one. Here's the input/output as I would hope for:

Input: 5000
Return: 5,000

Input: 9.5
Return: 9.5

Input: 1000.50
Return: 1,000.50

Hopefully this was clear, but please do let me know if you require more information about the issue at hand. Thank you!

Body:
Change the first replace because it is removing the dot in the string

.replace(/[^0-9\.]/g, "")


问:
Playing sound in React.js
```<code>import React, { Component } from 'react'
import { Button, Input, Icon,Dropdown,Card} from 'semantic-ui-react'
import { Link } from 'react-router-dom'
import $ from 'jquery'
import styles from './Home.scss'
import Modal from './Modal.jsx'
import MakeChannelModal from './MakeChannelModal.jsx'

class Music extends React.Component {
    constructor(props) {
    super(props);
    this.state = {

      play: false,
      pause: true

    };

    this.url = "http://streaming.tdiradio.com:8000/house.mp3";
    this.audio = new Audio(this.url);

  }

  play(){
    this.setState({
      play: true,
      pause: false
    });
    console.log(this.audio);
    this.audio.play();
  }

  pause(){
  this.setState({ play: false, pause: true });
    this.audio.pause();
  }

  render() {

  return (
    <div>
      <button onClick={this.play}>Play</button>
      <button onClick={this.pause}>Pause</button>
    </div>
    );
  }
}

export default Music
</code>```

This is the code that I am using to play the sound with url (this.url) in my react app. When I press the play button, it gives me an error

Uncaught TypeError: Cannot read property 'setState' of undefined

I am not sure why this is happpening since I don't see any undefined states. A;; states have been declared.

I am new to react so I might be missing something very important.

Please help!

答:
ES6 class properties syntax

```<code>class Music extends React.Component {
  state = {
    play: false
  }
  audio = new Audio(this.props.url)

  componentDidMount() {
    audio.addEventListener('ended', () => this.setState({ play: false }));
  }

  componentWillUnmount() {
    audio.removeEventListener('ended', () => this.setState({ play: false }));
  }

  togglePlay = () => {
    this.setState({ play: !this.state.play }, () => {
      this.state.play ? this.audio.play() : this.audio.pause();
    });
  }

  render() {
    return (
      <div>
        <button onClick={this.togglePlay}>{this.state.play ? 'Pause' : 'Play'}</button>
      </div>
    );
  }
}

export default Music;
</code>```

Hooks version (React 16.8+):

import React, { useState, useEffect } from "react";

const useAudio = url => {
  const [audio] = useState(new Audio(url));
  const [playing, setPlaying] = useState(false);

  const toggle = () => setPlaying(!playing);

  useEffect(() => {
      playing ? audio.play() : audio.pause();
    },
    [playing]
  );

  useEffect(() => {
    audio.addEventListener('ended', () => setPlaying(false));
    return () => {
      audio.removeEventListener('ended', () => setPlaying(false));
    };
  }, []);

  return [playing, toggle];
};

const Player = ({ url }) => {
  const [playing, toggle] = useAudio(url);

  return (

      <button onClick={toggle}>{playing ? "Pause" : "Play"}</button>

  );
};

export default Player;
```
<p><strong>Update 03/16/2020: Multiple concurrent players</strong></p>
<p>In response to @Cold_Class's comment:</p>
<blockquote>
<p>Unfortunately if I use multiple of these components the music from the other components doesn't stop playing whenever I start another component playing - any suggestions on an easy solution for this problem?</p>
</blockquote>
<p>Unfortunately, there is no straightforward solution using the exact codebase we used to implement a single <code>Player</code> component. The reason is that you somehow have to hoist up single player states to a <code>MultiPlayer</code> parent component in order for the <code>toggle</code> function to be able to pause other Players than the one you directly interacted with.</p>
<p>One solution is to modify the hook itself to manage multiple audio sources concurrently. Here is an example implementation:</p>
<pre class="lang-js prettyprint-override"><code>import React, { useState, useEffect } from 'react'

const useMultiAudio = urls => {
  const [sources] = useState(
    urls.map(url => {
      return {
        url,
        audio: new Audio(url),
      }
    }),
  )

  const [players, setPlayers] = useState(
    urls.map(url => {
      return {
        url,
        playing: false,
      }
    }),
  )

  const toggle = targetIndex => () => {
    const newPlayers = [...players]
    const currentIndex = players.findIndex(p => p.playing === true)
    if (currentIndex !== -1 && currentIndex !== targetIndex) {
      newPlayers[currentIndex].playing = false
      newPlayers[targetIndex].playing = true
    } else if (currentIndex !== -1) {
      newPlayers[targetIndex].playing = false
    } else {
      newPlayers[targetIndex].playing = true
    }
    setPlayers(newPlayers)
  }

  useEffect(() => {
    sources.forEach((source, i) => {
      players[i].playing ? source.audio.play() : source.audio.pause()
    })
  }, [sources, players])

  useEffect(() => {
    sources.forEach((source, i) => {
      source.audio.addEventListener('ended', () => {
        const newPlayers = [...players]
        newPlayers[i].playing = false
        setPlayers(newPlayers)
      })
    })
    return () => {
      sources.forEach((source, i) => {
        source.audio.removeEventListener('ended', () => {
          const newPlayers = [...players]
          newPlayers[i].playing = false
          setPlayers(newPlayers)
        })
      })
    }
  }, [])

  return [players, toggle]
}

const MultiPlayer = ({ urls }) => {
  const [players, toggle] = useMultiAudio(urls)

  return (
    <div>
      {players.map((player, i) => (
        <Player key={i} player={player} toggle={toggle(i)} />
      ))}
    </div>
  )
}

const Player = ({ player, toggle }) => (
  <div>
    <p>Stream URL: {player.url}</p>
    <button onClick={toggle}>{player.playing ? 'Pause' : 'Play'}</button>
  </div>
)

export default MultiPlayer
</code>```

Example App.js using the MultiPlayer component:

import React from 'react'
import './App.css'
import MultiPlayer from './MultiPlayer'

function App() {
  return (

      <MultiPlayer
        urls={[
          'https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3',
          'https://www.soundhelix.com/examples/mp3/SoundHelix-Song-2.mp3',
          'https://www.soundhelix.com/examples/mp3/SoundHelix-Song-3.mp3',
        ]}
      />

  )
}

export default App
```

The idea is to manage 2 parallel arrays:

your audio sources (built from the urls props you pass to the parent component ; the urls props is an array of strings (your MP3 URLs))

an array tracking the state of each player

The toggle method updates the player state array based on the following logic:

if there is a player currently active (i.e. audio is playing) and this active player is not the player targeted by the toggle method, revert that player's playing state to false, and set the targeted player's playing state to true [you clicked on 'play' while another audio stream was already playing]

if the player currently active is the player targeted by the toggle method, simply revert the targeted player's playing state to false [you clicked on 'pause']

if there is no player currently active, simply set the targeted player's state to true [you clicked on 'play' while no audio stream was currently playing]

Note that the toggle method is curried to accept the source player's index (i.e. the index of the child component where the corresponding button was clicked).

Actual audio object control happens in useEffect as in the original hook, but is slightly more complex as we have to iterate through the entire array of audio objects with every update.

Similarly, event listeners for audio stream 'ended' events are handled in a second useEffect as in the original hook, but updated to deal with an array of audio objects rather than a single such object.

Finally, the new hook is called from the parent MultiPlayer component (holding multiple players), which then maps to individual Players using (a) an object that contains the player's current state and its source streaming URL and (b) the toggle method curried with the player's index.

CodeSandbox demo

ContentLicense: CC BY-SA 4.0

Title: Playing sound in React.js

Body:
import React, { Component } from 'react'
import { Button, Input, Icon,Dropdown,Card} from 'semantic-ui-react'
import { Link } from 'react-router-dom'
import $ from 'jquery'
import styles from './Home.scss'
import Modal from './Modal.jsx'
import MakeChannelModal from './MakeChannelModal.jsx'

class Music extends React.Component {
    constructor(props) {
    super(props);
    this.state = {

      play: false,
      pause: true

    };

    this.url = "http://streaming.tdiradio.com:8000/house.mp3";
    this.audio = new Audio(this.url);

  }

  play(){
    this.setState({
      play: true,
      pause: false
    });
    console.log(this.audio);
    this.audio.play();
  }

  pause(){
  this.setState({ play: false, pause: true });
    this.audio.pause();
  }

  render() {

  return (

      <button onClick={this.play}>Play</button>
      <button onClick={this.pause}>Pause</button>

    );
  }
}

export default Music

This is the code that I am using to play the sound with url (this.url) in my react app. When I press the play button, it gives me an error

Uncaught TypeError: Cannot read property 'setState' of undefined

I am not sure why this is happpening since I don't see any undefined states. A;; states have been declared.

I am new to react so I might be missing something very important.

Please help!

Body:
ES6 class properties syntax

class Music extends React.Component {
  state = {
    play: false
  }
  audio = new Audio(this.props.url)

  componentDidMount() {
    audio.addEventListener('ended', () => this.setState({ play: false }));
  }

  componentWillUnmount() {
    audio.removeEventListener('ended', () => this.setState({ play: false }));
  }

  togglePlay = () => {
    this.setState({ play: !this.state.play }, () => {
      this.state.play ? this.audio.play() : this.audio.pause();
    });
  }

  render() {
    return (
      <div>
        <button onClick={this.togglePlay}>{this.state.play ? 'Pause' : 'Play'}</button>
      </div>
    );
  }
}

export default Music;

Hooks version (React 16.8+):

import React, { useState, useEffect } from "react";

const useAudio = url => {
  const [audio] = useState(new Audio(url));
  const [playing, setPlaying] = useState(false);

  const toggle = () => setPlaying(!playing);

  useEffect(() => {
      playing ? audio.play() : audio.pause();
    },
    [playing]
  );

  useEffect(() => {
    audio.addEventListener('ended', () => setPlaying(false));
    return () => {
      audio.removeEventListener('ended', () => setPlaying(false));
    };
  }, []);

  return [playing, toggle];
};

const Player = ({ url }) => {
  const [playing, toggle] = useAudio(url);

  return (
    <div>
      <button onClick={toggle}>{playing ? "Pause" : "Play"}</button>
    </div>
  );
};

export default Player;

Update 03/16/2020: Multiple concurrent players

In response to @Cold_Class's comment:

Unfortunately if I use multiple of these components the music from the other components doesn't stop playing whenever I start another component playing - any suggestions on an easy solution for this problem?

Unfortunately, there is no straightforward solution using the exact codebase we used to implement a single Player component. The reason is that you somehow have to hoist up single player states to a MultiPlayer parent component in order for the toggle function to be able to pause other Players than the one you directly interacted with.

One solution is to modify the hook itself to manage multiple audio sources concurrently. Here is an example implementation:

import React, { useState, useEffect } from 'react'

const useMultiAudio = urls => {
  const [sources] = useState(
    urls.map(url => {
      return {
        url,
        audio: new Audio(url),
      }
    }),
  )

  const [players, setPlayers] = useState(
    urls.map(url => {
      return {
        url,
        playing: false,
      }
    }),
  )

  const toggle = targetIndex => () => {
    const newPlayers = [...players]
    const currentIndex = players.findIndex(p => p.playing === true)
    if (currentIndex !== -1 && currentIndex !== targetIndex) {
      newPlayers[currentIndex].playing = false
      newPlayers[targetIndex].playing = true
    } else if (currentIndex !== -1) {
      newPlayers[targetIndex].playing = false
    } else {
      newPlayers[targetIndex].playing = true
    }
    setPlayers(newPlayers)
  }

  useEffect(() => {
    sources.forEach((source, i) => {
      players[i].playing ? source.audio.play() : source.audio.pause()
    })
  }, [sources, players])

  useEffect(() => {
    sources.forEach((source, i) => {
      source.audio.addEventListener('ended', () => {
        const newPlayers = [...players]
        newPlayers[i].playing = false
        setPlayers(newPlayers)
      })
    })
    return () => {
      sources.forEach((source, i) => {
        source.audio.removeEventListener('ended', () => {
          const newPlayers = [...players]
          newPlayers[i].playing = false
          setPlayers(newPlayers)
        })
      })
    }
  }, [])

  return [players, toggle]
}

const MultiPlayer = ({ urls }) => {
  const [players, toggle] = useMultiAudio(urls)

  return (
    <div>
      {players.map((player, i) => (
        <Player key={i} player={player} toggle={toggle(i)} />
      ))}
    </div>
  )
}

const Player = ({ player, toggle }) => (
  <div>
    <p>Stream URL: {player.url}</p>
    <button onClick={toggle}>{player.playing ? 'Pause' : 'Play'}</button>
  </div>
)

export default MultiPlayer

Example App.js using the MultiPlayer component:

import React from 'react'
import './App.css'
import MultiPlayer from './MultiPlayer'

function App() {
  return (
    <div className="App">
      <MultiPlayer
        urls={[
          'https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3',
          'https://www.soundhelix.com/examples/mp3/SoundHelix-Song-2.mp3',
          'https://www.soundhelix.com/examples/mp3/SoundHelix-Song-3.mp3',
        ]}
      />
    </div>
  )
}

export default App

The idea is to manage 2 parallel arrays:

your audio sources (built from the urls props you pass to the parent component ; the urls props is an array of strings (your MP3 URLs))

an array tracking the state of each player

The toggle method updates the player state array based on the following logic:

if there is a player currently active (i.e. audio is playing) and this active player is not the player targeted by the toggle method, revert that player's playing state to false, and set the targeted player's playing state to true [you clicked on 'play' while another audio stream was already playing]

if the player currently active is the player targeted by the toggle method, simply revert the targeted player's playing state to false [you clicked on 'pause']

if there is no player currently active, simply set the targeted player's state to true [you clicked on 'play' while no audio stream was currently playing]

Note that the toggle method is curried to accept the source player's index (i.e. the index of the child component where the corresponding button was clicked).

Actual audio object control happens in useEffect as in the original hook, but is slightly more complex as we have to iterate through the entire array of audio objects with every update.

Similarly, event listeners for audio stream 'ended' events are handled in a second useEffect as in the original hook, but updated to deal with an array of audio objects rather than a single such object.

Finally, the new hook is called from the parent MultiPlayer component (holding multiple players), which then maps to individual Players using (a) an object that contains the player's current state and its source streaming URL and (b) the toggle method curried with the player's index.

CodeSandbox demo


问:
How can I expand a child div to 100% screen width if the container div is smaller?
The parent element of the whole page is a centered div limited to a max-width of 960px. All other elements on the page are children of that parent div. The simplified structure is the following:

```<code><div id="parent">
  <div id="something"></div>
  <div id="wide-div"></div>
  <div id="something-else"></div>
</div>
</code>```

While the parent div shouldn't expand beyond a width of 960px, the div I called "wide-div" here should fill the entire width of the screen. It contains a single image that is wider than the 960px, and it should set a different background color for the entire width of the screen.

I can't easily take that div out of the parent div, it would mess up other parts of my layout and it would make the whole thing rather awkward.

I found a few tricks on how you can achieve this, but none seemed to fit my requirements. My design is responsive, or at least I'm trying to achieve that. The tricks I found relied on knowing the size of the involved elements, which is not fixed in my case.

Is there a way to expand the inner div to the full screen width in a responsive layout?

答:
You can now do this

```<code>.full-width {
    margin-left: calc(50% - 50vw);
    margin-right: calc(50% - 50vw);
}
</code>```

or this

```<code>.full-width {
    width: 100vw;
    position: relative;
    left: 50%;
    right: 50%;
    margin-left: -50vw;
    margin-right: -50vw;
}
</code>```

More details:
https://css-tricks.com/full-width-containers-limited-width-parents/

Body:
The parent element of the whole page is a centered div limited to a max-width of 960px. All other elements on the page are children of that parent div. The simplified structure is the following:

While the parent div shouldn't expand beyond a width of 960px, the div I called "wide-div" here should fill the entire width of the screen. It contains a single image that is wider than the 960px, and it should set a different background color for the entire width of the screen.

I can't easily take that div out of the parent div, it would mess up other parts of my layout and it would make the whole thing rather awkward.

I found a few tricks on how you can achieve this, but none seemed to fit my requirements. My design is responsive, or at least I'm trying to achieve that. The tricks I found relied on knowing the size of the involved elements, which is not fixed in my case.

Is there a way to expand the inner div to the full screen width in a responsive layout?

Body:
You can now do this

.full-width {
    margin-left: calc(50% - 50vw);
    margin-right: calc(50% - 50vw);
}

or this

.full-width {
    width: 100vw;
    position: relative;
    left: 50%;
    right: 50%;
    margin-left: -50vw;
    margin-right: -50vw;
}

More details:
https://css-tricks.com/full-width-containers-limited-width-parents/


答:
Actually regular expressions are not appropriate for this problem, because not every culture uses commas as thousands separators and periods for the radix separator. You should be using toLocaleString. In node, for example:

```<code>> (52342.214).toLocaleString()
'52,342.214'
> (52342.214).toLocaleString('de-DE')
'52.342,214'
> (52342.214).toLocaleString('ar-EG')
'٥٢٬٣٤٢٫٢١٤'
> (5234289877.21).toLocaleString('en-US')
'5,234,289,877.21'
</code>```

This way you don't have to write your own error-prone code and you can localize for different cultures. The work has already been done for you!

You also get the zeros part of your question for free too! Notice:

```<code>> (38209).toLocaleString()
'38,209'
> (38209.0000).toLocaleString()
'38,209'
</code>```

Again, all for free!

Title: Regex replace for commas in the thousands

Body:
Actually regular expressions are not appropriate for this problem, because not every culture uses commas as thousands separators and periods for the radix separator. You should be using toLocaleString. In node, for example:

> (52342.214).toLocaleString()
'52,342.214'
> (52342.214).toLocaleString('de-DE')
'52.342,214'
> (52342.214).toLocaleString('ar-EG')
'٥٢٬٣٤٢٫٢١٤'
> (5234289877.21).toLocaleString('en-US')
'5,234,289,877.21'

This way you don't have to write your own error-prone code and you can localize for different cultures. The work has already been done for you!

You also get the zeros part of your question for free too! Notice:

> (38209).toLocaleString()
'38,209'
> (38209.0000).toLocaleString()
'38,209'

Again, all for free!


问:
Django Timezone Awareness - Data to be stored in UTC

This is my first time developing a timezone aware web app.  I'm using Django 1.11.7.  I have looked through many posts regarding timezones and honestly, I'm starting to feel like I just don't understand the concept of timezones... 0_o

I'm making a booking app with start_time and end_time for each reservation.

I expect the user to be able to enter dates and times as he experiences them in his timezone.  On the other hand, I want these dates and times stored in a postgresql database in UTC format.

If I was choosing to reserve, for example, between 12am and 2am (today), the result in the database should show between 5pm and 7pm (today).

Right?

Django Internationalization settings:

```<code>LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_TZ = True
USE_L10N = True
USE_I18N = True
</code>```

During database creation:

```<code>start_time      TIMESTAMP WITH TIME ZONE NOT NULL,
end_time        TIMESTAMP WITH TIME ZONE NOT NULL
</code>```

Using Django's built in admin page feature, I enter the following information:

But when I look up the results in the database, here's what I get:

```<code>2017-12-05 19:00:00-05 | 2017-12-05 20:59:59-05
</code>```

The stored result changed in the opposite direction of what I was expecting.  I was expecting:

```<code>2017-12-06 05:00:00+05 | 2017-12-06 07:00:00+05
</code>```

If my expectations are wrong and everything is working fine, I would be grateful if you could explain to me how I should interpret the timezone when I read it.

Otherwise, if my expectations where right, I would appreciate any advice.

Thank you.

答:
I had a very similar issue with Hotel bookings. This answer put me on the right track.

https://stackoverflow.com/a/18307581/4660189

The key here is in what you said:

I expect the user to be able to enter dates and times as he experiences them in his timezone.

"his timezone" would need to be handled via a middleware. So that each user can be assigned a timezone, and thus the system would handle all times/dates for this user accordingly.

This should get you going. Happy coding and welcome to the mind bending reality of timezones.

Body:
This is my first time developing a timezone aware web app.  I'm using Django 1.11.7.  I have looked through many posts regarding timezones and honestly, I'm starting to feel like I just don't understand the concept of timezones... 0_o

I'm making a booking app with start_time and end_time for each reservation.

I expect the user to be able to enter dates and times as he experiences them in his timezone.  On the other hand, I want these dates and times stored in a postgresql database in UTC format.

If I was choosing to reserve, for example, between 12am and 2am (today), the result in the database should show between 5pm and 7pm (today).

Right?

Django Internationalization settings:

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_TZ = True
USE_L10N = True
USE_I18N = True

During database creation:

start_time      TIMESTAMP WITH TIME ZONE NOT NULL,
end_time        TIMESTAMP WITH TIME ZONE NOT NULL

Using Django's built in admin page feature, I enter the following information:

But when I look up the results in the database, here's what I get:

2017-12-05 19:00:00-05 | 2017-12-05 20:59:59-05

The stored result changed in the opposite direction of what I was expecting.  I was expecting:

2017-12-06 05:00:00+05 | 2017-12-06 07:00:00+05

If my expectations are wrong and everything is working fine, I would be grateful if you could explain to me how I should interpret the timezone when I read it.

Otherwise, if my expectations where right, I would appreciate any advice.

Thank you.


问:
Cookie based Redirection using Javascript

I'm attempting to create a redirect based on a cookie existence. So when a user connects to my website jonathanstevens.org for the first time, they are redirected to jonathanstevens.org/landing

Code parts:

```<code><script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
</code>```

Global.js

function create_cookie(name, value, days) {
    var expires = "";
    if (days) {
        var date = new Date();
        date.setTime( date.getTime() + (days*24*60*60*1000) );
        expires = "; expires=" + date.toGMTString();
    }
    document.cookie = name + "=" + value + expires + "; path=/";
}

function get_cookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) === ' ') {
            c = c.substring(1, c.length);
        }
        if (c.indexOf(nameEQ) === 0) {
            return c.substring(nameEQ.length, c.length);
        }
    }
    return null;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></code>```

Index.html

```
</div>
</div>
</p>

<p>landing.html
<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- Adds second Visit cookie -->
<script>
 jQuery(document).ready(function($) {
    // Create cookie so that the user is no longer redirected
    create_cookie('secondvisit', 'true', 30);
 });
</script></code>```

The expected result was it to check for a cookie, then forward me to my landing page if it wasn't defined. Any ideas on what I've done wrong?

答:
You should compare with null instead of undefined as you are returning null from the function get_cookie

Index.html

```<code><!-- redirect to landing page -->
<script>
  // Redirect to landing page if 'form_submitted' cookie does not exist
  if (get_cookie('secondvisit') === null) {
    window.location.href = "landing.html";
  }
</script>
</code>```

Apart from this you should use this library really good one an easy to work with see below

Create a cookie, valid across the entire site:

```<code>Cookies.set('name', 'value');
</code>```

Create a cookie that expires 7 days from now, valid across the entire site:

```<code>Cookies.set('name', 'value', { expires: 7 });
</code>```

Create an expiring cookie, valid to the path of the current page:

```<code>Cookies.set('name', 'value', { expires: 7, path: '' });
</code>```

Read cookie:

```<code>Cookies.get('name'); // => 'value'
Cookies.get('nothing'); // => undefined
</code>```

Read all visible cookies:

```<code>Cookies.get(); // => { name: 'value' }
</code>```

Delete cookie:

```<code>Cookies.remove('name');
</code>```

Delete a cookie valid to the path of the current page:

```<code>Cookies.set('name', 'value', { path: '' });
Cookies.remove('name'); // fail!
Cookies.remove('name', { path: '' }); // removed!
</code>```

EDIT

A converted version of your code using js.cookie library will look like following.

(Note: i have tested this code and it works correctly, make sure you are including the library correctly and there are no errors on the console.)

Index.html

```<code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/js-cookie@2/src/js.cookie.min.js"></script>
<!-- redirect to landing page -->
<script>
    $(document).ready(function () {
        if (typeof Cookies.get('secondvisit') === 'undefined') {
            window.location.href = "landing.html";
        }
    })
    // Redirect to landing page if 'form_submitted' cookie does not exist
</script>
</code>```

landing.html

```<code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/js-cookie@2/src/js.cookie.min.js"></script>
<!-- Adds second Visit cookie -->
<script>
    jQuery(document).ready(function () {
        // Create cookie so that the user is no longer redirected
        var a = Cookies.set('secondvisit', 'true', {
            expires: 7
        });
    });
</script>
</code>```

Body:
I'm attempting to create a redirect based on a cookie existence. So when a user connects to my website jonathanstevens.org for the first time, they are redirected to jonathanstevens.org/landing

Code parts:

Global.js

function create_cookie(name, value, days) {
    var expires = "";
    if (days) {
        var date = new Date();
        date.setTime( date.getTime() + (days*24*60*60*1000) );
        expires = "; expires=" + date.toGMTString();
    }
    document.cookie = name + "=" + value + expires + "; path=/";
}

function get_cookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) === ' ') {
            c = c.substring(1, c.length);
        }
        if (c.indexOf(nameEQ) === 0) {
            return c.substring(nameEQ.length, c.length);
        }
    }
    return null;
}

Index.html

landing.html

The expected result was it to check for a cookie, then forward me to my landing page if it wasn't defined. Any ideas on what I've done wrong?

Body:
You should compare with null instead of undefined as you are returning null from the function get_cookie

Index.html

<!-- redirect to landing page -->
<script>
  // Redirect to landing page if 'form_submitted' cookie does not exist
  if (get_cookie('secondvisit') === null) {
    window.location.href = "landing.html";
  }
</script>

Apart from this you should use this library really good one an easy to work with see below

Create a cookie, valid across the entire site:

Cookies.set('name', 'value');

Create a cookie that expires 7 days from now, valid across the entire site:

Cookies.set('name', 'value', { expires: 7 });

Create an expiring cookie, valid to the path of the current page:

Cookies.set('name', 'value', { expires: 7, path: '' });

Read cookie:

Cookies.get('name'); // => 'value'
Cookies.get('nothing'); // => undefined

Read all visible cookies:

Cookies.get(); // => { name: 'value' }

Delete cookie:

Cookies.remove('name');

Delete a cookie valid to the path of the current page:

Cookies.set('name', 'value', { path: '' });
Cookies.remove('name'); // fail!
Cookies.remove('name', { path: '' }); // removed!

EDIT

A converted version of your code using js.cookie library will look like following.

(Note: i have tested this code and it works correctly, make sure you are including the library correctly and there are no errors on the console.)

Index.html

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/js-cookie@2/src/js.cookie.min.js"></script>
<!-- redirect to landing page -->
<script>
    $(document).ready(function () {
        if (typeof Cookies.get('secondvisit') === 'undefined') {
            window.location.href = "landing.html";
        }
    })
    // Redirect to landing page if 'form_submitted' cookie does not exist
</script>

landing.html

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/js-cookie@2/src/js.cookie.min.js"></script>
<!-- Adds second Visit cookie -->
<script>
    jQuery(document).ready(function () {
        // Create cookie so that the user is no longer redirected
        var a = Cookies.set('secondvisit', 'true', {
            expires: 7
        });
    });
</script>


问:
Execution failed for task ':compileJava'. > invalid source release: 1.7
I am using :

gradle-2.3

javac -version = 1.7

jre = 1.7

regedit shows it is pointing to 1.7.

But I am still getting below error

Execution failed for task ':compileJava'. > invalid source release: 1.7

Please let me know how to fix it.

答:
to check if the $JAVA_HOME is really to point the default java
# echo $JAVA_HOME
/usr/lib/jvm/java-1.7.0-openjdk
# java -version
openjdk version "1.8.0_151"
if misaligned like above, to modify $JAVA_HOME in the /etc/profile (or alternatively the .profile/.bashprofile/ in your user's home directory)
let point to JAVA_HOME=/usr/lib/jvm/java-1.8.0-openjdk
BTW: solved at Centos7 to fix Invalid release 1.8


问:
Empty __init__ list
```<code>class rand:

    def __init__(self):
        self.c = []

c = rand()

len(c)
</code>```

I am trying to get an empty list in init.

So, what I am expecting from the code above is this: len(c) = 0

TypeError: object of type 'rand' has no len()
But I keep getting the error above. How do I get the result above?

答: The global variable c and its attribute of the same name are two different objects. You want len(c.c), not len(c).

Title: Empty __init__ list

Body:
class rand:

    def __init__(self):
        self.c = []

c = rand()

len(c)

I am trying to get an empty list in init.

So, what I am expecting from the code above is this: len(c) = 0

TypeError: object of type 'rand' has no len()
But I keep getting the error above. How do I get the result above?


问:
Trouble removing hidden parts of a string
I'm trying to use a scraped string with BeautifulSoup in a simple calculation. The interpreter gives a base 10 error, indicating that there's hidden characters in the string.

This turned out to be true, because the console outputs the raw string including hidden data as:

2.177
['\n\n2.177']
```

2.177 is the number I'm trying to work with here. ['\n\n2.177'] is a hidden part of the string.  Since it won't cast to int because of the hidden values however I can't make any calculations on it.

I've looked up a few ways to remove hidden characters from strings but so far stackoverflow only seems to have answers regarding removing special hidden characters.

Mine are sadly not special. Does anyone know how to remove this part of the string?

答:
Based on the clarification, it looks like the contents of the string are "\n\n2.177", i.e. with two leading newline characters. In this case, the issue is not so much with the newlines as the fact that 2.177 is indeed not a valid representation of an int. Both int("\n\n2.177") and int("2.177") give ValueError: invalid literal for int() with base 10: '2.177'.

To answer your direct question, you can strip leading and trailing whitespace with the strip method on strings, e.g. vacancy_amount.strip().

Perhaps instead you intend to get a floating-point number out, in which case float(vacancy_amount) will give you 2.177. If you want to further convert this to an integer, you can try int(float(vacancy_amount)) to give 2.

Body:
I'm trying to use a scraped string with BeautifulSoup in a simple calculation. The interpreter gives a base 10 error, indicating that there's hidden characters in the string.

This turned out to be true, because the console outputs the raw string including hidden data as:

2.177
['\n\n2.177']

2.177 is the number I'm trying to work with here. ['\n\n2.177'] is a hidden part of the string.  Since it won't cast to int because of the hidden values however I can't make any calculations on it.

I've looked up a few ways to remove hidden characters from strings but so far stackoverflow only seems to have answers regarding removing special hidden characters.

Mine are sadly not special. Does anyone know how to remove this part of the string?


答:
You can use the builtin __len__ method:

```<code>class rand:
   def __init__(self):
      self.c = []
   def __len__(self):
      return len(self.c)

c = rand()
print(len(c))
</code>```

Output:

```<code>0
</code>```

Title: Empty __init__ list

Body:
You can use the builtin __len__ method:

class rand:
   def __init__(self):
      self.c = []
   def __len__(self):
      return len(self.c)

c = rand()
print(len(c))

Output:

0


问:
(Java) Trying to format the layout of multiple JTables with other elements in a JPanel
I've been working on a Pokemon-themed quiz game in Java (modeled after Sporcle, if you're familiar). Pretty much everything works how I want it to, except for the layout of the different components of the program.

I've never been very good with the different layout managers, and I don't know how to get them to do what I need.

Here's what the window looks like right now:

Now, I'll play around with font sizes later, but the tables themselves look exactly how I want them to. The problem is, I want them to be under the text fields and buttons and stuff. Here's the portion of the code where I add all the components to my JPanel:

```<code>    panel.add(label,FlowLayout.LEFT); //adding the "big question text"
    panel.add(answerfield); //adding the JTextField
    panel.add(correctAnswerTracker); //adding the "x / 151" text
    for(int x = sPanes.length-1; x >=0; x--) //as you keep adding to left, it gets pushed over, so doing it backwards results in the correct order
    panel.add(sPanes[x],FlowLayout.LEFT);
    //each table is in a scrollPane, and all my scrollPanes are in the array sPanes, so I'm looping through that to add the tables
    panel.add(startStopButton); //button that says "Start"
    panel.add(exit); //button that says "Exit
    panel.add(timer); //the timer
</code>```

As you can see, the statements to add the text field, and correct answer tracker are all written before the add statement for the tables, and yet the tables are at the top. Additionally, there's the issue of my tables in that loop being added in the backwards order, so I had to reverse the direction of the loop iterations to get the tables to appear in the correct order. I've tried using stuff like setLocation and setBounds to get my components more where I want them, but nothing happened. Also, everything just appears in a row below the tables (and I know that's what FlowLayout does), but how would I go about customizing exactly where things appear?

答: Wrap a panel with BorderLayout around ones with FlowLayout. Put all the content that should be above the tables in a panel and add it with BorderLayout.NORTH. Put all the content that should be below the tables in another panel and add it with BorderLayout.SOUTH. Then put the tables in their own panel just as your are now, and add it with BorderLayout.CENTER.

Body:
I've been working on a Pokemon-themed quiz game in Java (modeled after Sporcle, if you're familiar). Pretty much everything works how I want it to, except for the layout of the different components of the program.

I've never been very good with the different layout managers, and I don't know how to get them to do what I need.

Here's what the window looks like right now:

Now, I'll play around with font sizes later, but the tables themselves look exactly how I want them to. The problem is, I want them to be under the text fields and buttons and stuff. Here's the portion of the code where I add all the components to my JPanel:

    panel.add(label,FlowLayout.LEFT); //adding the "big question text"
    panel.add(answerfield); //adding the JTextField
    panel.add(correctAnswerTracker); //adding the "x / 151" text
    for(int x = sPanes.length-1; x >=0; x--) //as you keep adding to left, it gets pushed over, so doing it backwards results in the correct order
    panel.add(sPanes[x],FlowLayout.LEFT);
    //each table is in a scrollPane, and all my scrollPanes are in the array sPanes, so I'm looping through that to add the tables
    panel.add(startStopButton); //button that says "Start"
    panel.add(exit); //button that says "Exit
    panel.add(timer); //the timer

As you can see, the statements to add the text field, and correct answer tracker are all written before the add statement for the tables, and yet the tables are at the top. Additionally, there's the issue of my tables in that loop being added in the backwards order, so I had to reverse the direction of the loop iterations to get the tables to appear in the correct order. I've tried using stuff like setLocation and setBounds to get my components more where I want them, but nothing happened. Also, everything just appears in a row below the tables (and I know that's what FlowLayout does), but how would I go about customizing exactly where things appear?


问:
PHP flushing output as soon as you call echo
I thought flush(); would work, at least from what Google/Stackoverflow tell me, but on my Windows WAMP (Windows, Apache, MySQL, PHP) system it doesn't work.

Is there some PHP setting I have to set to make flush() work?

Here's my code:

```<code><?php
echo "Fun";

flush();

sleep(5);

echo "<br>Mo";
?>
</code>```

The code just outputs all together when the script is done executing (after 5 seconds).. I don't want this, I want 'Fun' to show up right away, and then after 5 seconds 'Mo'.

I've tried other combinations of flush like ob_end_flush(); or ob_implicit_flush(true); but nothing is working. Any ideas?

答:
If the problem persists, although you explicitly set

```<code>implicit_flush = yes
</code>```

in your php.ini, you might also want to set

```<code>output_buffering = off
</code>```

which did the trick in my case (after pulling my hair for 4+hrs)

Body:
I thought flush(); would work, at least from what Google/Stackoverflow tell me, but on my Windows WAMP (Windows, Apache, MySQL, PHP) system it doesn't work.

Is there some PHP setting I have to set to make flush() work?

Here's my code:

<?php
echo "Fun";

flush();

sleep(5);

echo "
Mo";
?>

The code just outputs all together when the script is done executing (after 5 seconds).. I don't want this, I want 'Fun' to show up right away, and then after 5 seconds 'Mo'.

I've tried other combinations of flush like ob_end_flush(); or ob_implicit_flush(true); but nothing is working. Any ideas?

Body:
If the problem persists, although you explicitly set

implicit_flush = yes

in your php.ini, you might also want to set

output_buffering = off

which did the trick in my case (after pulling my hair for 4+hrs)


问:
Error: [$parse:syntax] when passing values as parameter in angular controller method

I get an error in my developer console as such:

```<code>Error: [$parse:syntax] http://errors.angularjs.org/1.6.5/$parse/syntax?p0=%7B&p1=invalid%20key&p2=43&p3=GetTimelineByUserIdAndProjectId(u.UserId%2C%7B%7BselectedProject.Id%7D%7D)&p4=%7BselectedProject.Id%7D%7D)
</code>```

angular

```<code>$scope.GetTimelineByUserIdAndProjectId = function (userId, projectId) {
   alert(userId +"-"+projectId);
}
</code>```

HTML

```<code><div class="active tab-pane" id="view_projects">
<div>
    <form class="form-inline">

        <select ng-model="selectedProject" class="selectpicker" data-live-search="true"
                ng-options="s.Description for s in allProjects track by s.Id"
                ng-change="getProjectsByUserId(selectedProject.Id)"
                select-picker></select>

        <select ng-model="selectedDeveloper" class="selectpicker" data-live-search="true" ng-options="u.ID as u.FullName for u in allUsers" select-picker></select>
    </form>
</div>
<br/>
<div >
    <div class="panel panel-default" style="width:25%" ng-show="showUserTable">
        <div class="panel-body">
            <table class="table table-bordered table-hover">
                <thead>
                    <tr>
                        <th>Developers for {{selectedProject.Description}}</th>
                    </tr>
                </thead>
                <tbody>
                    <tr ng-repeat="u in usersByProjectId">
                        <td ng-click="GetTimelineByUserIdAndProjectId(u.UserId,{{selectedProject.Id}})"><a href="javascript:void(0);"> {{u.Developer}}</a></td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
</div>
</code>```

I should be able to get the "alert" when I click on the list. If I just get the u.userId I am actually able to get the alert with the value but when I add the {{selectedProject.Id}} that's when I get the error.

答:
Inside ng-click you don't need to put interpolation because you are already entering expression. We give {{interpolation}} to write expressions in HTML.
In your case ng-click is already an expression so it you don't need that {{}} there in ng-click. you give
GetTimelineByUserIdAndProjectId(u.UserId,selectedProject.Id)

Body:
I get an error in my developer console as such:

Error: [$parse:syntax] http://errors.angularjs.org/1.6.5/$parse/syntax?p0=%7B&p1=invalid%20key&p2=43&p3=GetTimelineByUserIdAndProjectId(u.UserId%2C%7B%7BselectedProject.Id%7D%7D)&p4=%7BselectedProject.Id%7D%7D)

angular

$scope.GetTimelineByUserIdAndProjectId = function (userId, projectId) {
   alert(userId +"-"+projectId);
}

HTML

    <form class="form-inline">

        <select ng-model="selectedProject" class="selectpicker" data-live-search="true"
                ng-options="s.Description for s in allProjects track by s.Id"
                ng-change="getProjectsByUserId(selectedProject.Id)"
                select-picker></select>

        <select ng-model="selectedDeveloper" class="selectpicker" data-live-search="true" ng-options="u.ID as u.FullName for u in allUsers" select-picker></select>
    </form>

                        Developers for {{selectedProject.Description}}

                         {{u.Developer}}

I should be able to get the "alert" when I click on the list. If I just get the u.userId I am actually able to get the alert with the value but when I add the {{selectedProject.Id}} that's when I get the error.


问:
Specific information on how to insert into html table
I am trying to use the results of a database and display them in an HTML table. I've searched around but can't find a specific answer for my situation as I am new to PHP and I had to copy this code from another source because I was unable to get it to work on my own. Please help.

```<code><?php $server = "127.0.0.1";
$user = "admin";
$pass = "password";
$dbname = "hysteryalelogs";
// Create connection in mysqli
$connection = new mysqli($server, $user, $pass, $dbname);
//Check connection in mysqli
if($connection->connect_error){
    die("Error on connection:" .$connection->connect_error);
}
//Display the informaion
$sql = "SELECT * FROM logs";
$res = $connection->query($sql);
if($res->num_rows > 0){
    while($row = $res->fetch_assoc()){
    echo "Sales Number: ". $row["Sales_Number"]. "<br/>";
    echo "Quantity: ". $row["Quantity"]. "<br/>";
    echo "Due Date: ". $row["Due_Date"]. "<br/>";
    echo "Burnished Housing: ". $row["Burnished"]. "<br/>";
    echo "Greased Bearings: ". $row["Grease"]. "<br/>";
    echo "Air Cleaned: ". $row["Air"]. "<br/>";
    echo "SS Screw: ". $row["Screw"]. "<br/>";
    echo "Test Date: ". $row["Test_Date"]. "<br/>";
    echo "Pass: ". $row["Pass"]. "<br/>";
    echo "Fail: ". $row["Fail"]. "<br/>";
    echo "Tester: ". $row["Tester"]. "<br/>";
    echo "Final Check: ". $row["Final_Check"]. "<br/>";
    echo "Green Dot: ". $row["Green_Dot"]. "<br/>";
    echo "Green Dot Check: ". $row["Green_Dot_Check"]. "<br/>";
    echo "Ship Date: ". $row["Ship_Date"]. "<br/>";
    echo "Serial Number: ". $row["Serial_Number"]. "<br><br><hr><br/>";
  }
  } else {
echo "No Record Found!";
}
$connection->close();
?>
</code>```

(clarification) The code works. I Just don't know how to format the table for it to display inside.

答:
Hi :) Hope this helps :)</p>

```<code><?php
$server = "127.0.0.1";
$user = "admin";
$pass = "password";
$dbname = "hysteryalelogs";
// Create connection in mysqli
$connection = new mysqli($server, $user, $pass, $dbname);
//Check connection in mysqli
if($connection->connect_error){
die("Error on connection:" .$connection->connect_error);
}
//Display the informaion
$sql = "SELECT * FROM logs";
$res = $connection->query($sql);
if($res->num_rows > 0){
echo "<table border='3px' cellpadding='5px' cellspacing='5px' align='center' bgcolor='skyblue' ";
echo "<tr>";
echo "<td><center><strong>Sales Number</strong></center></td>";
echo "<td><center><strong>Quantity</strong></center></td>";
echo "<td><center><strong>Due Date</strong></center></td>";
echo "<td><center><strong>Burnished Housing</strong></center></td>";
echo "<td><center><strong>Greased Bearings</strong></center></td>";
echo "<td><center><strong>Air Cleaned</strong></center></td>";
echo "<td><center><strong>SS Screw</strong></center></td>";
echo "<td><center><strong>Test Date</strong></center></td>";
echo "<td><center><strong>Pass</strong></center></td>";
echo "<td><center><strong>Fail</strong></center></td>";
echo "<td><center><strong>Tester</strong></center></td>";
echo "<td><center><strong>Final Check</strong></center></td>";
echo "<td><center><strong>Green Dot</strong></center></td>";
echo "<td><center><strong>Green Dot Check</strong></center></td>";
echo "<td><center><strong>Ship Date</strong></center></td>";
echo "<td><center><strong>Serial Number</strong></center></td>";
echo "</tr>";
while($row = $res->fetch_assoc()){
echo "<tr>";
echo "<td>"."<center>"."<i>".$row["Sales_Number"]."</i>"."</center>"."</td>";
echo "<td>"."<center>"."<i>".$row["Quantity"]."</i>"."</center>"."</td>";
echo "<td>"."<center>"."<i>".$row["Due_Date"]."</i>"."</center>"."</td>";
echo "<td>"."<center>"."<i>".$row["Burnished"]."</i>"."</center>"."</td>";
echo "<td>"."<center>"."<i>".$row["Grease"]."</i>"."</center>"."</td>";
echo "<td>"."<center>"."<i>".$row["Air"]."</i>"."</center>"."</td>";
echo "<td>"."<center>"."<i>".$row["Screw"]."</i>"."</center>"."</td>";
echo "<td>"."<center>"."<i>".$row["Test_Date"]."</i>"."</center>"."</td>";
echo "<td>"."<center>"."<i>".$row["Pass"]."</i>"."</center>"."</td>";
echo "<td>"."<center>"."<i>".$row["Fail"]."</i>"."</center>"."</td>";
echo "<td>"."<center>"."<i>".$row["Tester"]."</i>"."</center>"."</td>";
echo "<td>"."<center>"."<i>".$row["Final_Check"]."</i>"."</center>"."</td>";
echo "<td>"."<center>"."<i>".$row["Green_Dot"]."</i>"."</center>"."</td>";
echo "<td>"."<center>"."<i>".$row["Green_Dot_Check"]."</i>"."</center>"."</td>";
echo "<td>"."<center>"."<i>".$row["Ship_Date"]."</i>"."</center>"."</td>";
echo "<td>"."<center>"."<i>".$row["Serial_Number"]."</i>"."</center>"."</td>";
echo "</tr>";
}
echo "</table>";
} else {
echo "No Record Found!";
}
$connection->close();
?>
</code>```

Body:
I am trying to use the results of a database and display them in an HTML table. I've searched around but can't find a specific answer for my situation as I am new to PHP and I had to copy this code from another source because I was unable to get it to work on my own. Please help.

<?php $server = "127.0.0.1";
$user = "admin";
$pass = "password";
$dbname = "hysteryalelogs";
// Create connection in mysqli
$connection = new mysqli($server, $user, $pass, $dbname);
//Check connection in mysqli
if($connection->connect_error){
    die("Error on connection:" .$connection->connect_error);
}
//Display the informaion
$sql = "SELECT * FROM logs";
$res = $connection->query($sql);
if($res->num_rows > 0){
    while($row = $res->fetch_assoc()){
    echo "Sales Number: ". $row["Sales_Number"]. "
";
    echo "Quantity: ". $row["Quantity"]. "
";
    echo "Due Date: ". $row["Due_Date"]. "
";
    echo "Burnished Housing: ". $row["Burnished"]. "
";
    echo "Greased Bearings: ". $row["Grease"]. "
";
    echo "Air Cleaned: ". $row["Air"]. "
";
    echo "SS Screw: ". $row["Screw"]. "
";
    echo "Test Date: ". $row["Test_Date"]. "
";
    echo "Pass: ". $row["Pass"]. "
";
    echo "Fail: ". $row["Fail"]. "
";
    echo "Tester: ". $row["Tester"]. "
";
    echo "Final Check: ". $row["Final_Check"]. "
";
    echo "Green Dot: ". $row["Green_Dot"]. "
";
    echo "Green Dot Check: ". $row["Green_Dot_Check"]. "
";
    echo "Ship Date: ". $row["Ship_Date"]. "
";
    echo "Serial Number: ". $row["Serial_Number"]. "

";
  }
  } else {
echo "No Record Found!";
}
$connection->close();
?>

(clarification) The code works. I Just don't know how to format the table for it to display inside.

Body:
Hi :) Hope this helps :)

<?php
$server = "127.0.0.1";
$user = "admin";
$pass = "password";
$dbname = "hysteryalelogs";
// Create connection in mysqli
$connection = new mysqli($server, $user, $pass, $dbname);
//Check connection in mysqli
if($connection->connect_error){
die("Error on connection:" .$connection->connect_error);
}
//Display the informaion
$sql = "SELECT * FROM logs";
$res = $connection->query($sql);
if($res->num_rows > 0){
echo "<table border='3px' cellpadding='5px' cellspacing='5px' align='center' bgcolor='skyblue' ";
echo "<tr>";
echo "<td><center><strong>Sales Number</strong></center></td>";
echo "<td><center><strong>Quantity</strong></center></td>";
echo "<td><center><strong>Due Date</strong></center></td>";
echo "<td><center><strong>Burnished Housing</strong></center></td>";
echo "<td><center><strong>Greased Bearings</strong></center></td>";
echo "<td><center><strong>Air Cleaned</strong></center></td>";
echo "<td><center><strong>SS Screw</strong></center></td>";
echo "<td><center><strong>Test Date</strong></center></td>";
echo "<td><center><strong>Pass</strong></center></td>";
echo "<td><center><strong>Fail</strong></center></td>";
echo "<td><center><strong>Tester</strong></center></td>";
echo "<td><center><strong>Final Check</strong></center></td>";
echo "<td><center><strong>Green Dot</strong></center></td>";
echo "<td><center><strong>Green Dot Check</strong></center></td>";
echo "<td><center><strong>Ship Date</strong></center></td>";
echo "<td><center><strong>Serial Number</strong></center></td>";
echo "</tr>";
while($row = $res->fetch_assoc()){
echo "<tr>";
echo "<td>"."<center>"."<i>".$row["Sales_Number"]."</i>"."</center>"."</td>";
echo "<td>"."<center>"."<i>".$row["Quantity"]."</i>"."</center>"."</td>";
echo "<td>"."<center>"."<i>".$row["Due_Date"]."</i>"."</center>"."</td>";
echo "<td>"."<center>"."<i>".$row["Burnished"]."</i>"."</center>"."</td>";
echo "<td>"."<center>"."<i>".$row["Grease"]."</i>"."</center>"."</td>";
echo "<td>"."<center>"."<i>".$row["Air"]."</i>"."</center>"."</td>";
echo "<td>"."<center>"."<i>".$row["Screw"]."</i>"."</center>"."</td>";
echo "<td>"."<center>"."<i>".$row["Test_Date"]."</i>"."</center>"."</td>";
echo "<td>"."<center>"."<i>".$row["Pass"]."</i>"."</center>"."</td>";
echo "<td>"."<center>"."<i>".$row["Fail"]."</i>"."</center>"."</td>";
echo "<td>"."<center>"."<i>".$row["Tester"]."</i>"."</center>"."</td>";
echo "<td>"."<center>"."<i>".$row["Final_Check"]."</i>"."</center>"."</td>";
echo "<td>"."<center>"."<i>".$row["Green_Dot"]."</i>"."</center>"."</td>";
echo "<td>"."<center>"."<i>".$row["Green_Dot_Check"]."</i>"."</center>"."</td>";
echo "<td>"."<center>"."<i>".$row["Ship_Date"]."</i>"."</center>"."</td>";
echo "<td>"."<center>"."<i>".$row["Serial_Number"]."</i>"."</center>"."</td>";
echo "</tr>";
}
echo "</table>";
} else {
echo "No Record Found!";
}
$connection->close();
?>


问:
Managing a property of the special "this" object at the function block
I got this code in a function.

The first line works.

```<code>    this.learningPlan.learnerType = ['abc']; // this line works
</code>```

but these lines below won't.

```<code>    properyName = 'learningPlan.learnerType';
    this[properyName] = ['abc'];
</code>```

Is there a way to refer to the this so I can pass the properyName value to the function?

I need this functionality so I can keep the function generic and not mention the specific phrase 'learningPlan.learnerType'. Cause then I can do the following:

```<code>function blah(propertyName){
        this[properyName] = ['abc'];
}
</code>```

答:
How does this look:

Edit: Added explanatory comments.

```<code>function T() {
    this.learningPlan = { learnerType : "aaa" };
    this.setVal = function(p, v) {
        // Split the property string into its "parts"
        // thus "learningPlan.learnerType" becomes ["learningPlan","learnerType"]
        var ps = p.split(".");

        // Remove and capture the "last" (right-most) property
        // From ["learningPlan","learnerType"] this would be "learnerType"
        // leaving the array with ["learningPlan"]
        var lastProp = ps.pop();

        // Work "down" the object finding each level object finally returning
        // the property object containing the property you wish to set
        var o = ps.reduce(function(a,e) {
          // This checks that each object["property"] exists and if
          // it doesn't then it creates an empty object so that it can
          // continue traversing down the property hierarchy.
          // Given the property string "learningPlan.learnerType" if the
          // property this.learningPlan didn't exist then attempting to
          // reference this.learningPlan.learnerType would throw an error
          // since learnerType is not a property of undefined. This is, I
          // believe, the error you are experiencing. Using (a[e] || {})
          // ensures that a[e] references something so that traversal
          // can continue.
          a[e] = (a[e] || {});

          // This simply returns the property so that the reduce can keep
          // moving through the array
          return a[e];
        }, this);

        // Finally, we set the value for the last property in our string.
        // The above reduce would walk down 'this' finding/setting each
        // property until it reached the last string we left in our array
        // after the pop and thereby returning a reference to that property
        // into our variable "o". We then use the last property string as a
        // property of "o" to set our value.
        o[lastProp] = v;
    };
}
</code>```

It will allow you to do things like:

```<code>var t = new T();
t.setVal("learningPlan.learnerType", "def");
</code>```

Body:
I got this code in a function.

The first line works.

    this.learningPlan.learnerType = ['abc']; // this line works

but these lines below won't.

    properyName = 'learningPlan.learnerType';
    this[properyName] = ['abc'];

Is there a way to refer to the this so I can pass the properyName value to the function?

I need this functionality so I can keep the function generic and not mention the specific phrase 'learningPlan.learnerType'. Cause then I can do the following:

function blah(propertyName){
        this[properyName] = ['abc'];
}

Body:
How does this look:

Edit: Added explanatory comments.

function T() {
    this.learningPlan = { learnerType : "aaa" };
    this.setVal = function(p, v) {
        // Split the property string into its "parts"
        // thus "learningPlan.learnerType" becomes ["learningPlan","learnerType"]
        var ps = p.split(".");

        // Remove and capture the "last" (right-most) property
        // From ["learningPlan","learnerType"] this would be "learnerType"
        // leaving the array with ["learningPlan"]
        var lastProp = ps.pop();

        // Work "down" the object finding each level object finally returning
        // the property object containing the property you wish to set
        var o = ps.reduce(function(a,e) {
          // This checks that each object["property"] exists and if
          // it doesn't then it creates an empty object so that it can
          // continue traversing down the property hierarchy.
          // Given the property string "learningPlan.learnerType" if the
          // property this.learningPlan didn't exist then attempting to
          // reference this.learningPlan.learnerType would throw an error
          // since learnerType is not a property of undefined. This is, I
          // believe, the error you are experiencing. Using (a[e] || {})
          // ensures that a[e] references something so that traversal
          // can continue.
          a[e] = (a[e] || {});

          // This simply returns the property so that the reduce can keep
          // moving through the array
          return a[e];
        }, this);

        // Finally, we set the value for the last property in our string.
        // The above reduce would walk down 'this' finding/setting each
        // property until it reached the last string we left in our array
        // after the pop and thereby returning a reference to that property
        // into our variable "o". We then use the last property string as a
        // property of "o" to set our value.
        o[lastProp] = v;
    };
}

It will allow you to do things like:

var t = new T();
t.setVal("learningPlan.learnerType", "def");


问:
Alias to record all commands and std output to a file
I am looking to figure out a way to get my documentation done quicker for my project work. One thing that would help me would be to record my history and each commands output to a file. However, I don't want to have this on all the time and I would rather not have it as a toggle option for the risk of forgetting to turn it off and recording a load of junk that I will have to just go and delete later.

The idea I had was to create an alias, lets say 'verbatim', so that I could enter the command as so:

```<code>verbatim <command>
</code>```

And then the alias would remove 'verbatim', take whatever  that was entered and prepend/append it with:

```<code>echo -n \[\$(date)\] >> output_file | echo "<command>" >> output_file | <command> | fee -a output_file | echo " " >> output_file
</code>```

where the output will be:

```<code><timestamp>
<command>
<outputOfTheCommand>
<newLine>
</code>```

could also add comments by

```<code>verbatim #some comment to go in line
</code>```

example:

```<code>verbatim #deploying the production stack upgrade
verbatim <someDeployCommand>
</code>```

This way by typing just one word extra per line I can record everything that happens as I am doing a deployment for example, which can be used to basically do all of my documentation for me since it is saved to a file in order, all I have to do is remove anything that is irrelevant in hindsight. And the fact that all the data is timestamped means it could also speed up RCA if something goes wrong.

Thanks in advance, any and all advice welcome

答:
You should probably just use script, but you could do something like:

```<code>v() { { date; echo "$@"; "$@" | tee /dev/tty; echo; } >> ${OUTPUT-/tmp/output} 2>&1; }
</code>```

or

```<code>v() { { date; echo "$@"; "$@"; echo; } 2>&1 | tee -a ${OUTPUT-/tmp/output}; }
</code>```

(verbatim is too long, so I shortened it to v)

This won't handle comments at all; that would require writing a new parser, since the comment will never be seen by the function.  But you can always echo "# some comment" >> $OUTPUT

Body:
I am looking to figure out a way to get my documentation done quicker for my project work. One thing that would help me would be to record my history and each commands output to a file. However, I don't want to have this on all the time and I would rather not have it as a toggle option for the risk of forgetting to turn it off and recording a load of junk that I will have to just go and delete later.

The idea I had was to create an alias, lets say 'verbatim', so that I could enter the command as so:

verbatim <command>

And then the alias would remove 'verbatim', take whatever  that was entered and prepend/append it with:

echo -n \[\$(date)\] >> output_file | echo "<command>" >> output_file | <command> | fee -a output_file | echo " " >> output_file

where the output will be:

<timestamp>
<command>
<outputOfTheCommand>
<newLine>

could also add comments by

verbatim #some comment to go in line

example:

verbatim #deploying the production stack upgrade
verbatim <someDeployCommand>

This way by typing just one word extra per line I can record everything that happens as I am doing a deployment for example, which can be used to basically do all of my documentation for me since it is saved to a file in order, all I have to do is remove anything that is irrelevant in hindsight. And the fact that all the data is timestamped means it could also speed up RCA if something goes wrong.

Thanks in advance, any and all advice welcome

Body:
You should probably just use script, but you could do something like:

v() { { date; echo "$@"; "$@" | tee /dev/tty; echo; } >> ${OUTPUT-/tmp/output} 2>&1; }

or

v() { { date; echo "$@"; "$@"; echo; } 2>&1 | tee -a ${OUTPUT-/tmp/output}; }

(verbatim is too long, so I shortened it to v)

This won't handle comments at all; that would require writing a new parser, since the comment will never be seen by the function.  But you can always echo "# some comment" >> $OUTPUT


问:
How to convert Numpy NaT values to Pandas datetime values
I need to convert numpy.datetime64('NaT') values to Pandas datetime values. I used Gord Thompson's solution below to convert numpy.datetime64 values.

```<code>def dt64_to_datetime(dt64):
   unix_epoch = np.datetime64(0, 's')
   one_second = np.timedelta64(1, 's')
   seconds_since_epoch = (dt64 - unix_epoch) / one_second
   return datetime.utcfromtimestamp(seconds_since_epoch)
</code>```

Example usage:

```<code>for value in df[col].values: ##Convert each np.datetime64 value in DF column to Pandas datetime
    dt = dt64_to_datetime(value)
</code>```

When the function reaches a np.datetime64('NaT') value, the following error is shown: OSError: [Errno 22] Invalid argument.

What can I do to convert np.datetime64('NaT') values to Python datetime values?

EDIT / UPDATE:

I am trying to convert np.datetime64('NaT') values to Python datetime values because research has shown that this can help me upload the values from DataFrame column into MS Access table. How can I do this?

答:
There doesn't seem to be a datetime.datetime analog for numpy.datetitme64('NaT').
Catch the error and just choose something appropriate. Since the error says the value is too large, return the maximum datetime possible.</p>

```<code>def dt64_to_datetime(dt64):
    unix_epoch = np.datetime64(0, 's')
    one_second = np.timedelta64(1, 's')
    seconds_since_epoch = (dt64 - unix_epoch) / one_second
    #print(seconds_since_epoch)
    try:
        v = datetime.datetime.utcfromtimestamp(seconds_since_epoch)
    except OSError as e:
        #print(e)
        v = datetime.datetime.max
    return v
</code>```

Body:
I need to convert numpy.datetime64('NaT') values to Pandas datetime values. I used Gord Thompson's solution below to convert numpy.datetime64 values.

def dt64_to_datetime(dt64):
   unix_epoch = np.datetime64(0, 's')
   one_second = np.timedelta64(1, 's')
   seconds_since_epoch = (dt64 - unix_epoch) / one_second
   return datetime.utcfromtimestamp(seconds_since_epoch)

Example usage:

for value in df[col].values: ##Convert each np.datetime64 value in DF column to Pandas datetime
    dt = dt64_to_datetime(value)

When the function reaches a np.datetime64('NaT') value, the following error is shown: OSError: [Errno 22] Invalid argument.

What can I do to convert np.datetime64('NaT') values to Python datetime values?

EDIT / UPDATE:

I am trying to convert np.datetime64('NaT') values to Python datetime values because research has shown that this can help me upload the values from DataFrame column into MS Access table. How can I do this?

Body:
There doesn't seem to be a datetime.datetime analog for numpy.datetitme64('NaT').
Catch the error and just choose something appropriate. Since the error says the value is too large, return the maximum datetime possible.

def dt64_to_datetime(dt64):
    unix_epoch = np.datetime64(0, 's')
    one_second = np.timedelta64(1, 's')
    seconds_since_epoch = (dt64 - unix_epoch) / one_second
    #print(seconds_since_epoch)
    try:
        v = datetime.datetime.utcfromtimestamp(seconds_since_epoch)
    except OSError as e:
        #print(e)
        v = datetime.datetime.max
    return v


问:
iPhone SDK: How do I programmatically create squares?
Does anyone know how I can programmatically create a grid of squares. (each square being 10x10) ?

What i'd like to do is to simulate a digital display, so I would need to be able to set the colour of each individual square, after its been defined as well.

I know I could make each individual square in interface builder, but that would be simply impractical with all the required outlets.

Any help is greatly appreciated.

答:
Create a custom view, override drawRect: and call UIRectFill to draw squares.

See this


问:
How to change title of Activity in Android?
I am using

```<code>Window w = getWindow();
w.setTitle("My title");
</code>```

to change title of my current Activity but it does not seem to work.

Can anyone guide me on how to change this?

答:
I'm using Android Studio 3.0.1.

WIth an Activity:

```<code>setTitle("Title Text");
</code>```

Inside a fragment:

```<code>getActivity().setTitle("Title Text");
</code>```

Body:
I am using

Window w = getWindow();
w.setTitle("My title");

to change title of my current Activity but it does not seem to work.

Can anyone guide me on how to change this?

Body:
I'm using Android Studio 3.0.1.

WIth an Activity:

setTitle("Title Text");

Inside a fragment:

getActivity().setTitle("Title Text");


问:
Firebase Auth, acquiring textfield value from different class
I am using Firebase email authentication in my app, I have 2 different view controllers for the sign up process, first view controller asks for the email for firebase and the second view controller asks for the password. How can I set it up for the firebase code?

```<code>if let phoneEmail = phoneEmailTextField.text, let createdpassword = createdPasswordTextField {

            Auth.auth().createUser(withEmail: phoneEmail, password: createdpassword, completion: { (user, error) in
</code>```

I have the textfield "phoneEmailTextField" in the first view controller (class 1) and the textfield "createdPasswordTextField" in the second view controller(class 2). How can I link the textfield "createdPasswordTextField" from the second view controller (class 2) back to the first view controller (class 1) in order to execute the Firebase function?

答: Use segue for passing mail textfield's data from first view controller to the second.Shortly,search how segue,navigation controller pushing works.</p>

Body:
I am using Firebase email authentication in my app, I have 2 different view controllers for the sign up process, first view controller asks for the email for firebase and the second view controller asks for the password. How can I set it up for the firebase code?

if let phoneEmail = phoneEmailTextField.text, let createdpassword = createdPasswordTextField {

            Auth.auth().createUser(withEmail: phoneEmail, password: createdpassword, completion: { (user, error) in

I have the textfield "phoneEmailTextField" in the first view controller (class 1) and the textfield "createdPasswordTextField" in the second view controller(class 2). How can I link the textfield "createdPasswordTextField" from the second view controller (class 2) back to the first view controller (class 1) in order to execute the Firebase function?


问:
How to create a custom style?
I have several View widgets in my axml file they looks like that:

```<code> <View
     android:layout_width="fill_parent"
     android:layout_height="2dp"
     android:layout_marginTop="1dp"
     android:layout_marginBottom="5dp"
     android:background="#c0c0c0" />
</code>```

I don't want to repeat the code so I created styles.xml file in Values folder with the following content:

```<code><resources>
  <style name="HorizontalLine">
       <item name="android:layout_width">fill_parent</item>
       <item name="android:layout_height">2dp</item>
       <item name="android:layout_marginTop">1dp</item>
       <item name="marginBottom">5dp</item>
       <item name="android:background">#c0c0c0</item>
  </style>
</resources>
</code>```

Now I'm trying to reference the style in my Views like that:

```<code><View
     android:style="@style/HorizontalLine"
/>
</code>```

But it doesn't work. I've tried all in internet to create style. Where I'm wrong?

答:
Here is about how to use style in Xamarin.Android

Replace your code with this:

styles.xml:

```<code><resources>
  <style name="HorizontalLine">
       <item name="android:layout_width">fill_parent</item>
       <item name="android:layout_height">2dp</item>
       <item name="android:layout_marginTop">1dp</item>
       <item name="android:layout_marginBottom">5dp</item>
       <item name="android:background">#c0c0c0</item>
  </style>
</resources>
</code>```

<item name="marginBottom">5dp</item> it can not be recognized by the compiler.

layout.xml:

```<code><View
     style="@style/HorizontalLine"
/>
</code>```

Replace android:style= with style=, you can see it in the link.

Title: How to create a custom style?

Body:
I have several View widgets in my axml file they looks like that:

 <View
     android:layout_width="fill_parent"
     android:layout_height="2dp"
     android:layout_marginTop="1dp"
     android:layout_marginBottom="5dp"
     android:background="#c0c0c0" />

I don't want to repeat the code so I created styles.xml file in Values folder with the following content:

<resources>

</resources>

Now I'm trying to reference the style in my Views like that:

<View
     android:style="@style/HorizontalLine"
/>

But it doesn't work. I've tried all in internet to create style. Where I'm wrong?

Body:
Here is about how to use style in Xamarin.Android

Replace your code with this:

styles.xml:

<resources>
  <style name="HorizontalLine">
       <item name="android:layout_width">fill_parent</item>
       <item name="android:layout_height">2dp</item>
       <item name="android:layout_marginTop">1dp</item>
       <item name="android:layout_marginBottom">5dp</item>
       <item name="android:background">#c0c0c0</item>
  </style>
</resources>

<item name="marginBottom">5dp</item> it can not be recognized by the compiler.

layout.xml:

<View
     style="@style/HorizontalLine"
/>

Replace android:style= with style=, you can see it in the link.


问:
failed to connect to mail server in PHP
I have written a small piece of PHP code for sending mail:

```<code>   <?php
    //define the receiver of the email
    $to = 'rohaanthakare@gmail.com';
    //define the subject of the email
    $subject = 'Hishob email';
    //define the message to be sent. Each line should be separated with \n
    $message = "Hello World!\n\nThis is my first mail.";
    //define the headers we want passed. Note that they are separated with \r\n
    $headers = "From: webmaster@example.com\r\nReply-To: webmaster@example.com";
    //send the email
    $mail_sent = mail( $to, $subject, $message, $headers );
    //if the message is sent successfully print "Mail sent". Otherwise print "Mail failed"
    echo $mail_sent ? "Mail sent" : "Mail failed";
    ?>
</code>```

after executing it I got following warning:

Failed to connect to mailserver at "localhost" port 25, verify your "SMTP" and "smtp_port" setting in php.ini or use ini_set() in C:\wamp\www\NewHishob\PhpFiles\send_mail.php on line 11

  Mail failed

I am using a WAMP server and there are two files, INI-DIST and other is INI-RECOMENDED. Which one is important?

I had also gone through php.ini-dist file and for SMTP it contains the following:

```<code>[mail function]
; For Win32 only.
SMTP = localhost
smtp_port = 25

; For Win32 only.
;sendmail_from = me@example.com

; For Unix only.  You may supply arguments as well (default: "sendmail -t -i").
;sendmail_path =
</code>```

Please suggest what I should do? Thanks to all in advance.

答:
Do you have a SMTP server on that host/port combination ? You can check if something is listening there by doing:

```<code>$ telnet localhost 25
</code>```

and seeing if telnet actually connects.

Title: failed to connect to mail server in PHP

Body:
I have written a small piece of PHP code for sending mail:

   <?php
    //define the receiver of the email
    $to = 'rohaanthakare@gmail.com';
    //define the subject of the email
    $subject = 'Hishob email';
    //define the message to be sent. Each line should be separated with \n
    $message = "Hello World!\n\nThis is my first mail.";
    //define the headers we want passed. Note that they are separated with \r\n
    $headers = "From: webmaster@example.com\r\nReply-To: webmaster@example.com";
    //send the email
    $mail_sent = mail( $to, $subject, $message, $headers );
    //if the message is sent successfully print "Mail sent". Otherwise print "Mail failed"
    echo $mail_sent ? "Mail sent" : "Mail failed";
    ?>

after executing it I got following warning:

Failed to connect to mailserver at "localhost" port 25, verify your "SMTP" and "smtp_port" setting in php.ini or use ini_set() in C:\wamp\www\NewHishob\PhpFiles\send_mail.php on line 11

  Mail failed

I am using a WAMP server and there are two files, INI-DIST and other is INI-RECOMENDED. Which one is important?

I had also gone through php.ini-dist file and for SMTP it contains the following:

[mail function]
; For Win32 only.
SMTP = localhost
smtp_port = 25

; For Win32 only.
;sendmail_from = me@example.com

; For Unix only.  You may supply arguments as well (default: "sendmail -t -i").
;sendmail_path =

Please suggest what I should do? Thanks to all in advance.

Body:
Do you have a SMTP server on that host/port combination ? You can check if something is listening there by doing:

$ telnet localhost 25

and seeing if telnet actually connects.