问:
Display: inline-block will not work with PHP (screenshots included)
I'm currently creating an e-commerce site. I'm using PHP/SQL to display information on the product.

I have set a display: inline-block in the CSS and it seems to work fine when there is no PHP. However once I put in the php, it seems like it becomes a display: block element instead.

Here is my code for the html/php:

```<code><section class="products">

    <div class="sectionintro introcontainer">
     <h1>Gucci</h1>
     <p>Established in Florence in 1921, Gucci has evolved from a manufacturer of quality leather accessories into one of the world’s premiere luxury brands. A legacy of glamour, elegance, and modernity underpin its status as a bastion of essential Italian fashion. Alessandro Michele, named creative director in 2015, has ushered in a uniquely contemporary vision of luxury with his eclectic, bohemian, and highly romantic designs. </p>
    </div>

        <article>

        <?php

 $query = "SELECT * FROM products WHERE product_brand = 'Gucci' ";

 $select_all_products = mysqli_query($connection, $query);

 while($row = mysqli_fetch_assoc($select_all_products)){

    $product_id = $row['product_id'];
    $product_name = $row['product_name'];
    $product_type = $row['product_type'];
    $product_image_front = $row['product_image_front'];
    $product_image_back = $row['product_image_back'];
    $product_image_side = $row['product_image_side'];
    $product_image_full = $row['product_image_full'];
    $product_description = $row['product_description'];
    $product_price = $row['product_price'];
    $product_brand = $row['product_brand'];

?>

        <img  src="productImages/<?php echo $product_image_front ?>" >
         <h2><?php echo $product_brand; ?></h2>
          <h3><?php echo $product_name; ?></h3>
          <p><?php echo $product_price; ?></p>
<?php } ?>
</article>
</section>
</code>```

here is a screenshot of what happens:

and here is my CSS:

```<code>.products article{
    display:inline-block;
    width:33%;
    text-align: center;
    padding-bottom:60px;
    padding-top:20px;
}
</code>```

Here is what happens when there's no PHP:

What am I doing wrong in my code?

答:
You have set the inline-block on the
-tag, which means that you need to put the
-tag inside the loop:

```<code><?php
$query = "SELECT * FROM products WHERE product_brand = 'Gucci' ";
$select_all_products = mysqli_query($connection, $query);

while($row = mysqli_fetch_assoc($select_all_products)){

    $product_id = $row['product_id'];
    $product_name = $row['product_name'];
    $product_type = $row['product_type'];
    $product_image_front = $row['product_image_front'];
    $product_image_back = $row['product_image_back'];
    $product_image_side = $row['product_image_side'];
    $product_image_full = $row['product_image_full'];
    $product_description = $row['product_description'];
    $product_price = $row['product_price'];
    $product_brand = $row['product_brand'];
?>

    <article>
        <img src="productImages/<?php echo $product_image_front ?>" />
        <h2><?php echo $product_brand; ?></h2>
        <h3><?php echo $product_name; ?></h3>
        <p><?php echo $product_price; ?></p>
    </article>

<?php } ?>
</code>```

Currently, you're putting all products in the same (and only)
-tag.

Body:
I'm currently creating an e-commerce site. I'm using PHP/SQL to display information on the product.

I have set a display: inline-block in the CSS and it seems to work fine when there is no PHP. However once I put in the php, it seems like it becomes a display: block element instead.

Here is my code for the html/php:

Gucci

Established in Florence in 1921, Gucci has evolved from a manufacturer of quality leather accessories into one of the world’s premiere luxury brands. A legacy of glamour, elegance, and modernity underpin its status as a bastion of essential Italian fashion. Alessandro Michele, named creative director in 2015, has ushered in a uniquely contemporary vision of luxury with his eclectic, bohemian, and highly romantic designs.

        <?php

 $query = "SELECT * FROM products WHERE product_brand = 'Gucci' ";

 $select_all_products = mysqli_query($connection, $query);

 while($row = mysqli_fetch_assoc($select_all_products)){

    $product_id = $row['product_id'];
    $product_name = $row['product_name'];
    $product_type = $row['product_type'];
    $product_image_front = $row['product_image_front'];
    $product_image_back = $row['product_image_back'];
    $product_image_side = $row['product_image_side'];
    $product_image_full = $row['product_image_full'];
    $product_description = $row['product_description'];
    $product_price = $row['product_price'];
    $product_brand = $row['product_brand'];

?>

        <img  src="productImages/<?php echo $product_image_front ?>" >

<?php echo $product_brand; ?>

<?php echo $product_name; ?>

<?php echo $product_price; ?>

<?php } ?>

here is a screenshot of what happens:

and here is my CSS:

.products article{
    display:inline-block;
    width:33%;
    text-align: center;
    padding-bottom:60px;
    padding-top:20px;
}

Here is what happens when there's no PHP:

What am I doing wrong in my code?

Body:
You have set the inline-block on the <article>-tag, which means that you need to put the <article>-tag inside the loop:

<?php
$query = "SELECT * FROM products WHERE product_brand = 'Gucci' ";
$select_all_products = mysqli_query($connection, $query);

while($row = mysqli_fetch_assoc($select_all_products)){

    $product_id = $row['product_id'];
    $product_name = $row['product_name'];
    $product_type = $row['product_type'];
    $product_image_front = $row['product_image_front'];
    $product_image_back = $row['product_image_back'];
    $product_image_side = $row['product_image_side'];
    $product_image_full = $row['product_image_full'];
    $product_description = $row['product_description'];
    $product_price = $row['product_price'];
    $product_brand = $row['product_brand'];
?>

    <article>
        <img src="productImages/<?php echo $product_image_front ?>" />
        <h2><?php echo $product_brand; ?></h2>
        <h3><?php echo $product_name; ?></h3>
        <p><?php echo $product_price; ?></p>
    </article>

<?php } ?>

Currently, you're putting all products in the same (and only) <article>-tag.


来源: stackexchange

问:
RxJS subscribe never executes
I would like to calculate and update my map's region every time the map's markers change. So I'm trying to create an observable from the map's markers and subscribe to it:

```<code>class Map extends Component {

  componentDidMount() {
    const { store } = this.context
    this.unsubscribe = store.subscribe(() => { })
    const markers$ = Observable.from(this.props.markers)
    markers$.subscribe(x => console.log('observable', x))
  }
</code>```

Initially I am just console.logging the markers - but eventually I will want to run getRegionForCoordinates and then this.props.updateRegion whenever the markers change. Nothing ever logs to the console. What am I doing wrong? this.props.markers is an empty array initially.

Map.js

```<code>import { StyleSheet } from 'react-native'
import React, { Component } from 'react'
import MapView from 'react-native-maps'
import { connect } from 'react-redux'
import {
  Button,
  Container
} from 'native-base'
import { Observable } from 'rxjs'

import selectMarkers from './markers.selector'

import { updateRegion } from './map.action'
import Icon from 'react-native-vector-icons/FontAwesome'
import { toggleMenu } from '../search-page/searchPage.action'
import mapStyle from './style'

const mapStateToProps = (state) => ({
  region: state.get('map').get('region'),
  markers: selectMarkers(state)
})

const mapDispatchToProps = (dispatch) => ({
  onRegionChange: (region) => {
    dispatch(updateRegion(region))
  },
  onToggleMenuClick: () => {
    dispatch(toggleMenu())
  }
})

const getRegionForCoordinates = (points) => {
  // points should be an array of { latitude: X, longitude: Y }
  let minX, maxX, minY, maxY;

  // init first point
  ((point) => {
    minX = point.latitude
    maxX = point.latitude
    minY = point.longitude
    maxY = point.longitude
  })(points[0])

  // calculate rect
  points.map((point) => {
    minX = Math.min(minX, point.latitude)
    maxX = Math.max(maxX, point.latitude)
    minY = Math.min(minY, point.longitude)
    maxY = Math.max(maxY, point.longitude)
  })

  const midX = (minX + maxX) / 2
  const midY = (minY + maxY) / 2
  const deltaX = (maxX - minX)
  const deltaY = (maxY - minY)

  return {
    latitude: midX,
    longitude: midY,
    latitudeDelta: deltaX,
    longitudeDelta: deltaY
  }
}

class Map extends Component {

  componentDidMount() {
    const { store } = this.context
    this.unsubscribe = store.subscribe(() => { })
    const markers$ = Observable.from(this.props.markers)
    markers$.subscribe(x => console.log('observable', x))
  }

  componentWillUnmount() {
    this.unsubscribe()
  }

  render() {
    return (
      <Container>
        <MapView
          style={styles.map}
          region={this.props.region}
          onRegionChangeComplete={this.props.onRegionChange}
        >
          {
            this.props.markers.map(marker => {
              return (
                <MapView.Marker
                  coordinate={{ latitude: marker.latitude, longitude: marker.longitude }}
                  title={marker.name}
                />
              )
            })}
        </MapView>
        <Button
          small
          icon
          style={mapStyle.toggleMenuButton}
          onPress={() => this.props.onToggleMenuClick()}>
          <Icon name="sliders" size={20} color="#FFFFFF" />
        </Button>
      </Container>
    )
  }
}

Map.contextTypes = {
  store: React.PropTypes.object
}

Map.propTypes = {
  region: React.PropTypes.shape({
    latitude: React.PropTypes.number,
    longitude: React.PropTypes.number,
    latitudeDelta: React.PropTypes.number,
    longitudeDelta: React.PropTypes.number
  }).isRequired,
  onRegionChange: React.PropTypes.func.isRequired,
  onToggleMenuClick: React.PropTypes.func.isRequired,
  markers: React.PropTypes.array
}

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(Map)

const styles = StyleSheet.create({
  map: {
    ...StyleSheet.absoluteFillObject,
    zIndex: -1
  }
})
</code>```

markers.selector.js

```<code>import { createSelector } from 'reselect'

const searchResultsSelector = state => {
  return state.get('searchResults')
}

const selectMarkers = createSelector(
  searchResultsSelector,
  (searchResults) => {
    const shops = searchResults ? searchResults.map(result => {
      return result.shops.map(shop => {
        return {
          id: shop.f1,
          name: shop.f2,
          latitude: shop.f4,
          longitude: shop.f3
        }
      })
    }) : searchResults
    const shopIds = []
    const flattenedShops = [].concat.apply([], shops)
    const uniqueShops = flattenedShops.map(shop => {
      if (!shopIds.includes(shop.id)) {
        shopIds.push(shop.id)
        return shop
      }
    })
    const finalMarkers = uniqueShops.filter(n => n != undefined)
    return finalMarkers
  }
)

export default selectMarkers
</code>```

答:
[EDIT]

below is the solution using rx observables, but quickly after posting it, I was thinking: are you sure you need the power of Observables to achieve what you want?

I think you should consider only using the componentWillReceiveProps which is the React way to observe changes. It might very well suit you needs, I think.

You can totally trigger a getRegionForCoordinates and this.props.updateRegion in this callback without the need of any observable.

[END EDIT]

I see what you are trying to achieve. First, you have to understand that Observable.from only takes a single object/value and then ignores any change made to the initial object.

```<code>const value = [1]
const obs$ = Observable.from(arr)
obs$.subscribe(console.log.bind(console)) // < this will only print once
value.push(2); // < this will be ignored and wont fire anything
</code>```

But, hopefully for you, there is a way to tell React "warn me when properties change". And that's exactly what you want. You want to catch any change made to the this.props.markers and feed it to your observable.

We are going to use Rect's componentWillReceiveProps https://facebook.github.io/react/docs/react-component.html#componentwillreceiveprops to do that

First thing we need to do, is to keep a reference to the marker$ (so it can be accessed in another method:

```<code>componentDidMount() {
  //...
  this.markers$ = new Observable.Subject()
  //you can subscribe here to this observable
  this.markers$.next(this.props.markers)
}
</code>```

And we will also need to implement the componentWillReceiveProps that will feed our markers$

```<code>componentWillReceiveProps(nextProps) {
  this.markers$.next(nextProps.markers)
}
</code>```

And now, this will trigger a subscribe call on your markers$.

ContentLicense: CC BY-SA 3.0

Title: RxJS subscribe never executes

Body:
I would like to calculate and update my map's region every time the map's markers change. So I'm trying to create an observable from the map's markers and subscribe to it:

class Map extends Component {

  componentDidMount() {
    const { store } = this.context
    this.unsubscribe = store.subscribe(() => { })
    const markers$ = Observable.from(this.props.markers)
    markers$.subscribe(x => console.log('observable', x))
  }

Initially I am just console.logging the markers - but eventually I will want to run getRegionForCoordinates and then this.props.updateRegion whenever the markers change. Nothing ever logs to the console. What am I doing wrong? this.props.markers is an empty array initially.

Map.js

import { StyleSheet } from 'react-native'
import React, { Component } from 'react'
import MapView from 'react-native-maps'
import { connect } from 'react-redux'
import {
  Button,
  Container
} from 'native-base'
import { Observable } from 'rxjs'

import selectMarkers from './markers.selector'

import { updateRegion } from './map.action'
import Icon from 'react-native-vector-icons/FontAwesome'
import { toggleMenu } from '../search-page/searchPage.action'
import mapStyle from './style'

const mapStateToProps = (state) => ({
  region: state.get('map').get('region'),
  markers: selectMarkers(state)
})

const mapDispatchToProps = (dispatch) => ({
  onRegionChange: (region) => {
    dispatch(updateRegion(region))
  },
  onToggleMenuClick: () => {
    dispatch(toggleMenu())
  }
})

const getRegionForCoordinates = (points) => {
  // points should be an array of { latitude: X, longitude: Y }
  let minX, maxX, minY, maxY;

  // init first point
  ((point) => {
    minX = point.latitude
    maxX = point.latitude
    minY = point.longitude
    maxY = point.longitude
  })(points[0])

  // calculate rect
  points.map((point) => {
    minX = Math.min(minX, point.latitude)
    maxX = Math.max(maxX, point.latitude)
    minY = Math.min(minY, point.longitude)
    maxY = Math.max(maxY, point.longitude)
  })

  const midX = (minX + maxX) / 2
  const midY = (minY + maxY) / 2
  const deltaX = (maxX - minX)
  const deltaY = (maxY - minY)

  return {
    latitude: midX,
    longitude: midY,
    latitudeDelta: deltaX,
    longitudeDelta: deltaY
  }
}

class Map extends Component {

  componentDidMount() {
    const { store } = this.context
    this.unsubscribe = store.subscribe(() => { })
    const markers$ = Observable.from(this.props.markers)
    markers$.subscribe(x => console.log('observable', x))
  }

  componentWillUnmount() {
    this.unsubscribe()
  }

  render() {
    return (
      <Container>
        <MapView
          style={styles.map}
          region={this.props.region}
          onRegionChangeComplete={this.props.onRegionChange}
        >
          {
            this.props.markers.map(marker => {
              return (
                <MapView.Marker
                  coordinate={{ latitude: marker.latitude, longitude: marker.longitude }}
                  title={marker.name}
                />
              )
            })}
        </MapView>
        <Button
          small
          icon
          style={mapStyle.toggleMenuButton}
          onPress={() => this.props.onToggleMenuClick()}>
          <Icon name="sliders" size={20} color="#FFFFFF" />
        </Button>
      </Container>
    )
  }
}

Map.contextTypes = {
  store: React.PropTypes.object
}

Map.propTypes = {
  region: React.PropTypes.shape({
    latitude: React.PropTypes.number,
    longitude: React.PropTypes.number,
    latitudeDelta: React.PropTypes.number,
    longitudeDelta: React.PropTypes.number
  }).isRequired,
  onRegionChange: React.PropTypes.func.isRequired,
  onToggleMenuClick: React.PropTypes.func.isRequired,
  markers: React.PropTypes.array
}

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(Map)

const styles = StyleSheet.create({
  map: {
    ...StyleSheet.absoluteFillObject,
    zIndex: -1
  }
})

markers.selector.js

import { createSelector } from 'reselect'

const searchResultsSelector = state => {
  return state.get('searchResults')
}

const selectMarkers = createSelector(
  searchResultsSelector,
  (searchResults) => {
    const shops = searchResults ? searchResults.map(result => {
      return result.shops.map(shop => {
        return {
          id: shop.f1,
          name: shop.f2,
          latitude: shop.f4,
          longitude: shop.f3
        }
      })
    }) : searchResults
    const shopIds = []
    const flattenedShops = [].concat.apply([], shops)
    const uniqueShops = flattenedShops.map(shop => {
      if (!shopIds.includes(shop.id)) {
        shopIds.push(shop.id)
        return shop
      }
    })
    const finalMarkers = uniqueShops.filter(n => n != undefined)
    return finalMarkers
  }
)

export default selectMarkers

Body:
[EDIT]

below is the solution using rx observables, but quickly after posting it, I was thinking: are you sure you need the power of Observables to achieve what you want?

I think you should consider only using the componentWillReceiveProps which is the React way to observe changes. It might very well suit you needs, I think.

You can totally trigger a getRegionForCoordinates and this.props.updateRegion in this callback without the need of any observable.

[END EDIT]

I see what you are trying to achieve. First, you have to understand that Observable.from only takes a single object/value and then ignores any change made to the initial object.

const value = [1]
const obs$ = Observable.from(arr)
obs$.subscribe(console.log.bind(console)) // < this will only print once
value.push(2); // < this will be ignored and wont fire anything

But, hopefully for you, there is a way to tell React "warn me when properties change". And that's exactly what you want. You want to catch any change made to the this.props.markers and feed it to your observable.

We are going to use Rect's componentWillReceiveProps https://facebook.github.io/react/docs/react-component.html#componentwillreceiveprops to do that

First thing we need to do, is to keep a reference to the marker$ (so it can be accessed in another method:

componentDidMount() {
  //...
  this.markers$ = new Observable.Subject()
  //you can subscribe here to this observable
  this.markers$.next(this.props.markers)
}

And we will also need to implement the componentWillReceiveProps that will feed our markers$

componentWillReceiveProps(nextProps) {
  this.markers$.next(nextProps.markers)
}

And now, this will trigger a subscribe call on your markers$.


问:
Issue Drawing Multiple Moving Items of Screen Pygame
I am attempting to draw multiple items on the screen that will move in random directions. The problem is that when I run the program, the objects blink and flash on the screen, not progress across smoothly. I am rather baffled as I only update the screen once, as recommended by other posts on SO. My code is below:</p>

```<code>class Game:
   def __init__(self):
        self.possible_directions = ["up", "down"]
        self.speed_down = 800
        self.speed_up = 0
        self.asteroid = pygame.image.load("Asteroididadactyl.png")

   def def draw_asteroid(self, direction):

       if direction == "down":
           self.gameDisplay.blit(self.asteroid, (self.options[direction], self.speed_down))

           self.speed_down -= 1

       elif direction == "up":

           self.gameDisplay.blit(self.asteroid, (self.options[direction], self.speed_up))
           self.speed_up += 1

   def player(self):

      pygame.init()
      self.gameDisplay = pygame.display.set_mode((1000, 900))

      pygame.display.set_caption("Asteroid belt")

      while True:

          for event in pygame.event.get():
             #move main object.

          self.choice = random.choice(self.possible_directions)

          self.draw_asteroid(self.choice)

          pygame.display.flip()
</code>```

答:
The draw_asteroid method blits the asteroid image depending on the direction that was passed, and since you pass a random direction each frame,  the image is sometimes blitted at the up position (which is called self.speed_up) and other times at the down position (self.speed_down), so it appears to flicker.

I'd recommend to change the code completely and rather use objects or pygame sprites with vectors for the velocity and position which you can set to random values during the instantiation. Then first update the objects altogether in the while loop and finally blit them onto the display.

Edit: Here's a minimal example (you could also use pygame.sprite.Sprites and sprite groups instead of the list).

```<code>import sys
import random
import pygame as pg

class Asteroid:

    def __init__(self):
        self.image = pg.Surface((50, 50))
        self.image.fill((150, 60, 10))
        self.pos = pg.math.Vector2(random.randrange(1230),
                                   random.randrange(750))
        self.vel = pg.math.Vector2(random.uniform(-5, 5),
                                   random.uniform(-5, 5))

    def update(self):
        self.pos += self.vel

class Game:

    def __init__(self):
        pg.init()
        self.screen = pg.display.set_mode((1280, 800))
        self.clock = pg.time.Clock()
        self.bg_color = pg.Color(20, 20, 20)
        self.asteroids = [Asteroid() for _ in range(10)]
        self.done = False

    def run(self):
        while not self.done:
            for event in pg.event.get():
                if event.type == pg.QUIT:
                    self.done = True

            for asteroid in self.asteroids:
                asteroid.update()

            self.screen.fill(self.bg_color)
            for asteroid in self.asteroids:
                self.screen.blit(asteroid.image, asteroid.pos)

            pg.display.flip()
            self.clock.tick(30)

Game().run()
pg.quit()
sys.exit()
</code>```

Body:
I am attempting to draw multiple items on the screen that will move in random directions. The problem is that when I run the program, the objects blink and flash on the screen, not progress across smoothly. I am rather baffled as I only update the screen once, as recommended by other posts on SO. My code is below:

class Game:
   def __init__(self):
        self.possible_directions = ["up", "down"]
        self.speed_down = 800
        self.speed_up = 0
        self.asteroid = pygame.image.load("Asteroididadactyl.png")

   def def draw_asteroid(self, direction):

       if direction == "down":
           self.gameDisplay.blit(self.asteroid, (self.options[direction], self.speed_down))

           self.speed_down -= 1

       elif direction == "up":

           self.gameDisplay.blit(self.asteroid, (self.options[direction], self.speed_up))
           self.speed_up += 1

   def player(self):

      pygame.init()
      self.gameDisplay = pygame.display.set_mode((1000, 900))

      pygame.display.set_caption("Asteroid belt")

      while True:

          for event in pygame.event.get():
             #move main object.

          self.choice = random.choice(self.possible_directions)

          self.draw_asteroid(self.choice)

          pygame.display.flip()

Body:
The draw_asteroid method blits the asteroid image depending on the direction that was passed, and since you pass a random direction each frame,  the image is sometimes blitted at the up position (which is called self.speed_up) and other times at the down position (self.speed_down), so it appears to flicker.

I'd recommend to change the code completely and rather use objects or pygame sprites with vectors for the velocity and position which you can set to random values during the instantiation. Then first update the objects altogether in the while loop and finally blit them onto the display.

Edit: Here's a minimal example (you could also use pygame.sprite.Sprites and sprite groups instead of the list).

import sys
import random
import pygame as pg

class Asteroid:

    def __init__(self):
        self.image = pg.Surface((50, 50))
        self.image.fill((150, 60, 10))
        self.pos = pg.math.Vector2(random.randrange(1230),
                                   random.randrange(750))
        self.vel = pg.math.Vector2(random.uniform(-5, 5),
                                   random.uniform(-5, 5))

    def update(self):
        self.pos += self.vel

class Game:

    def __init__(self):
        pg.init()
        self.screen = pg.display.set_mode((1280, 800))
        self.clock = pg.time.Clock()
        self.bg_color = pg.Color(20, 20, 20)
        self.asteroids = [Asteroid() for _ in range(10)]
        self.done = False

    def run(self):
        while not self.done:
            for event in pg.event.get():
                if event.type == pg.QUIT:
                    self.done = True

            for asteroid in self.asteroids:
                asteroid.update()

            self.screen.fill(self.bg_color)
            for asteroid in self.asteroids:
                self.screen.blit(asteroid.image, asteroid.pos)

            pg.display.flip()
            self.clock.tick(30)

Game().run()
pg.quit()
sys.exit()


问:
How to create a truly blank project in Visual Studio (2017)
It seems like there should be a way to do this, but I just can't seem to do it. I love VS and I want to use it to develop web apps that are strictly HTML/Javascript based. In other words, no C#, no VB, no resulting /bin folder, no web config, no nothing. A blank project meaning "truly 100% blank" and not trying force me into some Microsoft technology or otherwise. I just want to use VS to write the code because it's still the best HTML/Javascript/Typescript/Everything-else-script editor out there.

Any thoughts on this? Can it even be done? Or is VS just too dependent on "Microsoft thinking" to allow this?

答:
It seems that what you want is to start with an empty canvas like Blank Solution and then add your files in the solution. You don't actually need to have library/console/web projects in a solution, you could just have html and js and whatever you use for web development.
You can find the Blank Solution when you create a new project under the Other Project Types tab.</p>


问:
Xamarin.Forms labels not working anymore, on iOS
I am making a Xamarin.Forms project, and I am in the end of my app, but something really strange have happened. My app starts up with no labels (!?), meaning they are invisible or not created at all. Everything else seems to be working, until I press a button that is supposed to change the label - when I do this, the app freezes. I get no exception in Visual Studio, though.

One problem is that my breakpoints in PLC code never hits, only those I place in the iOS code. However, the buttons not related to changing a label works, so I know the PLC code have been ran. If I let the app run for a little while, and then press the pause-button in VS debugging to see where in the code I am, it stops at

```<code>UIApplication.Main(args, null, "AppDelegate");
</code>```

.. in Main.cs. I dont know if this is correct or not, when I run on Android, I get a Break Mode - No code is currently running.

I have been trying for hours to debug, reinstall, restart, clean and rebuild, but nothing seems to help. My code works perfectly in Android, and it worked in iOS 1 week ago. Anyone have any ideas what is going on, or what I can do to debug some more? Or must I make a new project and try start over?

Edit: I have also tried different starting pages, and all are the same: all views loads except those with text in them. I have a page with an Editor in it, and I can write in it, but no text is appearing inside of it. Only button have visible text. I do not use a custom font for my labels, I have not specified anything.

答:
Waking up fresh in the morning, I found my issue in 15 minutes..

After altering my Google search to TextView iOS instead of Label Xamarin, I found much more answers. Thanks to this question and answer.

Basically, changing anything on the labels in the constructor of the page (even after InitializeComponent()), will mess up the view. I moved my code outside of the constructor (in the protected override void OnAppearing() method), and now it is working again.

The freeze part was not related - this was my custom menu that covered my screen with an invisible layout eating up all clicking events. A bit confusing, none of these issues are present in Android, but there you go.

Body:
I am making a Xamarin.Forms project, and I am in the end of my app, but something really strange have happened. My app starts up with no labels (!?), meaning they are invisible or not created at all. Everything else seems to be working, until I press a button that is supposed to change the label - when I do this, the app freezes. I get no exception in Visual Studio, though.

One problem is that my breakpoints in PLC code never hits, only those I place in the iOS code. However, the buttons not related to changing a label works, so I know the PLC code have been ran. If I let the app run for a little while, and then press the pause-button in VS debugging to see where in the code I am, it stops at

UIApplication.Main(args, null, "AppDelegate");

.. in Main.cs. I dont know if this is correct or not, when I run on Android, I get a Break Mode - No code is currently running.

I have been trying for hours to debug, reinstall, restart, clean and rebuild, but nothing seems to help. My code works perfectly in Android, and it worked in iOS 1 week ago. Anyone have any ideas what is going on, or what I can do to debug some more? Or must I make a new project and try start over?

Edit: I have also tried different starting pages, and all are the same: all views loads except those with text in them. I have a page with an Editor in it, and I can write in it, but no text is appearing inside of it. Only button have visible text. I do not use a custom font for my labels, I have not specified anything.


问:
Printing PDF using PDFRenderer - shapes are not sharp
I need to print PDF shipping label. Those labels are in PDF format. The printed shipping label has sharp text but there is problem with barcode which has little "Gear teeths" - the barcode-stripes are not smooth on the edges which is problematic for scanners.

I tried to use PDF-creator as printer and print it to the file - barcodes are sharp then (on the PC-display).

I tried also print already created file using PDF-creator (like above), then print it in PDF-Reader and barcodes are sharp in this case.

I test it on thermal Printer Zebra TLP 2844 and the printer supports only one mode 80 DPI (according to PrintService attributes)

答: It is resolved, there were wrong resolution of image and the printer scaled the image itself which disturb the quality of printed image (where fonts were still sharp [I had to print both image and font on the same paper])</p>


问:
How to set selected item in reactstrap Dropdown?
How to set selected item in reactstrap Dropdown?

There is example of dropdown: https://reactstrap.github.io/components/dropdowns/

When I select item in dropdown, it is not displayed.

*******************Working solution*****************************

import React from "react";
import {ButtonDropdown, DropdownItem, DropdownMenu, DropdownToggle} from "reactstrap";
import superagent from "superagent";

class BootstrapSelect extends React.Component {

    constructor(props) {
        super(props);

        this.toggle = this.toggle.bind(this);
        this.changeValue = this.changeValue.bind(this);
        this.state = {
            actions: [],
            dropDownValue: 'Select action',
            dropdownOpen: false
        };
    }

    toggle(event) {

        this.setState({
            dropdownOpen: !this.state.dropdownOpen
        });
    }

    changeValue(e) {
        this.setState({dropDownValue: e.currentTarget.textContent});
        let id = e.currentTarget.getAttribute("id");
        console.log(id);
    }

    componentDidMount() {
        superagent
            .get('/getActions')
            .type('application/json; charset=utf-8')
            .end(function (err, res) {
                console.log(res.body);
                this.setState({actions: res.body});
            }.bind(this));

    }

    render() {
        return (
            <ButtonDropdown isOpen={this.state.dropdownOpen} toggle={this.toggle}>
                <DropdownToggle caret>
                    {this.state.dropDownValue}
                </DropdownToggle>
                <DropdownMenu>
                    {this.state.actions.map(e => {
                        return <DropdownItem id={e.id} key={e.id} onClick={this.changeValue}>{e.name}</DropdownItem>
                    })}
                </DropdownMenu>

            </ButtonDropdown>
        );
    }

}

export default BootstrapSelect;
```

答:
Add an onclick on your DropDownItem (inside a div ?) to change your state. Set a "dropDownValue" from your click event.
In your dropDownToggle, get your state.dropDownValue.

Something like this :

```<code>changeValue(e) {
  this.setState({dropDownValue: e.currentTarget.textContent})
}

<DropdownToggle caret>
    {this.state.dropDownValue}
</DropdownToggle>
<DropdownItem>
    <div onClick={this.changeValue}>Another Action</div>
</DropdownItem>
</code>```

Of course, don't forget to init it and bind the function for your this to work.

Body:
Add an onclick on your DropDownItem (inside a div ?) to change your state. Set a "dropDownValue" from your click event.
In your dropDownToggle, get your state.dropDownValue.

Something like this :

changeValue(e) {
  this.setState({dropDownValue: e.currentTarget.textContent})
}

<DropdownToggle caret>
    {this.state.dropDownValue}
</DropdownToggle>
<DropdownItem>
    <div onClick={this.changeValue}>Another Action</div>
</DropdownItem>

Of course, don't forget to init it and bind the function for your this to work.


问:
Custom shaped buttons in Android layout
How would one achieve these type of buttons?

Can selector and shapes achieve this (the buttons clickable area should have the shape of the button) or are there any libraries and custom widgets for this?

答:
I did a custom view called RoundButton,add this class in your project

```<code>import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Xfermode;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;

/**
 * Created by Jinesh Francis on 5/6/17.
 */

public class RoundButton extends View {
    private Paint firstCirclePaint,secondCirclePaint,secondCircleStrokePaint;
    private int firstCircleColor=0xFF006680,secondCircleColor=0xFF85A3BD,secondCircleStokeColor=0xFFFFFFFF;
    private int width,height;
    private PorterDuffXfermode porterDuffXfermode;
    public RoundButton(Context context) {
        super(context);
        init(context,null);
    }

    public RoundButton(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context,attrs);
    }

    private void init(Context context, AttributeSet attrs) {
        setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        firstCirclePaint=new Paint(Paint.ANTI_ALIAS_FLAG);
        firstCirclePaint.setColor(firstCircleColor);

        secondCirclePaint=new Paint(Paint.ANTI_ALIAS_FLAG);
        secondCirclePaint.setColor(secondCircleColor);

        secondCircleStrokePaint=new Paint(Paint.ANTI_ALIAS_FLAG);
        secondCircleStrokePaint.setColor(secondCircleStokeColor);

        porterDuffXfermode=new PorterDuffXfermode(PorterDuff.Mode.CLEAR);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        secondCircleStrokePaint.setXfermode(porterDuffXfermode);
        canvas.drawCircle(width/2,width/2,width/2,firstCirclePaint);
        canvas.drawCircle(width/2,(width/2)+(width/3),(width/3)+(width/(width/8)),secondCircleStrokePaint);
        canvas.drawCircle(width/2,(width/2)+(width/3),width/3,secondCirclePaint);

    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int desiredWidth = 300;
        int desiredHeight = desiredWidth+((desiredWidth/3)/2)+(desiredWidth/(desiredWidth/8));

        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);

        int width;
        int height;

        //Measure Width
        if (widthMode == MeasureSpec.EXACTLY) {
            //Must be this size
            width = widthSize;
        } else if (widthMode == MeasureSpec.AT_MOST) {
            //Can't be bigger than...
            width = Math.min(desiredWidth, widthSize);
        } else {
            //Be whatever you want
            width = desiredWidth;
        }

        //Measure Height
        if (heightMode == MeasureSpec.EXACTLY) {
            //Must be this size
            height = heightSize;
        } else if (heightMode == MeasureSpec.AT_MOST) {
            //Can't be bigger than...
            height = Math.min(desiredHeight, heightSize);
        } else {
            //Be whatever you want
            height = desiredHeight;
        }

        //MUST CALL THIS
        setMeasuredDimension(width, height);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        width=w;
        height=h;
    }

    public int getFirstCircleColor() {
        return firstCircleColor;
    }

    public void setFirstCircleColor(int firstCircleColor) {
        this.firstCircleColor = firstCircleColor;
    }

    public int getSecondCircleColor() {
        return secondCircleColor;
    }

    public void setSecondCircleColor(int secondCircleColor) {
        this.secondCircleColor = secondCircleColor;
    }

    public int getSecondCircleStokeColor() {
        return secondCircleStokeColor;
    }

    public void setSecondCircleStokeColor(int secondCircleStokeColor) {
        this.secondCircleStokeColor = secondCircleStokeColor;
    }
}
</code>```

For adding button in layout

```<code> <"write_your_package_of_RoundButton_here".RoundButton
        android:layout_width="wrap_content"
        android:layout_centerInParent="true"
        android:id="@+id/round"
        android:layout_height="wrap_content" />
</code>```

And In Activity set Clicklistner for RoundButton

```<code> RoundButton roundButton= (RoundButton) findViewById(R.id.round);
 roundButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
       Toast.makeText(MainActivity.this, "View Clicked!", Toast.LENGTH_SHORT).show();
    }
 });
</code>```

ScreenShot:

Title: Custom shaped buttons in Android layout

Body:
I did a custom view called RoundButton,add this class in your project

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Xfermode;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;

/**
 * Created by Jinesh Francis on 5/6/17.
 */

public class RoundButton extends View {
    private Paint firstCirclePaint,secondCirclePaint,secondCircleStrokePaint;
    private int firstCircleColor=0xFF006680,secondCircleColor=0xFF85A3BD,secondCircleStokeColor=0xFFFFFFFF;
    private int width,height;
    private PorterDuffXfermode porterDuffXfermode;
    public RoundButton(Context context) {
        super(context);
        init(context,null);
    }

    public RoundButton(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context,attrs);
    }

    private void init(Context context, AttributeSet attrs) {
        setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        firstCirclePaint=new Paint(Paint.ANTI_ALIAS_FLAG);
        firstCirclePaint.setColor(firstCircleColor);

        secondCirclePaint=new Paint(Paint.ANTI_ALIAS_FLAG);
        secondCirclePaint.setColor(secondCircleColor);

        secondCircleStrokePaint=new Paint(Paint.ANTI_ALIAS_FLAG);
        secondCircleStrokePaint.setColor(secondCircleStokeColor);

        porterDuffXfermode=new PorterDuffXfermode(PorterDuff.Mode.CLEAR);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        secondCircleStrokePaint.setXfermode(porterDuffXfermode);
        canvas.drawCircle(width/2,width/2,width/2,firstCirclePaint);
        canvas.drawCircle(width/2,(width/2)+(width/3),(width/3)+(width/(width/8)),secondCircleStrokePaint);
        canvas.drawCircle(width/2,(width/2)+(width/3),width/3,secondCirclePaint);

    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int desiredWidth = 300;
        int desiredHeight = desiredWidth+((desiredWidth/3)/2)+(desiredWidth/(desiredWidth/8));

        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);

        int width;
        int height;

        //Measure Width
        if (widthMode == MeasureSpec.EXACTLY) {
            //Must be this size
            width = widthSize;
        } else if (widthMode == MeasureSpec.AT_MOST) {
            //Can't be bigger than...
            width = Math.min(desiredWidth, widthSize);
        } else {
            //Be whatever you want
            width = desiredWidth;
        }

        //Measure Height
        if (heightMode == MeasureSpec.EXACTLY) {
            //Must be this size
            height = heightSize;
        } else if (heightMode == MeasureSpec.AT_MOST) {
            //Can't be bigger than...
            height = Math.min(desiredHeight, heightSize);
        } else {
            //Be whatever you want
            height = desiredHeight;
        }

        //MUST CALL THIS
        setMeasuredDimension(width, height);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        width=w;
        height=h;
    }

    public int getFirstCircleColor() {
        return firstCircleColor;
    }

    public void setFirstCircleColor(int firstCircleColor) {
        this.firstCircleColor = firstCircleColor;
    }

    public int getSecondCircleColor() {
        return secondCircleColor;
    }

    public void setSecondCircleColor(int secondCircleColor) {
        this.secondCircleColor = secondCircleColor;
    }

    public int getSecondCircleStokeColor() {
        return secondCircleStokeColor;
    }

    public void setSecondCircleStokeColor(int secondCircleStokeColor) {
        this.secondCircleStokeColor = secondCircleStokeColor;
    }
}

For adding button in layout

 <"write_your_package_of_RoundButton_here".RoundButton
        android:layout_width="wrap_content"
        android:layout_centerInParent="true"
        android:id="@+id/round"
        android:layout_height="wrap_content" />

And In Activity set Clicklistner for RoundButton

 RoundButton roundButton= (RoundButton) findViewById(R.id.round);
 roundButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
       Toast.makeText(MainActivity.this, "View Clicked!", Toast.LENGTH_SHORT).show();
    }
 });

ScreenShot:


问:
How to play and pause the audio by using the media player?
I want to perform the three functions by using the single play button.
  First process - when we click the play button the mediaplayer should play the audio.
  second process - when user click second time the play button the audio should be paused.
  Third process - when user click the third time play button the audio should resume from the paused song.

The tried the below code

```<code> if (!mediaPlayer.isPlaying()) {
                mediaPlayer.reset();
                try {
                    mediaPlayer.setDataSource(path);
                    //  mediaPlayer.setOnPreparedListener((MediaPlayer.OnPreparedListener) getActivity());
                    mediaPlayer.prepare();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                mediaPlayer.start();

            }
           else if (mediaPlayer.isPlaying()) {
                mediaPlayer.pause();
            }

            else if (!mediaPlayer.isPlaying() && mediaPlayer.getCurrentPosition() > 0) {
                long currentPosition = mediaPlayer.getCurrentPosition();
                mediaPlayer.seekTo((int) currentPosition);
                mediaPlayer.start();

            }
</code>```

The above code is not working ,please help me how to solve this.

答:
You can try this

```<code>holder.btPlay.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {

    if (mediaPlayer != null && mediaPlayer[0] != null && mediaPlayer[0].isPlaying()) {
        mediaPlayer[0].stop();
        mediaPlayer[0].release();
        return;
    }
    mediaPlayer = new MediaPlayer[]{MediaPlayer.create(context, soundUri)};
    mediaPlayer[0].setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                                    @Override
                                    public void onPrepared(MediaPlayer mp) {mp.start();
                                    }
                                });
    mediaPlayer[0].setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mp) {
           try {
               mp.release();
           } catch (Exception e) {

           }
           mediaPlayer[0] = null;
        }
    });
    mediaPlayer[0].setOnErrorListener(new MediaPlayer.OnErrorListener() {
         @Override
         public boolean onError(MediaPlayer mp, int what, int extra) {
            try {
                mp.release();
            } catch (Exception e) {

            }
            mediaPlayer[0] = null;
            return false;}
    });
}
</code>```

}

Body:
I want to perform the three functions by using the single play button.
  First process - when we click the play button the mediaplayer should play the audio.
  second process - when user click second time the play button the audio should be paused.
  Third process - when user click the third time play button the audio should resume from the paused song.

The tried the below code

 if (!mediaPlayer.isPlaying()) {
                mediaPlayer.reset();
                try {
                    mediaPlayer.setDataSource(path);
                    //  mediaPlayer.setOnPreparedListener((MediaPlayer.OnPreparedListener) getActivity());
                    mediaPlayer.prepare();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                mediaPlayer.start();

            }
           else if (mediaPlayer.isPlaying()) {
                mediaPlayer.pause();
            }

            else if (!mediaPlayer.isPlaying() && mediaPlayer.getCurrentPosition() > 0) {
                long currentPosition = mediaPlayer.getCurrentPosition();
                mediaPlayer.seekTo((int) currentPosition);
                mediaPlayer.start();

            }

The above code is not working ,please help me how to solve this.

Body:
You can try this

holder.btPlay.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {

    if (mediaPlayer != null && mediaPlayer[0] != null && mediaPlayer[0].isPlaying()) {
        mediaPlayer[0].stop();
        mediaPlayer[0].release();
        return;
    }
    mediaPlayer = new MediaPlayer[]{MediaPlayer.create(context, soundUri)};
    mediaPlayer[0].setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                                    @Override
                                    public void onPrepared(MediaPlayer mp) {mp.start();
                                    }
                                });
    mediaPlayer[0].setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mp) {
           try {
               mp.release();
           } catch (Exception e) {

           }
           mediaPlayer[0] = null;
        }
    });
    mediaPlayer[0].setOnErrorListener(new MediaPlayer.OnErrorListener() {
         @Override
         public boolean onError(MediaPlayer mp, int what, int extra) {
            try {
                mp.release();
            } catch (Exception e) {

            }
            mediaPlayer[0] = null;
            return false;}
    });
}

}


问:
Powershell to restore database(SQL Server)
I am planning automate the restore process for SQL Server using Powershell. I don't get any error when I execute the below powershell script. Any help will be appreciated. I am not able to execute the below powershell script successfully. </p>

```<code>[string]  $SourceServer= ".\LOCAL"
[string]  $DestinationServer= ".\LOCAL2"
[string]  $SourceDatabase = "msdb"
[string]  $DestinationDatabase = "master"
[string]  $RestoreDatabase="test1"
[string]  $DataFolder='C:\Program Files\Microsoft SQL Server\MSSQL11.LOCAL2\MSSQL\DATA'
[string]  $LogFolder='C:\Program Files\Microsoft SQL Server\MSSQL11.LOCAL2\MSSQL\DATA'

[string]  $FullBackupSourceQuery= $("SELECT REPLACE (c.physical_device_name,'C:\SQL Server\Backup\','\\servername\Backup\')
FROM msdb.dbo.backupset a
INNER JOIN (SELECT database_name , backupdate = MAX(backup_finish_date)
FROM msdb.dbo.backupset
WHERE type = 'D' AND
backup_finish_date >= DATEADD(MONTH , -1 , GETDATE())
AND  database_name =$RestoreDatabase
GROUP BY database_name)b
ON a.database_name=b.database_name
AND a.backup_finish_date=b.backupdate
INNER JOIN msdb.dbo.backupmediafamily c
ON c.media_set_id = a.media_set_id")

[string]  $DiffBackupSourceQuery= $("SELECT REPLACE (c.physical_device_name,'C:\SQL Server\Backup\','\\servername\Backup\')
FROM msdb.dbo.backupset a
INNER JOIN (SELECT database_name , backupdate = MAX(backup_finish_date)
FROM msdb.dbo.backupset
WHERE type = 'I' AND
backup_finish_date >= DATEADD(MONTH , -1 , GETDATE())
AND  database_name =$RestoreDatabase
GROUP BY database_name)b
ON a.database_name=b.database_name
AND a.backup_finish_date=b.backupdate
INNER JOIN msdb.dbo.backupmediafamily c
ON c.media_set_id = a.media_set_id")

[string] $DestinationQuery=$("
EXEC master..RestoreDatabase
       @BackupFile = '$value',
       @NewDatabaseName = '$RestoreDatabase',
       @AdditionalOptions='STATS=5, REPLACE, NORECOVERY',
       @DataFolder = '$DataFolder',
       @LogFolder = '$LogFolder',
       @ExecuteRestoreImmediately = 'Y'

EXEC master..RestoreDatabase
       @BackupFile = '$value1',
       @NewDatabaseName = '$RestoreDatabase',
       @AdditionalOptions='STATS=5, REPLACE, RECOVERY',
       @DataFolder = '$DataFolder',
       @LogFolder = '$LogFolder',
       @ExecuteRestoreImmediately = 'Y'
")

function GenericSqlQuery ($SourceServer, $SourceDatabase, $SourceQuery, $DestinationServer, $DestinationDatabase, $DestnationQuery)
{
  {
    $SourceConnection = New-Object System.Data.SQLClient.SQLConnection
    $SourceConnection.ConnectionString = "server='$SourceServer';database='$SourceDatabase';trusted_connection=true;"
    $SourceConnection.Open()
    $SourceCommand = New-Object System.Data.SQLClient.SQLCommand
    $SourceCommand.Connection = $Connection
    $SourceCommand.CommandText = $FullBackupSourceQuery
    $SourceReader = $Command.ExecuteReader()
    while ($SourceReader.Read())  {
         $value=$SourceReader.GetValue($1)
                                  }
    $SourceCommand.CommandText = $DiffBackupSourceQuery

    $SourceReader = $Command.ExecuteReader()
    while ($SourceReader.Read()) {
         $value1=$SourceReader.GetValue($1)
                                 }
   }
      $SourceConnection.Close()
  {
    $DestinationConnection = New-Object System.Data.SQLClient.SQLConnection
    $DestinationConnection.ConnectionString = "server='$DestinationServer';database='$DestinationDatabase';trusted_connection=true;"
    $DestinationConnection.Open()
    $DestinationCommand = New-Object System.Data.SQLClient.SQLCommand
    $DestinationCommand.Connection = $Connection
    $DestinationCommand.CommandText = $DestinationQuery
    $DestinationReader = $Command.ExecuteReader()
  }
    $DestinationConnection.Close()
}
</code>```

答:
Right off your function GenericSqlQuery contains a variable called $1 which I do not see set to anything. In perl that was a special variable, but in PowerShell it has no meaning until you set it to something.

As noted though a more efficient method, that includes logging and validations, is to utilize dbatools module for the restores. [Disclosure: I am a contributor to this project.]

```<code>#if not installed
Install-Module dbatools

# import it
Import-Module dbatools

# Restore it
$sourceServer = '.\LOCAL'
$DestServer = '.\LOCAL2'
$RestoreDb = 'test1'
$DataFolder='C:\Program Files\Microsoft SQL Server\MSSQL11.LOCAL2\MSSQL\DATA'
$LogFolder='C:\Program Files\Microsoft SQL Server\MSSQL11.LOCAL2\MSSQL\DATA'

# IF you need to get backup history
Get-DbaRestoreHistory -SqlServer $sourceServer -Databases $RestoreDb |
    Restore-DbaDatabase -SqlServer $DestServer -DestinationDataDirectory $DataFolder -DestinationLogDirectory $LogFolder

# IF you just want to base it on backup folder, will SCAN complete folder
$dbBackupPath = "\\servername\Backup\$RestoreDb"
Restore-DbaDatabase -SqlServer $DestServer -Path $dbBackupPath -DestinationDataDirectory $DataFolder -DestinationLogDirectory $LogFolder
</code>```

Body:
I am planning automate the restore process for SQL Server using Powershell. I don't get any error when I execute the below powershell script. Any help will be appreciated. I am not able to execute the below powershell script successfully.

[string]  $SourceServer= ".\LOCAL"
[string]  $DestinationServer= ".\LOCAL2"
[string]  $SourceDatabase = "msdb"
[string]  $DestinationDatabase = "master"
[string]  $RestoreDatabase="test1"
[string]  $DataFolder='C:\Program Files\Microsoft SQL Server\MSSQL11.LOCAL2\MSSQL\DATA'
[string]  $LogFolder='C:\Program Files\Microsoft SQL Server\MSSQL11.LOCAL2\MSSQL\DATA'

[string]  $FullBackupSourceQuery= $("SELECT REPLACE (c.physical_device_name,'C:\SQL Server\Backup\','\\servername\Backup\')
FROM msdb.dbo.backupset a
INNER JOIN (SELECT database_name , backupdate = MAX(backup_finish_date)
FROM msdb.dbo.backupset
WHERE type = 'D' AND
backup_finish_date >= DATEADD(MONTH , -1 , GETDATE())
AND  database_name =$RestoreDatabase
GROUP BY database_name)b
ON a.database_name=b.database_name
AND a.backup_finish_date=b.backupdate
INNER JOIN msdb.dbo.backupmediafamily c
ON c.media_set_id = a.media_set_id")

[string]  $DiffBackupSourceQuery= $("SELECT REPLACE (c.physical_device_name,'C:\SQL Server\Backup\','\\servername\Backup\')
FROM msdb.dbo.backupset a
INNER JOIN (SELECT database_name , backupdate = MAX(backup_finish_date)
FROM msdb.dbo.backupset
WHERE type = 'I' AND
backup_finish_date >= DATEADD(MONTH , -1 , GETDATE())
AND  database_name =$RestoreDatabase
GROUP BY database_name)b
ON a.database_name=b.database_name
AND a.backup_finish_date=b.backupdate
INNER JOIN msdb.dbo.backupmediafamily c
ON c.media_set_id = a.media_set_id")

[string] $DestinationQuery=$("
EXEC master..RestoreDatabase
       @BackupFile = '$value',
       @NewDatabaseName = '$RestoreDatabase',
       @AdditionalOptions='STATS=5, REPLACE, NORECOVERY',
       @DataFolder = '$DataFolder',
       @LogFolder = '$LogFolder',
       @ExecuteRestoreImmediately = 'Y'

EXEC master..RestoreDatabase
       @BackupFile = '$value1',
       @NewDatabaseName = '$RestoreDatabase',
       @AdditionalOptions='STATS=5, REPLACE, RECOVERY',
       @DataFolder = '$DataFolder',
       @LogFolder = '$LogFolder',
       @ExecuteRestoreImmediately = 'Y'
")

function GenericSqlQuery ($SourceServer, $SourceDatabase, $SourceQuery, $DestinationServer, $DestinationDatabase, $DestnationQuery)
{
  {
    $SourceConnection = New-Object System.Data.SQLClient.SQLConnection
    $SourceConnection.ConnectionString = "server='$SourceServer';database='$SourceDatabase';trusted_connection=true;"
    $SourceConnection.Open()
    $SourceCommand = New-Object System.Data.SQLClient.SQLCommand
    $SourceCommand.Connection = $Connection
    $SourceCommand.CommandText = $FullBackupSourceQuery
    $SourceReader = $Command.ExecuteReader()
    while ($SourceReader.Read())  {
         $value=$SourceReader.GetValue($1)
                                  }
    $SourceCommand.CommandText = $DiffBackupSourceQuery

    $SourceReader = $Command.ExecuteReader()
    while ($SourceReader.Read()) {
         $value1=$SourceReader.GetValue($1)
                                 }
   }
      $SourceConnection.Close()
  {
    $DestinationConnection = New-Object System.Data.SQLClient.SQLConnection
    $DestinationConnection.ConnectionString = "server='$DestinationServer';database='$DestinationDatabase';trusted_connection=true;"
    $DestinationConnection.Open()
    $DestinationCommand = New-Object System.Data.SQLClient.SQLCommand
    $DestinationCommand.Connection = $Connection
    $DestinationCommand.CommandText = $DestinationQuery
    $DestinationReader = $Command.ExecuteReader()
  }
    $DestinationConnection.Close()
}

Body:
Right off your function GenericSqlQuery contains a variable called $1 which I do not see set to anything. In perl that was a special variable, but in PowerShell it has no meaning until you set it to something.

As noted though a more efficient method, that includes logging and validations, is to utilize dbatools module for the restores. [Disclosure: I am a contributor to this project.]

#if not installed
Install-Module dbatools

# import it
Import-Module dbatools

# Restore it
$sourceServer = '.\LOCAL'
$DestServer = '.\LOCAL2'
$RestoreDb = 'test1'
$DataFolder='C:\Program Files\Microsoft SQL Server\MSSQL11.LOCAL2\MSSQL\DATA'
$LogFolder='C:\Program Files\Microsoft SQL Server\MSSQL11.LOCAL2\MSSQL\DATA'

# IF you need to get backup history
Get-DbaRestoreHistory -SqlServer $sourceServer -Databases $RestoreDb |
    Restore-DbaDatabase -SqlServer $DestServer -DestinationDataDirectory $DataFolder -DestinationLogDirectory $LogFolder

# IF you just want to base it on backup folder, will SCAN complete folder
$dbBackupPath = "\\servername\Backup\$RestoreDb"
Restore-DbaDatabase -SqlServer $DestServer -Path $dbBackupPath -DestinationDataDirectory $DataFolder -DestinationLogDirectory $LogFolder


问:
zoom is not working in webView on android application
When I open pptx file through this link zoom is not working in android webview.

Here is the code that i'm using:

```<code>WebSettings setting = wView.getSettings();
setting.setBuiltInZoomControls(true);
setting.setSupportZoom(true);
</code>```

答:
For enable zoom option add this line of code.</p>

```<code>webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setSupportZoom(true);
</code>```

Body:
When I open pptx file through this link zoom is not working in android webview.

Here is the code that i'm using:

WebSettings setting = wView.getSettings();
setting.setBuiltInZoomControls(true);
setting.setSupportZoom(true);

Body:
For enable zoom option add this line of code.

webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setSupportZoom(true);

ContentLicense: CC BY-SA 4.0


问:
How to use variable in another variable in SCSS
How I can use a variable in another variable?
How I can do this:</p>

```<code>$buttons: default, success, primary, info, warning, danger;

$default_color: #aaa;
$success_color: #bbb;
$primary_color: #ccc;
$info_color: #ddd;
$warning_color: #eee;
$danger_color: #fff;

@each $b in $buttons {
  .btn-#{$b} {
    color: $#{b}_color;
  }
}
</code>```

答:
The way you are looking doesn't implement in SCSS yet but you can do something like this:

```<code>$default_color: #aaa;
$success_color: #bbb;
$primary_color: #ccc;
$info_color:    #ddd;
$warning_color: #eee;
$danger_color:  #fff;

$buttonsList:
  "default" $default_color,
  "success" $success_color,
  "primary" $primary_color,
  "info"    $info_color,
  "warning" $warning_color,
  "danger"  $danger_color;

@each $b in $buttonsList {
  .btn-#{nth($b, 1)} {
    color: nth($b, 2);
  }
}
</code>```

Sassmeister link.

Body:
How I can use a variable in another variable?
How I can do this:

$buttons: default, success, primary, info, warning, danger;

$default_color: #aaa;
$success_color: #bbb;
$primary_color: #ccc;
$info_color: #ddd;
$warning_color: #eee;
$danger_color: #fff;

@each $b in $buttons {
  .btn-#{$b} {
    color: $#{b}_color;
  }
}

Body:
The way you are looking doesn't implement in SCSS yet but you can do something like this:

$default_color: #aaa;
$success_color: #bbb;
$primary_color: #ccc;
$info_color:    #ddd;
$warning_color: #eee;
$danger_color:  #fff;

$buttonsList:
  "default" $default_color,
  "success" $success_color,
  "primary" $primary_color,
  "info"    $info_color,
  "warning" $warning_color,
  "danger"  $danger_color;

@each $b in $buttonsList {
  .btn-#{nth($b, 1)} {
    color: nth($b, 2);
  }
}

Sassmeister link.


问:
How to list all the items related to a certain category
I want to display all the items related to a certain category when the relevant category name is clicked from the navigation panel.
This is my navigation panel

```<code><ul class="nav navbar-nav">
        <li class="active"><a href="#">Home</a></li>
        <li><%=link_to "About us" ,pages_about_path %></li>
     <li><%=link_to "Contact us" ,pages_contact_path %></li>
        <% @categories.each do |category| %>
                <li><%=link_to category.name,category %><br></li>
        <%end%>
    </ul>
</code>```

This is the code for my show view for categories

```<code><div class="container">
<div class="col-md-12">
    <h1><%= @category.name %></h1>
        <div>
            <% @items.each do |item| %>
                    <div class="col-sm-4">
                        <div class="panel panel-primary">
                            <div class="panel-heading">
                                    <%= link_to item.title,item,class:"btn btn-primary btn-block" %>
                            </div>
                            <div class="panel-body">
                                Quantity  :<%= item.qty %><br>
                                Price  : <%= number_to_currency(item.price, unit: "RS " ) %><br>
                            </div>
                            <div class="panel-footer">
                                <%= link_to "Edit" ,edit_item_path(item) , class: "btn btn-default" %>
                                <%= link_to "Delete" ,item , :confirm => "Are you sure?" , :method => :delete , class: "btn btn-danger"%>
                            <hr>
                            </div>
                        </div>
                    </div>
                <%end%>
</code>```

This is the method at the categories controller.

```<code>def show
  @category =Category.find(params[:id])
  @items = Item.all
end
</code>```

When i use these blocks all the items are being displayed .

This is how the database tables are

```<code>class CreateItems < ActiveRecord::Migration[5.0]
  def change
    create_table :items do |t|
      t.string :title
      t.float :qty
      t.decimal :price
      t.integer :category_id

      t.timestamps
    end
  end
end

class CreateCategories < ActiveRecord::Migration[5.0]
  def change
    create_table :categories do |t|
      t.string :name

      t.timestamps
    end
  end
end
</code>```

答:
Categories Controller show should be changed as below:

```<code>def show
  @category = Category.find(params[:id])
  @items = @category.items #Item.all returns all items irrespective of a category
end
</code>```

Before doing this, make sure there is a has_many and belongs_to association defined in category model and item model,

In Category model (category.rb),

```<code>has_many :items
</code>```

In Item model (item.rb),

```<code>belongs_to :category
</code>```

Body:
I want to display all the items related to a certain category when the relevant category name is clicked from the navigation panel.
This is my navigation panel

Home

<%=link_to "About us" ,pages_about_path %>

<%=link_to "Contact us" ,pages_contact_path %>

        <% @categories.each do |category| %>

<%=link_to category.name,category %>

        <%end%>

This is the code for my show view for categories

<%= @category.name %>

            <% @items.each do |item| %>

                                    <%= link_to item.title,item,class:"btn btn-primary btn-block" %>

                                Quantity  :<%= item.qty %>

                                Price  : <%= number_to_currency(item.price, unit: "RS " ) %>

                                <%= link_to "Edit" ,edit_item_path(item) , class: "btn btn-default" %>
                                <%= link_to "Delete" ,item , :confirm => "Are you sure?" , :method => :delete , class: "btn btn-danger"%>

                <%end%>

This is the method at the categories controller.

def show
  @category =Category.find(params[:id])
  @items = Item.all
end

When i use these blocks all the items are being displayed .

This is how the database tables are

class CreateItems < ActiveRecord::Migration[5.0]
  def change
    create_table :items do |t|
      t.string :title
      t.float :qty
      t.decimal :price
      t.integer :category_id

      t.timestamps
    end
  end
end

class CreateCategories < ActiveRecord::Migration[5.0]
  def change
    create_table :categories do |t|
      t.string :name

      t.timestamps
    end
  end
end

Body:
Categories Controller show should be changed as below:

def show
  @category = Category.find(params[:id])
  @items = @category.items #Item.all returns all items irrespective of a category
end

Before doing this, make sure there is a has_many and belongs_to association defined in category model and item model,

In Category model (category.rb),

has_many :items

In Item model (item.rb),

belongs_to :category


问:
How do I get an event callback when a Tkinter Entry widget is modified?
Exactly as the question says. Text widgets have the <<Modified>> event, but Entry widgets don't appear to.

答:
At the time of writing (2017, Python 3.6, tkinter version 8.6.6) the docs suggest that .trace is deprecated.  The suggested form now seems to be:

```<code>sv.trace_add("write", callback)
</code>```

This works very well if you want notification whenever the variable is changed.  However, my application just wants notification when he user finishes editing the text.  I found piggy-backing on the "validation" mechanism to work well here:

```<code>from tkinter import *

root = Tk()
sv = StringVar()

def callback():
    print(sv.get())
    return True

e = Entry(root, textvariable=sv, validate="focusout", validatecommand=callback)
e.grid()
e = Entry(root)
e.grid()
root.mainloop()
</code>```

This will invoke callback whenever the entry widget loses focus (I added a 2nd entry widget so the 1st one can actually lose focus!)

Body:
At the time of writing (2017, Python 3.6, tkinter version 8.6.6) the docs suggest that .trace is deprecated.  The suggested form now seems to be:

sv.trace_add("write", callback)

This works very well if you want notification whenever the variable is changed.  However, my application just wants notification when he user finishes editing the text.  I found piggy-backing on the "validation" mechanism to work well here:

from tkinter import *

root = Tk()
sv = StringVar()

def callback():
    print(sv.get())
    return True

e = Entry(root, textvariable=sv, validate="focusout", validatecommand=callback)
e.grid()
e = Entry(root)
e.grid()
root.mainloop()

This will invoke callback whenever the entry widget loses focus (I added a 2nd entry widget so the 1st one can actually lose focus!)


问:
Finding the minimum balance given a time frame
What is the best method by which I can calculate the minimum balance given a time frame?  In my database, I have a deposit column and a withdraw column and date column at which they are done.

Update

Suppose on 1/1, the balance is 300.  On 1/2, 300 is deposited with total of 600. On 1/15, 200 is withdrawn leaving a balance of 400. On 1/25, further withdrawal of 300 is made and the balance goes down to 100.  On 1/28, 800 is deposited and balance total to 900.  If on 1/31 I were to calculate the minimum balance for that month, I should get 100.  Any ideas?

答:
Use windowing functions to build the running balance, then extract the minimum out of each time interval like this:

```<code>with cte_transaction_data as
(
    select 300 as deposit, null as withdraw, date '01/02/2010' as transaction_date union all
    select null, 200, date '01/15/2010' union all
    select null, 300, date '01/25/2010' union all
    select 800, null, date '01/28/2010'
)
select
    month,
    min(balance) as minimum_balance
from
    (
        select
            transaction_date,
            date_trunc('month', transaction_date) as month,
            300
            + coalesce(sum(deposit) over(order by transaction_date rows between unbounded preceding and current row), 0)
            - coalesce(sum(withdraw) over(order by transaction_date rows between unbounded preceding and current row), 0) as balance
         from cte_transaction_data
    ) as running_balance
group by
    month
order by
    month```

Result:

```<code>month                   minimum_balance
2010-01-01 00:00:00-06  100```

ContentLicense: CC BY-SA 2.5

Body:
Use windowing functions to build the running balance, then extract the minimum out of each time interval like this:

with cte_transaction_data as
(
    select 300 as deposit, null as withdraw, date '01/02/2010' as transaction_date union all
    select null, 200, date '01/15/2010' union all
    select null, 300, date '01/25/2010' union all
    select 800, null, date '01/28/2010'
)
select
    month,
    min(balance) as minimum_balance
from
    (
        select
            transaction_date,
            date_trunc('month', transaction_date) as month,
            300
            + coalesce(sum(deposit) over(order by transaction_date rows between unbounded preceding and current row), 0)
            - coalesce(sum(withdraw) over(order by transaction_date rows between unbounded preceding and current row), 0) as balance
         from cte_transaction_data
    ) as running_balance
group by
    month
order by
    month

Result:

month                   minimum_balance
2010-01-01 00:00:00-06  100


问:
How do I use Python's map function with sklearn's preprocessing.scale?
I am trying to use a function (preprocessing.scale) on a list of data. I am new to mapreduce/parallelism in Python - I would like to process this on a large list of data to improve performance.

Example:

```<code>X = [1,2,3,4]
</code>```

Using the syntax:

```<code>list(map(preprocessing.scale, X))
</code>```

I get this error:

```<code>TypeError: Singleton array array(1.0) cannot be considered a valid collection.
</code>```

I think that is because of the return type of the function, but I am not sure how to fix this. Any help would be greatly appreciated!

答:
Executing list(map(preprocessing.scale, X)) is equivalent to executing [preprocessing.scale(a) for a in X].

Given this, what you are currently doing is scaling an singleton (one observation). You cannot scale a single item, and that is where the function breaks. Try doing preprocessing.scale(X[0]) and you will get the same error.

What is the purpose for you trying to run it like that and not just pass the array X preprocessing.scale(X)?

Body:
I am trying to use a function (preprocessing.scale) on a list of data. I am new to mapreduce/parallelism in Python - I would like to process this on a large list of data to improve performance.

Example:

X = [1,2,3,4]

Using the syntax:

list(map(preprocessing.scale, X))

I get this error:

TypeError: Singleton array array(1.0) cannot be considered a valid collection.

I think that is because of the return type of the function, but I am not sure how to fix this. Any help would be greatly appreciated!


问:
How to send HTTP Request at intervals and Asynchronously
I've an app with a webview and a uiview showing dynamic content. So I have to keep the uiview content refreshed dynamically with the webserver. I'm new to swift, so I build up this app from a single webview, and the uiview is recently added.

For now I use below stupid code, to keep uiview content sync. Using js do the http request at intervals Asynchronously and call swift code at the same time.

js code,

```<code>$interval(function()
{
    $http.get("http://192.168.1.66/uidata")
        .success(function(response)
        {
            window.webkit.messageHandlers.startLive.postMessage(response.data);
        }
}, 3000);
</code>```

swift code,

```<code>func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
  if(message.name == "startLive") {
    startLive(message.body)
  }
}
</code>```

How can I just use native swift code to do the HTTP Request  at intervals and Asynchronously?

Thank you in advance.

答:
I finally use Timer and URLSession which is asynchrously to make it.</p>

```<code>var timer: Timer?

func startTimer() {

    if timer == nil {
        timer = Timer.scheduledTimer(timeInterval: 3, target: self, selector: #selector(self.loop), userInfo: nil, repeats: true)
    }
}

func stopTimer() {
    if timer != nil {
        timer?.invalidate()
        timer = nil
    }
}

func loop() {
    let liveInfoUrl = URL(string: "http://192.168.1.66/api/cloud/app/liveInfo/7777")
    let task = URLSession.shared.dataTask(with: liveInfoUrl! as URL) {data, response, error in
        guard let data = data, error == nil else { return }
        print(String(data: data, encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) ?? "aaaa")
    }
    task.resume()
}
</code>```

Body:
I've an app with a webview and a uiview showing dynamic content. So I have to keep the uiview content refreshed dynamically with the webserver. I'm new to swift, so I build up this app from a single webview, and the uiview is recently added.

For now I use below stupid code, to keep uiview content sync. Using js do the http request at intervals Asynchronously and call swift code at the same time.

js code,

$interval(function()
{
    $http.get("http://192.168.1.66/uidata")
        .success(function(response)
        {
            window.webkit.messageHandlers.startLive.postMessage(response.data);
        }
}, 3000);

swift code,

func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
  if(message.name == "startLive") {
    startLive(message.body)
  }
}

How can I just use native swift code to do the HTTP Request  at intervals and Asynchronously?

Thank you in advance.

Body:
I finally use Timer and URLSession which is asynchrously to make it.

var timer: Timer?

func startTimer() {

    if timer == nil {
        timer = Timer.scheduledTimer(timeInterval: 3, target: self, selector: #selector(self.loop), userInfo: nil, repeats: true)
    }
}

func stopTimer() {
    if timer != nil {
        timer?.invalidate()
        timer = nil
    }
}

func loop() {
    let liveInfoUrl = URL(string: "http://192.168.1.66/api/cloud/app/liveInfo/7777")
    let task = URLSession.shared.dataTask(with: liveInfoUrl! as URL) {data, response, error in
        guard let data = data, error == nil else { return }
        print(String(data: data, encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) ?? "aaaa")
    }
    task.resume()
}


答:
Sass does not allow variables to be created or accessed dynamically.
Use map instead
http://sass-lang.com/documentation/file.SASS_REFERENCE.html#maps
Example: https://stackoverflow.com/a/17978519</p>

Title: How to use variable in another variable in SCSS


问:
Counting number of pages in tif image file using java
How can i count the number of pages in tiff file? i get it as byte array

Thanks

答:
You can get the number of pages using the Java Advanced Imaging API. I.e. Using:

ImageDecoder.getNumPages()

An example of how to use it can be found here.


问:
Nested Dictionary in iOS Swift
I want to save a data in a dictionary in below format and then have to convert it into json.

```<code>[{"id":"1",
"name":[{"id":"2","name":"k"},{"id":"6","name":"kk"}]",
"pass":"123"},
{"id":"2",
"name":[{"id":"2","name":"k"},{"id":"6","name":"kk"}]",
"pass":"234"}
]
</code>```

It got dictionary and single strings both within a dictionary. Here is what I'm trying, but unable to get the desirable result.

```<code>var myDictionary = Dictionary<String, AnyObject>()
</code>```

答:
```<code>let arrOfData = [["id":"1","pass":"123","name":[["id":"2","name":"k"],["id":"6","name":"kk"]]],
                 ["id":"2","pass":"234","name":[["id":"2","name":"k"],["id":"6","name":"kk"]]]]
</code>```

Here u can see the array of dictionary like Array<Dictionary,AnyObject> if you want to store in a single dictionary you can use it like let dict2 = ["data":arrOfData] Now this will convert into a single dictionary.

Title: Nested Dictionary in iOS Swift

Body:
I want to save a data in a dictionary in below format and then have to convert it into json.

[{"id":"1",
"name":[{"id":"2","name":"k"},{"id":"6","name":"kk"}]",
"pass":"123"},
{"id":"2",
"name":[{"id":"2","name":"k"},{"id":"6","name":"kk"}]",
"pass":"234"}
]

It got dictionary and single strings both within a dictionary. Here is what I'm trying, but unable to get the desirable result.

var myDictionary = Dictionary<String, AnyObject>()

Body:
let arrOfData = [["id":"1","pass":"123","name":[["id":"2","name":"k"],["id":"6","name":"kk"]]],
                 ["id":"2","pass":"234","name":[["id":"2","name":"k"],["id":"6","name":"kk"]]]]

Here u can see the array of dictionary like Array<Dictionary,AnyObject> if you want to store in a single dictionary you can use it like let dict2 = ["data":arrOfData] Now this will convert into a single dictionary.


问:
Specifying range criteria without the use of a structured table
I am working on a table that holds the total amount for products sold or bought in the total column with a reference column that refers to the product id which the total points to.

I need to mark of those products for which the total amount (debit/received) calculates to 0 for each product reference.

For this, I am currently using structured table references to specify the range in my SUMIFS formula like this

```<code>=ROUND(SUMIFS([Total],[Reference],[@Reference]),2)=0
</code>```

Could you please help with how to do the same using the range instead of table references as in

```<code>=ROUND(SUMIFS(AD:AD,AC:AC, ..............),2)=0
</code>```

Please help me on how to write the formula in this case.

答:
You need to enter this at a given row, say row 2:

```<code>=ROUND(SUMIFS(AD:AD,AC:AC,AC2),2)=0
'                          ^^^ The row you type in
</code>```

and then copy/paste in the cells below; the row number will automatically adjust for each row.

Body:
I am working on a table that holds the total amount for products sold or bought in the total column with a reference column that refers to the product id which the total points to.

I need to mark of those products for which the total amount (debit/received) calculates to 0 for each product reference.

For this, I am currently using structured table references to specify the range in my SUMIFS formula like this

=ROUND(SUMIFS([Total],[Reference],[@Reference]),2)=0

Could you please help with how to do the same using the range instead of table references as in

=ROUND(SUMIFS(AD:AD,AC:AC, ..............),2)=0

Please help me on how to write the formula in this case.

Body:
You need to enter this at a given row, say row 2:

=ROUND(SUMIFS(AD:AD,AC:AC,AC2),2)=0
'                          ^^^ The row you type in

and then copy/paste in the cells below; the row number will automatically adjust for each row.


问:
"FILESTREAM Access Level" stuck at disabled
SQL Server "FILESTREAM Access Level" is stuck at disabled. I have checked all ways by SSMS and queries.

After restart, also my configured value is Full Access but Running value is disabled:

Windows 10 Enterprise v1703 Build 15063 Redstone 2

答:
After lots of efforts finally I found the solution to my problem:
1- Computer Management -> Services and Applications -> SQL Server Service -> SQL Server (MSSQLSERVER{Your Instance Name})
2- Change User to an administrator user in Log On tab
3- Enable check check boxes considering your goal from FILESTREAM tab</p>


问:
WCF service without using proxy in C#
I have got a WCF service from one of my users. I want to check whether the service is working or not without adding any proxy. Is there any way that I can achieve this in my C# code?</p>

答:
Try appending ?wsdl at the of the URL pointing to the WCF-service.

If your Web service address is

```<code>http://services.aonaware.com/DictService/DictService.asmx
</code>```

you can reach your wsdl file like this:

```<code>http://services.aonaware.com/DictService/DictService.asmx?WSDL
</code>```

The returned WSDL allows you to see all the method the WCF-service provides.

Title: WCF service without using proxy in C#

Body:
Try appending ?wsdl at the of the URL pointing to the WCF-service.

If your Web service address is

http://services.aonaware.com/DictService/DictService.asmx

you can reach your wsdl file like this:

http://services.aonaware.com/DictService/DictService.asmx?WSDL

The returned WSDL allows you to see all the method the WCF-service provides.


问:
How to validate for checkbox selection if all checkbox have same name?
Hi All
I have a group of check box having same name so as to get the array of single variable when it is posted on serverside for exampleL

```<code><input type="checkbox" name="midlevelusers[]" value="1">
<input type="checkbox" name="midlevelusers[]" value="1">
<input type="checkbox" name="midlevelusers[]" value="1">
<input type="checkbox" name="midlevelusers[]" value="1">
</code>```

I need a javascript validation to check whether any checkbox is selected or not?

Thanks and Regards

NOTE: I need javascript validation

答:
You can access the DOM elements and check their checked property. For instance:

```<code>var list, index, item, checkedCount;

checkedCount = 0;
list = document.getElementsByTagName('input');
for (index = 0; index < list.length; ++index) {
    item = list[index];
    if (item.getAttribute('type') === "checkbox"
        && item.checked
        && item.name === "midlevelusers[]") {
        ++checkedCount;
    }
 }
</code>```

Live example

There we're looking through the whole document, which may not be efficient. If you have a container around these (and presumably you do, a form element), then you can give that element an ID and then look only within it (only the var, form =, and list = lines are new/different):

```<code>var form, list, index, item, checkedCount;

checkedCount = 0;
form = document.getElementById('theForm');
list = form.getElementsByTagName('input');
for (index = 0; index < list.length; ++index) {
    item = list[index];
    if (item.getAttribute('type') === "checkbox"
        && item.checked
        && item.name === "midlevelusers[]") {
        ++checkedCount;
    }
 }
</code>```

Live example

Off-topic: You haven't mentioned using a library, so I haven't used one above, but FWIW this stuff is much easier if you use one like jQuery, Prototype, YUI, Closure, or any of several others. For instance, with jQuery:

```<code>var checkedCount = $("input[type=checkbox][name^=midlevelusers]:checked").length;
</code>```

Live example Other libraries will be similar, though the details will vary.

Body:
Hi All
I have a group of check box having same name so as to get the array of single variable when it is posted on serverside for exampleL

<input type="checkbox" name="midlevelusers[]" value="1">
<input type="checkbox" name="midlevelusers[]" value="1">
<input type="checkbox" name="midlevelusers[]" value="1">
<input type="checkbox" name="midlevelusers[]" value="1">

I need a javascript validation to check whether any checkbox is selected or not?

Thanks and Regards

NOTE: I need javascript validation

Body:
You can access the DOM elements and check their checked property. For instance:

var list, index, item, checkedCount;

checkedCount = 0;
list = document.getElementsByTagName('input');
for (index = 0; index < list.length; ++index) {
    item = list[index];
    if (item.getAttribute('type') === "checkbox"
        && item.checked
        && item.name === "midlevelusers[]") {
        ++checkedCount;
    }
 }

Live example

There we're looking through the whole document, which may not be efficient. If you have a container around these (and presumably you do, a form element), then you can give that element an ID and then look only within it (only the var, form =, and list = lines are new/different):

var form, list, index, item, checkedCount;

checkedCount = 0;
form = document.getElementById('theForm');
list = form.getElementsByTagName('input');
for (index = 0; index < list.length; ++index) {
    item = list[index];
    if (item.getAttribute('type') === "checkbox"
        && item.checked
        && item.name === "midlevelusers[]") {
        ++checkedCount;
    }
 }

Live example

Off-topic: You haven't mentioned using a library, so I haven't used one above, but FWIW this stuff is much easier if you use one like jQuery, Prototype, YUI, Closure, or any of several others. For instance, with jQuery:

var checkedCount = $("input[type=checkbox][name^=midlevelusers]:checked").length;

Live example Other libraries will be similar, though the details will vary.


问:
Run script if selected value is changed
I want to run a PHP script if the value is changed in my dropdown. The PHP script should run an if else statement. Is it possible to run this script, without a form POST?

Here is my dropdown:

```<code><select id="data" name="data" class="select2_single form-control">
  <option value="1">Data 1</option>
  <option value="2">Data 2</option>
</select>
</code>```

Here is the script I want to execute:

```<code><?php
  if($_POST['data'] != '1') {
    echo  'Value 1 is selected';
  }
  if($_POST['data'] != '2') {
    echo 'Value 1 is selected';
  } else {
    echo  'No value selected';
  }
?>
</code>```

答:
Try this js code for change value and handle post data at php end:</p>

```<code>$(document).ready(function() {
  $("#data").change(function() {
    var id=$(this).val();
    $.ajax
    ({
        type: "POST",
        data: 'id='+ id,
        url : "dynamic_select.php",
        success: function(data) {
            //Handle returned data
        }
    });

   });

});
</code>```

Title: Run script if selected value is changed

Body:
I want to run a PHP script if the value is changed in my dropdown. The PHP script should run an if else statement. Is it possible to run this script, without a form POST?

Here is my dropdown:

<select id="data" name="data" class="select2_single form-control">
  <option value="1">Data 1</option>
  <option value="2">Data 2</option>
</select>

Here is the script I want to execute:

<?php
  if($_POST['data'] != '1') {
    echo  'Value 1 is selected';
  }
  if($_POST['data'] != '2') {
    echo 'Value 1 is selected';
  } else {
    echo  'No value selected';
  }
?>

Body:
Try this js code for change value and handle post data at php end:

$(document).ready(function() {
  $("#data").change(function() {
    var id=$(this).val();
    $.ajax
    ({
        type: "POST",
        data: 'id='+ id,
        url : "dynamic_select.php",
        success: function(data) {
            //Handle returned data
        }
    });

   });

});