问:
Failed to start video surface due to main thread blocked error in QML
I wrote a sample QML- qt5 application for webcam display giving an Error :
OS:UBUNTU 13.04
Qt Creator 2.7.1 Based on Qt 5.0.2 (64 bit)

```<code>Failed to start video surface due to main thread blocked.
Failed to start video surface
CameraBin error: "Internal data flow error."
</code>```

PS: This error occurs randomly and most of the times; let say 18-19 times in 20 times

Here is the code :

```<code>import QtQuick 2.0
import QtMultimedia 5.0

Item {
width: 320
height: 240

VideoOutput {
    id:camOutput
    source: camera
    anchors.fill: parent
    focus : visible // to receive focus and capture key events when visible

}

Camera {
    id: camera

    imageProcessing.whiteBalanceMode: CameraImageProcessing.WhiteBalanceFlash

    exposure {
        exposureCompensation: -1.0
        exposureMode: Camera.ExposurePortrait
    }

    flash.mode: Camera.FlashRedEyeReduction

    imageCapture {
        onImageCaptured: {
            photoPreview.source = preview  // Show the preview in an Image
        }
    }

}
Image {
    id: photoPreview
}
}
</code>```

答:
That is a bug in Qt- see QTBUG-39567.

When writing this post (June 2017) there is no actual solution, but workaround is suggested:

Do not play video immediately when starting your app- wait one second on more before starting your video player.

I have tested this and it fixed my problem with playing video.

In your case this is not a video player but in my opinion this is related to all QtMultimedia components.

Body:
I wrote a sample QML- qt5 application for webcam display giving an Error :
OS:UBUNTU 13.04
Qt Creator 2.7.1 Based on Qt 5.0.2 (64 bit)

Failed to start video surface due to main thread blocked.
Failed to start video surface
CameraBin error: "Internal data flow error."

PS: This error occurs randomly and most of the times; let say 18-19 times in 20 times

Here is the code :

import QtQuick 2.0
import QtMultimedia 5.0

Item {
width: 320
height: 240

VideoOutput {
    id:camOutput
    source: camera
    anchors.fill: parent
    focus : visible // to receive focus and capture key events when visible

}

Camera {
    id: camera

    imageProcessing.whiteBalanceMode: CameraImageProcessing.WhiteBalanceFlash

    exposure {
        exposureCompensation: -1.0
        exposureMode: Camera.ExposurePortrait
    }

    flash.mode: Camera.FlashRedEyeReduction

    imageCapture {
        onImageCaptured: {
            photoPreview.source = preview  // Show the preview in an Image
        }
    }

}
Image {
    id: photoPreview
}
}


来源: stackexchange

问:
Div moving only once
I'm trying to make a simple application via Intel XDK. I made this button but it moves down only once after loading the page / application. I would be very grateful if somebody would advise me. Thanks in advance.

Code:

function buttonClick() {
    //alert('Thanks for using our app!!!');
    document.getElementById('button').style.boxShadow = "none";
    document.getElementById('button').style.top += "10px";
    setTimeout(function(){
      document.getElementById('button').style.top = "-10px";
        document.getElementById('button').style.boxShadow = "0px 5px 10px #3a926d";
        }, 500);
    }

function onLoad() {
    intel.xdk.device.setRotateOrientation("portrait");
}

document.addEventListener("intel.xdk.device.ready", onDeviceReady, false);
function onDeviceReady(){
    // set orientation

    intel.xdk.device.setRotateOrientation('portrait');
//    intel.xdk.device.setRotateOrientation('any');

    intel.xdk.device.hideSplashScreen();
} ```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#button {
    background-color: #29c786;
    padding: 10px;
    width: 55%;
    height: 30px;
    line-height: 30px;
    text-align: center;
    margin-top: 0;
    color: white;
    position:absolute; /*it can be fixed too*/
    left:0; right:0;
    top:0; bottom:0;
    margin:auto;
    box-shadow: 0px 5px 10px #3a926d;
    border-radius: 5px;
}

footer {
    font-size: 8;
    position: absolute;
    bottom: 5px;
    left: 5px;
}</code>```

OPEN GALLERY

VERSION 0.1; © Tomas Hobza 2017```

答:
function buttonClick() {
        //alert('Thanks for using our app!!!');
        document.getElementById('button').style.boxShadow = "none";
        document.getElementById('button').style.top = "10px";
        setTimeout(function(){
         document.getElementById('button').style.top = "-10px";
            document.getElementById('button').style.boxShadow = "0px 5px 10px #3a926d";
        }, 500);
    }```
<pre class="snippet-code-css lang-css prettyprint-override"><code> #button {
        background-color: #29c786;
        padding: 10px;
        width: 55%;
        height: 30px;
        line-height: 30px;
        text-align: center;
        margin-top: 0;
        color: white;
        position:absolute; /*it can be fixed too*/
        left:0; right:0;
        top:0; bottom:0;
        margin:auto;
        box-shadow: 0px 5px 10px #3a926d;
        border-radius: 5px;
    }

    footer {
        font-size: 8;
        position: absolute;
        bottom: 5px;
        left: 5px;
    }</code>```

OPEN GALLERY
```
</div>
</div>
</p>

<p>Change:</p>

```document.getElementById('button').style.top += "10px";
```

<p>To</p>

```document.getElementById('button').style.top = "10px";
```

ContentLicense: CC BY-SA 3.0

Title: Div moving only once

Body:
I'm trying to make a simple application via Intel XDK. I made this button but it moves down only once after loading the page / application. I would be very grateful if somebody would advise me. Thanks in advance.

Code:

function buttonClick() {
    //alert('Thanks for using our app!!!');
    document.getElementById('button').style.boxShadow = "none";
    document.getElementById('button').style.top += "10px";
    setTimeout(function(){
      document.getElementById('button').style.top = "-10px";
        document.getElementById('button').style.boxShadow = "0px 5px 10px #3a926d";
        }, 500);
    }

function onLoad() {
    intel.xdk.device.setRotateOrientation("portrait");
}

document.addEventListener("intel.xdk.device.ready", onDeviceReady, false);
function onDeviceReady(){
    // set orientation

    intel.xdk.device.setRotateOrientation('portrait');
//    intel.xdk.device.setRotateOrientation('any');

    intel.xdk.device.hideSplashScreen();
}

#button {
    background-color: #29c786;
    padding: 10px;
    width: 55%;
    height: 30px;
    line-height: 30px;
    text-align: center;
    margin-top: 0;
    color: white;
    position:absolute; /*it can be fixed too*/
    left:0; right:0;
    top:0; bottom:0;
    margin:auto;
    box-shadow: 0px 5px 10px #3a926d;
    border-radius: 5px;
}

footer {
    font-size: 8;
    position: absolute;
    bottom: 5px;
    left: 5px;
}

OPEN GALLERY

VERSION 0.1; © Tomas Hobza 2017

Body:
function buttonClick() {
        //alert('Thanks for using our app!!!');
        document.getElementById('button').style.boxShadow = "none";
        document.getElementById('button').style.top = "10px";
        setTimeout(function(){
         document.getElementById('button').style.top = "-10px";
            document.getElementById('button').style.boxShadow = "0px 5px 10px #3a926d";
        }, 500);
    }

 #button {
        background-color: #29c786;
        padding: 10px;
        width: 55%;
        height: 30px;
        line-height: 30px;
        text-align: center;
        margin-top: 0;
        color: white;
        position:absolute; /*it can be fixed too*/
        left:0; right:0;
        top:0; bottom:0;
        margin:auto;
        box-shadow: 0px 5px 10px #3a926d;
        border-radius: 5px;
    }

    footer {
        font-size: 8;
        position: absolute;
        bottom: 5px;
        left: 5px;
    }

<div id="button" onClick="buttonClick()"><b>OPEN GALLERY</b></div>

Change:

document.getElementById('button').style.top += "10px";

To

document.getElementById('button').style.top = "10px";


问:
Difference between Container and ContainerBuilder in Symfony
I'm trying to understand the Symfony core, but I'm not not completely sure about some things happening in the DI component.

What is the difference between the Container and the ContainerBuilder? The name would suggest that the ContainerBuilder is used to build a Container object, but regarding the docs it can be directly instantiated and used as a container:

```<code>$container = new ContainerBuilder();
$container->register('mailer', 'Mailer');
</code>```

Why not use $container = new Container() here?

答:
The answer is in the very class-definition of ContainerBuilder:

Symfony/Component/DependencyInjection/ContainerBuilder.php:

```<code>class ContainerBuilder extends Container implements TaggedContainerInterface
</code>```

So, ContainerBuilder is basically a Container, it just adds some functionality. For example Container does not have a register method like you gave in your example.

Body:
I'm trying to understand the Symfony core, but I'm not not completely sure about some things happening in the DI component.

What is the difference between the Container and the ContainerBuilder? The name would suggest that the ContainerBuilder is used to build a Container object, but regarding the docs it can be directly instantiated and used as a container:

$container = new ContainerBuilder();
$container->register('mailer', 'Mailer');

Why not use $container = new Container() here?

Body:
The answer is in the very class-definition of ContainerBuilder:

Symfony/Component/DependencyInjection/ContainerBuilder.php:

class ContainerBuilder extends Container implements TaggedContainerInterface

So, ContainerBuilder is basically a Container, it just adds some functionality. For example Container does not have a register method like you gave in your example.


问:
Search keyword using double quotes to get exact match in elasticsearch
If user searches by giving quotes around keyword like "flowers and mulch" then exact matches should be displayed.

I tried using query_string which is almost working but not satisfied with those results.

Can anyone help me out please.

```<code>{
    "query": {
        "query_string": {
           "fields": ["body"],
           "query": "\"flowers and mulch\""
        }
    }
}
</code>```

答:
As I put in the comment of the question, I think knowing what the OP found not satisfying about query_string would be great. I would recommend using query_string for these cases. Note that there are multiple options that could be set, such as: auto_generate_phrase_queries, split_on_whitespace, or quote_field_suffix (example: here), which makes it quite versatile.

The case one "two three"could be addressed using default parameters of query_string

Body:
If user searches by giving quotes around keyword like "flowers and mulch" then exact matches should be displayed.

I tried using query_string which is almost working but not satisfied with those results.

Can anyone help me out please.

{
    "query": {
        "query_string": {
           "fields": ["body"],
           "query": "\"flowers and mulch\""
        }
    }
}


问:
Firebase DB Architecting: filter based on two criteria, favorites and location
In my iOS app I'm using Firebase Realtime Database and I have the following models: Users and Venues.

So Users can favorite a Venue. What I want to do is be able to see all the Venues around me that people I follow have favorited. My main issue is I could generate a ‘favoritedFeed’ similar to how FriendlyPix does it, but I really need to consider the distance I am away from the venues and exclude ones that are too far.

Would it be beneficial to just build a ‘favoritedFeed’ of all the venues people I follow favorite, and then filter that feed by distance on the client side? Also I would like to paginate the feed if possible, but if I take this approach, that might not be possible.

I’ll draw my JSON tree, maybe that should be restructured.

```<code>users
   [user_id]
      …
      comments
         [comment_id]  = true
      favorites
         [venue_id] = true
comments
   [comment_id]
      user = [user_id]
      comment = “…..”
venues
  [venue_id]
      ...
      favorites
         [user_id] = true
</code>```

Right now I just iterate over all of the Users a user follows and then fetch their comments. That way doesn’t scale very well, but its the only way I can figure out how to get the comments at the moment.

答:
So there are a few different sound approaches you can play with. Depending on your use case, any of them might be the most optimized solution.

Store favorites in the venues and query there

Pros: Very simple to implement and effective to high volumes.

Cons: Might slow down if you have tens of thousands of favorites on each of tens of thousands of venues and have each client performing a very large number of queries against this list. That's probably an edge case though, and you can start here and easily adapt to other models as your app grows.

This approach would use a data structure similar to this:

```<code>venues/$venueid/favoritedby/$userid/<true>
venues/$venueid/meta/<detailed data about the venue could be stored here>
users/$userid/myfriends/$userid/<any data or just a true value here>
</code>```

Now fetching a list of venues requires that I do two things: Find venues favorited by my friends, and filter those based on proximity. I'll cover the proximity separately below and focus on how you get your friends' favorites here.

```<code>const ref = firebase.database().ref();
getMyFriends("kato")
  .then(getFavoritesOfMyFriends)
  .then(favorites => console.log(favorites));

function getMyFriends(myUserId) {
  // find everyone I've marked as a friend
  return ref.child(`users/${myUserId}/myfriends`)
    .once('value').then(snap => {
      // return the uids of my friends as an array
      return Object.keys( snap.val() || {} );
    });
}

function getFavoritesOfFriends(myListOfFriends) {
  const promises = [];
  // fetch favorites for each of my friends in parallel
  // and merge them into one object, data will be deduped
  // implicitly since we are storing in a hash
  let mergedFavorites = {};
  myListOfFriends.forEach(uid => {
    promises.push(
      getFavorites(uid)
        .then(favs => mergeInto(mergedFavorites, favs))
    );
  });
  return Promise.all(promises).then(() => mergedFavorites);
}

function getFavorites(uid) {
  // fetch directly from venues
  return ref.child('venues')
    // but only get items favorited by this uid
    .orderByChild(`favoritedby/${uid}`).equalTo(true)
    .once('value')
    // extract the data from snapshot before returning
    .then(snap => snap.val() || {});
}

function mergeInto(dest, newData) {
  Object.keys(newData).forEach(k => dest[k] = newData[k]);
  return dest;
}
</code>```

Use a flattened approach

Pros: highly flexible and works with millions of favorites at no real performance penalty

Cons: a bit more complex to implement--quite a bit of hoop-jumping to grab all the data

This approach would use a data structure similar to this:

```<code>venues/$venueid/<detailed data about the venue is stored here>
users/$userid/myfriends/$userid/<any data or just a true value here>
favorites/$userid/$venueid/<any data or just a true value here>
</code>```

Now I can grab my list of friends, and find all their favorite venue ids with something like the following. Then I can look up the individual venues to get names/et al or filter that according to my location.

```<code>const ref = firebase.database().ref();

getMyFriends("kato").then(getFavoritesOfMyFriends).then(favorites => console.log(favorites));

function getMyFriends(myUserId) {
  // find everyone I've marked as a friend
  return ref.child(`users/${myUserId}/myfriends`).once('value').then(snap => {
    // return the uids of my friends as an array
    return Object.keys( snap.val() || {} );
  });
}

function getFavoritesOfFriends(myListOfFriends) {
  const promises = [];
  // fetch favorites for each of my friends in parallel
  // and merge them into one object, data will be deduped
  // implicitly since we are storing in a hash
  let mergedVenues = {};
  myListOfFriends.forEach(uid => {
    promises.push(
      getFavorites(uid)
        .then(getVenuesByKey)
        .then(venues => mergeInto(mergedVenues, venues))
    );
  });
  return Promise.all(promises).then(() => mergedVenues);
}

function getFavorites(uid) {
  return ref.child(`favorites/${uid}`).once('value').then(snap => {
    return Object.keys(snap.val()||{});
  });
}

function getVenuesByKey(listOfKeys) {
  const promises = [];
  const venues = {};
  listOfKeys.forEach(venueId => {
    promises.push(
      getVenue(venueId)
        // add each entry to venues asynchronously
        .then(v => venues[venueId] = v)
    );
  });
  // Wait for all items to load then return the compiled list
  return Promise.all(promises).then(() => venues);
}

function getVenue(venueId) {
  return ref.child(`venues/${venueId}`).then(snap => snap.val() || {});
}

function mergeInto(dest, newData) {
  Object.keys(newData).forEach(k => dest[k] = newData[k]);
  return dest;
}
</code>```

For massive scale

Mostly for others reading this, and for posterity: Note that if you're running a twitter-like feed where a celebrity might have a million followers or similar scenarios, and you really need scale here, you would probably integrate Functions and use them similar to a stored procedure, actually writing duplicate information about the favorite venues out to each follow follower's "feed" for improved scale. But again, you don't need this in most apps, so you can keep it simple.

This is by far the most complex and scalable--it gets hairy when you start editing and changing venue data and has lots of edge cases. Highly recommend becoming intimate with NoSQL data structures before trying something like this.

Filtering by geo

I'd play with these to see how to filter data best locally, but I suspect that you'll end up with something like this:

Grab the list of venues close to me (see GeoFire)

Grab the favorites of my friends

Do something like venuesCloseToMe.some(key => return favoritesOfMyFriends.indexOf(key) > -1);

Now fetch those venues by key for display on the client

Body:
In my iOS app I'm using Firebase Realtime Database and I have the following models: Users and Venues.

So Users can favorite a Venue. What I want to do is be able to see all the Venues around me that people I follow have favorited. My main issue is I could generate a ‘favoritedFeed’ similar to how FriendlyPix does it, but I really need to consider the distance I am away from the venues and exclude ones that are too far.

Would it be beneficial to just build a ‘favoritedFeed’ of all the venues people I follow favorite, and then filter that feed by distance on the client side? Also I would like to paginate the feed if possible, but if I take this approach, that might not be possible.

I’ll draw my JSON tree, maybe that should be restructured.

users
   [user_id]
      …
      comments
         [comment_id]  = true
      favorites
         [venue_id] = true
comments
   [comment_id]
      user = [user_id]
      comment = “…..”
venues
  [venue_id]
      ...
      favorites
         [user_id] = true

Right now I just iterate over all of the Users a user follows and then fetch their comments. That way doesn’t scale very well, but its the only way I can figure out how to get the comments at the moment.

Body:
So there are a few different sound approaches you can play with. Depending on your use case, any of them might be the most optimized solution.

Store favorites in the venues and query there

Pros: Very simple to implement and effective to high volumes.

Cons: Might slow down if you have tens of thousands of favorites on each of tens of thousands of venues and have each client performing a very large number of queries against this list. That's probably an edge case though, and you can start here and easily adapt to other models as your app grows.

This approach would use a data structure similar to this:

venues/$venueid/favoritedby/$userid/<true>
venues/$venueid/meta/<detailed data about the venue could be stored here>
users/$userid/myfriends/$userid/<any data or just a true value here>

Now fetching a list of venues requires that I do two things: Find venues favorited by my friends, and filter those based on proximity. I'll cover the proximity separately below and focus on how you get your friends' favorites here.

const ref = firebase.database().ref();
getMyFriends("kato")
  .then(getFavoritesOfMyFriends)
  .then(favorites => console.log(favorites));

function getMyFriends(myUserId) {
  // find everyone I've marked as a friend
  return ref.child(`users/${myUserId}/myfriends`)
    .once('value').then(snap => {
      // return the uids of my friends as an array
      return Object.keys( snap.val() || {} );
    });
}

function getFavoritesOfFriends(myListOfFriends) {
  const promises = [];
  // fetch favorites for each of my friends in parallel
  // and merge them into one object, data will be deduped
  // implicitly since we are storing in a hash
  let mergedFavorites = {};
  myListOfFriends.forEach(uid => {
    promises.push(
      getFavorites(uid)
        .then(favs => mergeInto(mergedFavorites, favs))
    );
  });
  return Promise.all(promises).then(() => mergedFavorites);
}

function getFavorites(uid) {
  // fetch directly from venues
  return ref.child('venues')
    // but only get items favorited by this uid
    .orderByChild(`favoritedby/${uid}`).equalTo(true)
    .once('value')
    // extract the data from snapshot before returning
    .then(snap => snap.val() || {});
}

function mergeInto(dest, newData) {
  Object.keys(newData).forEach(k => dest[k] = newData[k]);
  return dest;
}

Use a flattened approach

Pros: highly flexible and works with millions of favorites at no real performance penalty

Cons: a bit more complex to implement--quite a bit of hoop-jumping to grab all the data

This approach would use a data structure similar to this:

venues/$venueid/<detailed data about the venue is stored here>
users/$userid/myfriends/$userid/<any data or just a true value here>
favorites/$userid/$venueid/<any data or just a true value here>

Now I can grab my list of friends, and find all their favorite venue ids with something like the following. Then I can look up the individual venues to get names/et al or filter that according to my location.

const ref = firebase.database().ref();

getMyFriends("kato").then(getFavoritesOfMyFriends).then(favorites => console.log(favorites));

function getMyFriends(myUserId) {
  // find everyone I've marked as a friend
  return ref.child(`users/${myUserId}/myfriends`).once('value').then(snap => {
    // return the uids of my friends as an array
    return Object.keys( snap.val() || {} );
  });
}

function getFavoritesOfFriends(myListOfFriends) {
  const promises = [];
  // fetch favorites for each of my friends in parallel
  // and merge them into one object, data will be deduped
  // implicitly since we are storing in a hash
  let mergedVenues = {};
  myListOfFriends.forEach(uid => {
    promises.push(
      getFavorites(uid)
        .then(getVenuesByKey)
        .then(venues => mergeInto(mergedVenues, venues))
    );
  });
  return Promise.all(promises).then(() => mergedVenues);
}

function getFavorites(uid) {
  return ref.child(`favorites/${uid}`).once('value').then(snap => {
    return Object.keys(snap.val()||{});
  });
}

function getVenuesByKey(listOfKeys) {
  const promises = [];
  const venues = {};
  listOfKeys.forEach(venueId => {
    promises.push(
      getVenue(venueId)
        // add each entry to venues asynchronously
        .then(v => venues[venueId] = v)
    );
  });
  // Wait for all items to load then return the compiled list
  return Promise.all(promises).then(() => venues);
}

function getVenue(venueId) {
  return ref.child(`venues/${venueId}`).then(snap => snap.val() || {});
}

function mergeInto(dest, newData) {
  Object.keys(newData).forEach(k => dest[k] = newData[k]);
  return dest;
}

For massive scale

Mostly for others reading this, and for posterity: Note that if you're running a twitter-like feed where a celebrity might have a million followers or similar scenarios, and you really need scale here, you would probably integrate Functions and use them similar to a stored procedure, actually writing duplicate information about the favorite venues out to each follow follower's "feed" for improved scale. But again, you don't need this in most apps, so you can keep it simple.

This is by far the most complex and scalable--it gets hairy when you start editing and changing venue data and has lots of edge cases. Highly recommend becoming intimate with NoSQL data structures before trying something like this.

Filtering by geo

I'd play with these to see how to filter data best locally, but I suspect that you'll end up with something like this:

Grab the list of venues close to me (see GeoFire)

Grab the favorites of my friends

Do something like venuesCloseToMe.some(key => return favoritesOfMyFriends.indexOf(key) > -1);

Now fetch those venues by key for display on the client


问:
How can I change the color of the JFXHamburger
I use the JFoenix Libary to develop a program with JavaFX.
The default color of the JFXHamburger is black but I need white.
I use the SceneBuilder to design the program but I can not find any property where I can change the color.

Does anyone know how I can do this?

TIA.

答:
This might help: How to change the color of the hamburger icon

Or this, to change the background: Change Pane Background


问:
how can I store my data in a global variable?
```<code>$(function(){

    var astronautsData;

    $.getJSON('http://api.open-notify.org/astros.json', doSomething);

    function doSomething(data) {
        astronautsData = data;
    }

    alert(astronautsData.people[0].name)

});
</code>```

I would like to be able to use the data in every function I make, that's why I tried to put it in the variable astronautsData, but unfortunately astronautsdata is undefined.

答:
Your .getJSON is asynchronous.

Try using a Promise to wait for your call to be done :

```<code>prom = new Promise((resolve, reject) => {
  $.getJSON('http://api.open-notify.org/astros.json', function(){
    astronautsData = data;
    resolve('Ajax done');
  });
});

prom.then((successMessage) => {
  console.log(successMessage);
  alert(astronautsData.people[0].name)
});
</code>```

Body:
$(function(){

    var astronautsData;

    $.getJSON('http://api.open-notify.org/astros.json', doSomething);

    function doSomething(data) {
        astronautsData = data;
    }

    alert(astronautsData.people[0].name)

});

I would like to be able to use the data in every function I make, that's why I tried to put it in the variable astronautsData, but unfortunately astronautsdata is undefined.

Body:
Your .getJSON is asynchronous.

Try using a Promise to wait for your call to be done :

prom = new Promise((resolve, reject) => {
  $.getJSON('http://api.open-notify.org/astros.json', function(){
    astronautsData = data;
    resolve('Ajax done');
  });
});

prom.then((successMessage) => {
  console.log(successMessage);
  alert(astronautsData.people[0].name)
});


问:
Regex replace name(<keepAnythingHere>) by <kept>.name
I have a hundred lines with code like

```<code>name(budget)
name(order)
...
</code>```

I would like to replace it all and have

```<code>budget.name
order.name
...
</code>```

Anyway to do this?

答:
Find by: (name)\((.*)\)

Replace with groups: ($2).($1)

Body:
I have a hundred lines with code like

name(budget)
name(order)
...

I would like to replace it all and have

budget.name
order.name
...

Anyway to do this?


问:
SQL : How to use “and” and “or” in a “Where” clause with "NOT IN" conditions
I have a query that should return me all users out of the special area. If i had areas, the result still the same

```<code>SELECT users.id AS id, SUBSTRING(users.zipcode, 1, 2)
FROM users JOIN country ON users.country_id = country.country_id
WHERE country.country_code NOT IN ('AD','AF','BE')
OR (country.country_code = 'FR' AND SUBSTRING(users.zipcode, 1, 2)
NOT IN (69,38,26,07,42))
</code>```

id | user_zipcode | country_code

1  | 38           | FR

1  | 69           | BE

I don't want all users with country_code 'AD','AF','BE' but if country_code is "FR" i don't want only those with the user_zipcode's 69,38,26,07,42

答:
Exclude Andora, Afghanistan, Belgium and some French departments:</p>

```<code>WHERE country.country_code NOT IN ('AD','AF','BE')
AND NOT (
    country.country_code = 'FR' AND
    SUBSTRING(users.zipcode, 1, 2) IN (69,38,26,07,42)
)
</code>```

Body:
I have a query that should return me all users out of the special area. If i had areas, the result still the same

SELECT users.id AS id, SUBSTRING(users.zipcode, 1, 2)
FROM users JOIN country ON users.country_id = country.country_id
WHERE country.country_code NOT IN ('AD','AF','BE')
OR (country.country_code = 'FR' AND SUBSTRING(users.zipcode, 1, 2)
NOT IN (69,38,26,07,42))

id | user_zipcode | country_code

1  | 38           | FR

1  | 69           | BE

I don't want all users with country_code 'AD','AF','BE' but if country_code is "FR" i don't want only those with the user_zipcode's 69,38,26,07,42

Body:
Exclude Andora, Afghanistan, Belgium and some French departments:

WHERE country.country_code NOT IN ('AD','AF','BE')
AND NOT (
    country.country_code = 'FR' AND
    SUBSTRING(users.zipcode, 1, 2) IN (69,38,26,07,42)
)


问:
how to perform pagination in List inside a model in mvc razor
I have a model like:

```<code>public class Customer
{
    public string Name { get; set; }
    public string Address { get; set; }
    public List<Contacts> ContactList { get; set; }
}
public class Contacts
{
    public string Name { get; set; }
    public string Phone { get; set; }
}
</code>```

Now in razor view, if we call the model like

```<code>@model MvcApp.Models.Customer
</code>```

how to perform paging operation on ContactList that is inside the Customer model using PagedList or something.

Any help ?

Thanks in advance

答:
If you want easy client side pagination then https://datatables.net/ would be your best option. Put Contacts into PartialView, make list displayed as table, apply datatables module, and it should look good.  If you want to use IPagedList then you would have to reload view every time when user clicks new page, because IPageList return one page at the time, and use of it on client side is not very good practice. However if you are ready to server calls:

```<code>public class Customer
{
    public string Name { get; set; }
    public string Address { get; set; }
    public IPageList<Contacts> ContactList { get; set; }
}
</code>```

Just load ContactList with page data on Server side every time when user clicks page.

Body:
I have a model like:

public class Customer
{
    public string Name { get; set; }
    public string Address { get; set; }
    public List<Contacts> ContactList { get; set; }
}
public class Contacts
{
    public string Name { get; set; }
    public string Phone { get; set; }
}

Now in razor view, if we call the model like

@model MvcApp.Models.Customer

how to perform paging operation on ContactList that is inside the Customer model using PagedList or something.

Any help ?

Thanks in advance

Body:
If you want easy client side pagination then https://datatables.net/ would be your best option. Put Contacts into PartialView, make list displayed as table, apply datatables module, and it should look good.  If you want to use IPagedList then you would have to reload view every time when user clicks new page, because IPageList return one page at the time, and use of it on client side is not very good practice. However if you are ready to server calls:

public class Customer
{
    public string Name { get; set; }
    public string Address { get; set; }
    public IPageList<Contacts> ContactList { get; set; }
}

Just load ContactList with page data on Server side every time when user clicks page.


问:
Adding a separator (a
 or a row separator) every 3

I'm building a site that get a JSON data and populates the site, so I get an unknown numbers of items, this items are on columns of 3, I would like that after each row to have a a nice looking line.

When it was static content what I did was:

```<code><ul>
  <li></li>
  <li></li>
  <li></li>
  <div class="separator"></div>
  <li></li>
  <li></li>
  <li></li>
  <div class="separator"></div>
</ul>
</code>```

but now that i get the dynamic content i dont know how to manage it.

答:
You can simply use the :nth-child-CSS-selector:

li:nth-child(3n) {
  /* replace with whatever style you have for the seperators */
  border-bottom:1px solid #999;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
  <li>6</li>
</ul></code>```

Title: Adding a separator (a <div> or a row separator) every 3 <li>

Body:
I'm building a site that get a JSON data and populates the site, so I get an unknown numbers of items, this items are on columns of 3, I would like that after each row to have a a nice looking line.

When it was static content what I did was:

but now that i get the dynamic content i dont know how to manage it.

Body:
You can simply use the :nth-child-CSS-selector:

li:nth-child(3n) {
  /* replace with whatever style you have for the seperators */
  border-bottom:1px solid #999;
}

<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
  <li>6</li>
</ul>


问:
Numpy delete rows of array inside object array
I am trying to delete rows from arrays which are stored inside an object array in numpy. However as you can see it complains that it cannot broadcast the smaller array into the larger array. Works fine when done directly to the array. What is the issue here? Any clean way around this error other than making a new object array and copying one by one until the array I want to modify?

```<code>In [1]: import numpy as np

In [2]: x = np.zeros((3, 2))

In [3]: x = np.delete(x, 1, axis=0)

In [4]: x
Out[4]:
array([[ 0.,  0.],
       [ 0.,  0.]])

In [5]: x = np.array([np.zeros((3, 2)), np.zeros((3, 2))], dtype=object)

In [6]: x[0] = np.delete(x[0], 1, axis=0)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-6-1687d284d03c> in <module>()
----> 1 x[0] = np.delete(x[0], 1, axis=0)

ValueError: could not broadcast input array from shape (2,2) into shape (3,2)
</code>```

Edit: Apparently it works when arrays are different shape. This is quite annoying. Any way to disable automatic concatenation by np.array?

```<code>In [12]: x = np.array([np.zeros((3, 2)), np.zeros((5, 8))], dtype=object)

In [13]: x[0] = np.delete(x[0], 1, axis=0)

In [14]: x = np.array([np.zeros((3, 2)), np.zeros((3, 2))], dtype=object)

In [15]: x.shape
Out[15]: (2, 3, 2)

In [16]: x = np.array([np.zeros((3, 2)), np.zeros((5, 8))], dtype=object)

In [17]: x.shape
Out[17]: (2,)
</code>```

This is some quite inconsistent behaviour.

答:
This is very hacky and ugly in my opinion but it's the only solution I could think of. Use list comprehension to convert object array to list (using .tolist() does not work as it breaks the subarrays into lists), modifying the element and converting back to object array.

```<code>In [37]: x = np.array([np.zeros((3, 2)), np.zeros((3, 2))], dtype=object)

In [38]: xx = [z for z in x]

In [39]: xx[0] = np.delete(xx[0], 1, axis=0)

In [40]: x = np.array(xx, dtype=object)

In [41]: x
Out[41]:
array([array([[0.0, 0.0],
       [0.0, 0.0]], dtype=object),
       array([[0.0, 0.0],
       [0.0, 0.0],
       [0.0, 0.0]], dtype=object)], dtype=object)
</code>```

I think I'll post an issue on the numpy github for consistent behavior of object arrays

Body:
I am trying to delete rows from arrays which are stored inside an object array in numpy. However as you can see it complains that it cannot broadcast the smaller array into the larger array. Works fine when done directly to the array. What is the issue here? Any clean way around this error other than making a new object array and copying one by one until the array I want to modify?

In [1]: import numpy as np

In [2]: x = np.zeros((3, 2))

In [3]: x = np.delete(x, 1, axis=0)

In [4]: x
Out[4]:
array([[ 0.,  0.],
       [ 0.,  0.]])

In [5]: x = np.array([np.zeros((3, 2)), np.zeros((3, 2))], dtype=object)

In [6]: x[0] = np.delete(x[0], 1, axis=0)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-6-1687d284d03c> in <module>()
----> 1 x[0] = np.delete(x[0], 1, axis=0)

ValueError: could not broadcast input array from shape (2,2) into shape (3,2)

Edit: Apparently it works when arrays are different shape. This is quite annoying. Any way to disable automatic concatenation by np.array?

In [12]: x = np.array([np.zeros((3, 2)), np.zeros((5, 8))], dtype=object)

In [13]: x[0] = np.delete(x[0], 1, axis=0)

In [14]: x = np.array([np.zeros((3, 2)), np.zeros((3, 2))], dtype=object)

In [15]: x.shape
Out[15]: (2, 3, 2)

In [16]: x = np.array([np.zeros((3, 2)), np.zeros((5, 8))], dtype=object)

In [17]: x.shape
Out[17]: (2,)

This is some quite inconsistent behaviour.

Body:
This is very hacky and ugly in my opinion but it's the only solution I could think of. Use list comprehension to convert object array to list (using .tolist() does not work as it breaks the subarrays into lists), modifying the element and converting back to object array.

In [37]: x = np.array([np.zeros((3, 2)), np.zeros((3, 2))], dtype=object)

In [38]: xx = [z for z in x]

In [39]: xx[0] = np.delete(xx[0], 1, axis=0)

In [40]: x = np.array(xx, dtype=object)

In [41]: x
Out[41]:
array([array([[0.0, 0.0],
       [0.0, 0.0]], dtype=object),
       array([[0.0, 0.0],
       [0.0, 0.0],
       [0.0, 0.0]], dtype=object)], dtype=object)

I think I'll post an issue on the numpy github for consistent behavior of object arrays


问:
LINQ to SQL: Reusing DataContext
I have a number of static methods that perform simple operations like insert or delete a record. All these methods follow this template of using:

```<code>public static UserDataModel FromEmail(string email)
{
    using (var db = new MyWebAppDataContext())
    {
        db.ObjectTrackingEnabled = false;
        return (from u in db.UserDataModels
                where u.Email == email
                select u).Single();
    }
}
</code>```

I also have a few methods that need to perform multiple operations that use a DataContext:

```<code>public static UserPreferencesDataModel Preferences(string email)
{
    return UserDataModel.Preferences(UserDataModel.FromEmail(email));
}

private static UserPreferencesViewModel Preferences(UserDataModel user)
{
    using(var db = new MyWebAppDataContext())
    {
        var preferences = (from u in db.UserDataModels
                          where u == user
                          select u.Preferences).Single();

        return new UserPreferencesViewModel(preferences);
    }
}
</code>```

I like that I can divide simple operations into faux-stored procedures in my data models with static methods like FromEmail(), but I'm concerned about the cost of having Preferences() invoking two connections (right?) via the two using DataContext statements.

Do I need to be? Is what I'm doing less efficient than using a single using(var db = new MyWebAppDataContext()) statement?

答:
I developed a wrapper component that uses an interface like:

```<code>public interface IContextCacher {
    DataContext GetFromCache();
    void SaveToCache(DataContext ctx);
}
</code>```

And use a wrapper to instantiate the context; if it exists in cache, it's pulled from there, otherwise, a new instance is created and pushed to the Save method, and all future implementations would get the value from the getter.

Depending on the type of application would be the actual caching mechanism.  Say for instance, an ASP.NET web application.  This could store the context in the items collection, so its alive for the request only.  For a windows app, it could pull it from some singleton collection.  It could be whatever you wanted under the scenes.

ContentLicense: CC BY-SA 2.5

Title: LINQ to SQL: Reusing DataContext

Body:
I have a number of static methods that perform simple operations like insert or delete a record. All these methods follow this template of using:

public static UserDataModel FromEmail(string email)
{
    using (var db = new MyWebAppDataContext())
    {
        db.ObjectTrackingEnabled = false;
        return (from u in db.UserDataModels
                where u.Email == email
                select u).Single();
    }
}

I also have a few methods that need to perform multiple operations that use a DataContext:

public static UserPreferencesDataModel Preferences(string email)
{
    return UserDataModel.Preferences(UserDataModel.FromEmail(email));
}

private static UserPreferencesViewModel Preferences(UserDataModel user)
{
    using(var db = new MyWebAppDataContext())
    {
        var preferences = (from u in db.UserDataModels
                          where u == user
                          select u.Preferences).Single();

        return new UserPreferencesViewModel(preferences);
    }
}

I like that I can divide simple operations into faux-stored procedures in my data models with static methods like FromEmail(), but I'm concerned about the cost of having Preferences() invoking two connections (right?) via the two using DataContext statements.

Do I need to be? Is what I'm doing less efficient than using a single using(var db = new MyWebAppDataContext()) statement?

Body:
I developed a wrapper component that uses an interface like:

public interface IContextCacher {
    DataContext GetFromCache();
    void SaveToCache(DataContext ctx);
}

And use a wrapper to instantiate the context; if it exists in cache, it's pulled from there, otherwise, a new instance is created and pushed to the Save method, and all future implementations would get the value from the getter.

Depending on the type of application would be the actual caching mechanism.  Say for instance, an ASP.NET web application.  This could store the context in the items collection, so its alive for the request only.  For a windows app, it could pull it from some singleton collection.  It could be whatever you wanted under the scenes.


问:
PHP Include Function Efficiency
If I use PHP's include function to import parts of the page that are repeated like navigation, header and footer for example - will that make the code more or less efficient or would it be the same?
Thanks</p>

答:
I would agree that this is probably not something that you should concentrate on too much.  Most of the time you can use includes freely without worrying about how fast it is.  Ultimately, includes like this are for saving your time as a programmer.

Another factor to think about on the very low level is that the file you are accessing might be at a different place on the disk.  So, that means that it may not be cached, and it will take longer to go to the file location than if it were located within the file itself.

Title: PHP Include Function Efficiency


问:
How do I use SortField to sort my data numerically in Flex/ActionScript?
From the documentation:

SortField () constructor

```<code>public function SortField(name:String = null, caseInsensitive:Boolean = false, descending:Boolean = false, numeric:Object = null)
</code>```

I'm confused on the last part - numeric:Object = null.

Here is my function:

```<code>private function createXMLDataProvider():XMLListCollection{
    var sort:Sort = new Sort();
    sort.fields = [new SortField("@sortorder",true,false,true), new SortField("@label")];
    var searchTypesCollection:XMLListCollection =
        new XMLListCollection(getAssociations(_appData.searchTypes, "category", searchType));
    searchTypesCollection.sort = sort;
    searchTypesCollection.refresh();
    return searchTypesCollection;
}
</code>```

On this line:

```<code>sort.fields = [new SortField("@sortorder",true,false,true), new SortField("@label")];
</code>```

The first SortField is a number but is being compared like it is text. What should I be putting where it says true?

Also from the documentation:

Specifies that if the field being sorted contains numeric (number/int/uint) values, or string representations of numeric values, the comparator use a numeric comparison. If this property is false, fields with string representations of numbers are sorted using strings comparison, so 100 precedes 99, because "1" is a lower string value than "9". If this property is null, the first data item is introspected to see if it is a number or string and the sort proceeds based on that introspection.

The default value is false.

答:
I'm just guessing here, but caseInsensitive and numeric fields seem like an either-or choice to me, that is, if you set caseInsensitive to true, there is no real point in also setting numeric, and vice versa. Try modifying the above line as follows and see if it works that way.

```<code>sort.fields = [new SortField("@sortorder",false,false,true), new SortField("@label")];
</code>```

OwnerDisplayName: leif

Body:
From the documentation:

SortField () constructor

public function SortField(name:String = null, caseInsensitive:Boolean = false, descending:Boolean = false, numeric:Object = null)

I'm confused on the last part - numeric:Object = null.

Here is my function:

private function createXMLDataProvider():XMLListCollection{
    var sort:Sort = new Sort();
    sort.fields = [new SortField("@sortorder",true,false,true), new SortField("@label")];
    var searchTypesCollection:XMLListCollection =
        new XMLListCollection(getAssociations(_appData.searchTypes, "category", searchType));
    searchTypesCollection.sort = sort;
    searchTypesCollection.refresh();
    return searchTypesCollection;
}

On this line:

sort.fields = [new SortField("@sortorder",true,false,true), new SortField("@label")];

The first SortField is a number but is being compared like it is text. What should I be putting where it says true?

Also from the documentation:

Specifies that if the field being sorted contains numeric (number/int/uint) values, or string representations of numeric values, the comparator use a numeric comparison. If this property is false, fields with string representations of numbers are sorted using strings comparison, so 100 precedes 99, because "1" is a lower string value than "9". If this property is null, the first data item is introspected to see if it is a number or string and the sort proceeds based on that introspection.

The default value is false.

Body:
I'm just guessing here, but caseInsensitive and numeric fields seem like an either-or choice to me, that is, if you set caseInsensitive to true, there is no real point in also setting numeric, and vice versa. Try modifying the above line as follows and see if it works that way.

sort.fields = [new SortField("@sortorder",false,false,true), new SortField("@label")];

OwnerDisplayName: David Hanak


问:
Cross module dependencies in Boost Python
Suppose I have two boost python modules that are defined as follows. Module A:

```<code>class SomeClass {
public:
    SomeClass() {}
    ~SomeClass() {}
};
BOOST_PYTHON_MODULE(A)
{
    class_<SomeClass>("SomeClass");
}
</code>```

And module B:

```<code>class AnotherClass {
public:
    AnotherClass() {}
    ~AnotherClass() {}
    void func(SomeClass& sp) {}
};
BOOST_PYTHON_MODULE(B)
{   class_<AnotherClass>("AnotherClass")
        .def("func", &AnotherClass::func)
    ;
}
</code>```

Module B has a dependency on module A (i.e. it uses SomeClass from module A). Now, I execute the following python script:

```<code>import A
import B
obj1 = A.SomeClass()
obj2 = B.AnotherClass()
obj2.func(obj1)
</code>```

I get the following error:

```<code>Traceback (most recent call last):
  File "C:\bladiebla\script.py", line 8, in <module>
    obj2.func(obj1)
ArgumentError: Python argument types in
AnotherClass.func(AnotherClass, SomeClass)
did not match C++ signature:
func(class AnotherClass {lvalue}, class SomeClass)
</code>```

It seems that Python does not automatically translate classes between modules. Does anyone have an idea how to solve this?

答:
Based on your latest response and updated error message in your question, I think the problem might be because your BOOST_PYTHON_MODULE usage might be incorrect (based on what I've seen in other examples of using it). Try something like this and see if it helps:

Module A:

```<code>class SomeClass {
public:
    SomeClass() {}
    ~SomeClass() {}
};
BOOST_PYTHON_MODULE(A)
{
    boost::python::class_<SomeClass>("SomeClass");
}
</code>```

And module B:

```<code>class AnotherClass {
public:
    AnotherClass() {}
    ~AnotherClass() {}
    void func(SomeClass& sp) {}
};
BOOST_PYTHON_MODULE(B)
{   boost::python::class_<AnotherClass>("AnotherClass")
        .def("func", &AnotherClass::func)
    ;
}
</code>```

Note the insertion of a "boost::python::" prefix onto the class_<...> statement in each of the two BOOST_PYTHON_MODULE declarations.

Body:
Suppose I have two boost python modules that are defined as follows. Module A:

class SomeClass {
public:
    SomeClass() {}
    ~SomeClass() {}
};
BOOST_PYTHON_MODULE(A)
{
    class_<SomeClass>("SomeClass");
}

And module B:

class AnotherClass {
public:
    AnotherClass() {}
    ~AnotherClass() {}
    void func(SomeClass& sp) {}
};
BOOST_PYTHON_MODULE(B)
{   class_<AnotherClass>("AnotherClass")
        .def("func", &AnotherClass::func)
    ;
}

Module B has a dependency on module A (i.e. it uses SomeClass from module A). Now, I execute the following python script:

import A
import B
obj1 = A.SomeClass()
obj2 = B.AnotherClass()
obj2.func(obj1)

I get the following error:

Traceback (most recent call last):
  File "C:\bladiebla\script.py", line 8, in <module>
    obj2.func(obj1)
ArgumentError: Python argument types in
AnotherClass.func(AnotherClass, SomeClass)
did not match C++ signature:
func(class AnotherClass {lvalue}, class SomeClass)

It seems that Python does not automatically translate classes between modules. Does anyone have an idea how to solve this?

Body:
Based on your latest response and updated error message in your question, I think the problem might be because your BOOST_PYTHON_MODULE usage might be incorrect (based on what I've seen in other examples of using it). Try something like this and see if it helps:

Module A:

class SomeClass {
public:
    SomeClass() {}
    ~SomeClass() {}
};
BOOST_PYTHON_MODULE(A)
{
    boost::python::class_<SomeClass>("SomeClass");
}

And module B:

class AnotherClass {
public:
    AnotherClass() {}
    ~AnotherClass() {}
    void func(SomeClass& sp) {}
};
BOOST_PYTHON_MODULE(B)
{   boost::python::class_<AnotherClass>("AnotherClass")
        .def("func", &AnotherClass::func)
    ;
}

Note the insertion of a "boost::python::" prefix onto the class_<...> statement in each of the two BOOST_PYTHON_MODULE declarations.


问:
Android Studio - Drawable folders
I have three general questions regarding android's drawable folders.

Do i put different sized images in each of these folders, or will the images automatically scale themselves? As in, does android decrease the quality of the .bmp files automatically if placed in these folders?

When using the android design preview screen, will the appropriate image from the appropriate drawable folder be shown? If I have to make different sized images for each folder, I want to ensure that what i'm seeing in the design preview matches what is shown on other devices.

Lastly, do the drawable folders, if used, help to avoid the issue with failing to allocate memory for drawables on devices? I have had to scale my images down, and yet my college's phone still cannot allocate enough resources.

I couldn't find answers to these specific questions anywhere, so i'd really appreciate the help with these!

答:
Ad 1 I always find it really helpful to load drawables to my project using Android Drawable Importer plugin. It will take care of loading appropriately-sized image into appropriate drawables folder.

Ad 3  If that works for you, maybe try loading images from server using tools like Glade or Picasso? That way you don't clutter your app with unnecessary resources, making it too heavy data-wise. Use a local drawable as placeholder only, in case there's no internet connection.

I'd also recommend using .png over .bmp format, .png are lossless and compressed, meaning your images can get significantly smaller while not losing quality.

Title: Android Studio - Drawable folders


问:
ASMX web methods are not invoking on azure webapp
I have developed the web app and it is hosted on Azure. Web app having one typeahead and data for this typeahead is getting from Web service having web method 'AutocompleteSuggestions'.
When I go to ASMX file address like 'abc.azurewebsites.net/MyWebService.asmx' it will show the web method name and after clicking on that web method 'invoke' button appears. After clicking on 'Invoke' it will show 'The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.' It is working fine on the local environment.

答: I resolved my issue by changing the location of MyWebService.asmx file. I put MyWebService.asmx file in the folder of that perticular module not in the root folder. The path is changed from 'abc.azurewebsites.net/MyWebService.asmx' to 'abc.azurewebsites.net/Module1/MyWebService.asmx'.</p>


问:
How can I write a custom Date Format with string into it?
silly question here:

I'm willing to write a custom date format in Swift for brazilian pattern, which will be something like:

```<code>"20 de Junho, 2017" // 20 of June, 2017
</code>```

I was trying this pattern:

```<code>"dd de MMMM, yyyy"
</code>```

But the "de" world is taken as a pattern as well. How can I say that this is a constant?

Thanks

答:
You have to wrap it into quotes ', e.g.

```<code>"dd 'de' MMMM, yyyy"
</code>```

From Date Format Patterns:

Literal text, which is output as-is when formatting, and must closely match when parsing. Literal text can include:

Any characters other than A..Z and a..z, including spaces and punctuation.

Any text between single vertical quotes ('xxxx'), which may include A..Z and a..z as literal text.

You can also let the formatter generate the de:

```<code>let locale = Locale(identifier: "pt-BR")
let dateFormatter = DateFormatter()

let dayFormat = DateFormatter.dateFormat(fromTemplate: "d MMMM", options: 0, locale: locale)!

dateFormatter.dateFormat = dayFormat + ", yyyy"
dateFormatter.locale = locale

print(dateFormatter.string(from: Date())) // 7 de junho, 2017
</code>```

Body:
silly question here:

I'm willing to write a custom date format in Swift for brazilian pattern, which will be something like:

"20 de Junho, 2017" // 20 of June, 2017

I was trying this pattern:

"dd de MMMM, yyyy"

But the "de" world is taken as a pattern as well. How can I say that this is a constant?

Thanks

Body:
You have to wrap it into quotes ', e.g.

"dd 'de' MMMM, yyyy"

From Date Format Patterns:

Literal text, which is output as-is when formatting, and must closely match when parsing. Literal text can include:

Any characters other than A..Z and a..z, including spaces and punctuation.

Any text between single vertical quotes ('xxxx'), which may include A..Z and a..z as literal text.

You can also let the formatter generate the de:

let locale = Locale(identifier: "pt-BR")
let dateFormatter = DateFormatter()

let dayFormat = DateFormatter.dateFormat(fromTemplate: "d MMMM", options: 0, locale: locale)!

dateFormatter.dateFormat = dayFormat + ", yyyy"
dateFormatter.locale = locale

print(dateFormatter.string(from: Date())) // 7 de junho, 2017

ContentLicense: CC BY-SA 4.0


问:
Google fonts not display on mobile devices
I have this source that looks perfectly in the desktop browser, but when I check on the mobile I get another different source. Do you have any idea what happens?

are two 2 paragraphs, the first takes this source

```<code>  Font-family: 'Amatic SC', cursive;
</code>```

the second

```<code>Font-family: 'Questrial', sans-serif;

<Link href =" https://fonts.googleapis.com/css?family=Questrial "rel =" stylesheet ">
    <Link href = "https://fonts.googleapis.com/css?family=Academy+SC:700" rel = "stylesheet">
</code>```

The second paragraph maintains the source perfectly, the first one when reviewing it on a telephone is changed from source.

This is the page of the problem, it is in the first section, where says HOLA

答:
The link is not working, so here a few tips + a fix

Remove the whitespaces before and after the links and type everything lowercase.

```<code><Link href =" https://fonts.googleapis.com/css?family=Questrial "rel =" stylesheet ">
</code>```

should be this:

```<code><link href="https://fonts.googleapis.com/css?family=Questrial" rel="stylesheet">
</code>```

You use Font-family with an uppercase F, this should be lowercase (font-family)

And now the fix for your problem, you import Academy+SC but in your font-family you use: Amatic SC, this should be Academy SC.

Hope this helps!

Body:
I have this source that looks perfectly in the desktop browser, but when I check on the mobile I get another different source. Do you have any idea what happens?

are two 2 paragraphs, the first takes this source

  Font-family: 'Amatic SC', cursive;

the second

Font-family: 'Questrial', sans-serif;

<Link href =" https://fonts.googleapis.com/css?family=Questrial "rel =" stylesheet ">
    <Link href = "https://fonts.googleapis.com/css?family=Academy+SC:700" rel = "stylesheet">

The second paragraph maintains the source perfectly, the first one when reviewing it on a telephone is changed from source.

This is the page of the problem, it is in the first section, where says HOLA

Body:
The link is not working, so here a few tips + a fix

Remove the whitespaces before and after the links and type everything lowercase.

<Link href =" https://fonts.googleapis.com/css?family=Questrial "rel =" stylesheet ">

should be this:

<link href="https://fonts.googleapis.com/css?family=Questrial" rel="stylesheet">

You use Font-family with an uppercase F, this should be lowercase (font-family)

And now the fix for your problem, you import Academy+SC but in your font-family you use: Amatic SC, this should be Academy SC.

Hope this helps!


问:
Can I use complex in a view?
I want to create a view from table T1 with two fields, one is the ID and the other can take its value from the fields Name or Name_aux. The logic is to take the value from Name_2 except if it is NULL, empty (''), or a blank space. I cannot make any change into the table.

T1 has an structure like this:

```<code>|ID|Name |Name_2|
|1 |T001 |      |
|2 |T001T|T001X |
|3 |T002 |      |
</code>```

I have used the IIF function but although I can use it from a script I cannot make it work in a query:

```<code>SELECT ID, IIF( (([Name_2] = '') OR ([Name_2] = ' ') OR ([Name_2] IS NULL)),
[Name], [Name_2] ) AS NAME
FROM     dbo.T1
</code>```

I have read in this thread that it is not possible to use complex IF logic inside a view but since it is from some years ago, I want to ask again.

If there is no other solution, I can do a User Defined Function that receives two strings and returns one, but I want to avoid that.

Thank you

答: There is no obvious reason why you cannot do that in a view -or a function for that matter. Some of our views ore quite hairy beats with many such conditional statements etc. The only requirement is that a derived column MUST be given an alias.</p>

Title: Can I use complex in a view?

Body:
I want to create a view from table T1 with two fields, one is the ID and the other can take its value from the fields Name or Name_aux. The logic is to take the value from Name_2 except if it is NULL, empty (''), or a blank space. I cannot make any change into the table.

T1 has an structure like this:

|ID|Name |Name_2|
|1 |T001 |      |
|2 |T001T|T001X |
|3 |T002 |      |

I have used the IIF function but although I can use it from a script I cannot make it work in a query:

SELECT ID, IIF( (([Name_2] = '') OR ([Name_2] = ' ') OR ([Name_2] IS NULL)),
[Name], [Name_2] ) AS NAME
FROM     dbo.T1

I have read in this thread that it is not possible to use complex IF logic inside a view but since it is from some years ago, I want to ask again.

If there is no other solution, I can do a User Defined Function that receives two strings and returns one, but I want to avoid that.

Thank you


答: use global.astronautsData if you want it to be global</p>

Title: how can I store my data in a global variable?

Body:
$(function(){

    var astronautsData;

    $.getJSON('http://api.open-notify.org/astros.json', doSomething);

    function doSomething(data) {
        astronautsData = data;
    }

    alert(astronautsData.people[0].name)

});

I would like to be able to use the data in every function I make, that's why I tried to put it in the variable astronautsData, but unfortunately astronautsdata is undefined.


问:
Why does the order in which Netbeans loads Java Libraries cause errors sometimes? and how do I avoid it?
Basic background data:  Windows 7, Netbeans 8.0.2, LWJGL 2.9.3, Slick Util.
The rest of the code is my own.

So, periodically, I was having what I thought was a bug, that caused my program to run within the IDE, but would fail when I used "Clean and Build" on the project.

Today, when it happened again, I decided to get to the bottom of it.  So, taking a copy of the whole project folder, that was working and otherwise identical, and replacing 1 file at a time, and testing it, I was able to narrow it down to the /nbproject/project.properties file.

Every other file could be replaced and the problem persisted.  Replace ONLY this file, and the problem went away.  So then I loaded up both files and compared them side by side (using the Netbeans "Diff to..." feature) and narrowed it down to the following lines:

```<code>javac.classpath=\
${libs.LWJGL-2.9.3.classpath}:\
${libs.0-Slick_Util.classpath}:\
${libs.0-Loaders_v03.classpath}:\
${libs.0-Text2D_v03.classpath}:\
${libs.0-Foundation_v04.classpath}:\
${libs.0-Abstracts_v04.classpath}
</code>```

Now this code, looks like it is telling the compiler the ORDER in which the libraries should be loaded (I may be wrong).

With that in mind, I decided to test it.  I copied this block from the working file, to the non-working file, and it worked just fine.  The working code btw is this:

```<code>javac.classpath=\
${libs.LWJGL-2.9.3.classpath}:\
${libs.0-Slick_Util.classpath}:\
${libs.0-Foundation_v04.classpath}:\
${libs.0-Abstracts_v04.classpath}:\
${libs.0-Loaders_v03.classpath}:\
${libs.0-Text2D_v03.classpath}
</code>```

The only differences, you may notice, is the ORDER.  Continuing my test, I went into the non-working project's Library properties page, and simply re-ordered the libraries to match the working list.  PROBLEM WENT AWAY!  If I simply moved the Foundation and Abstracts libraries down in the list, the PROBLEM CAME BACK!

I must have tried a dozen different order combinations, and got about 2/3 that failed, and 1/3 that worked.  The ones that worked all involved Foundation and/or Abstracts to be near the top.

Why is this happening? How can I know what order my libraries need to be loaded to avoid the error?

The error btw is this:

```<code>F:\Dropbox\2-Documents\4-Java Programming\Library\0-LoadingScreen_v04-Copy\src\A_Library\Test_LoadingScreen.java:94: error: cannot find symbol
    Lib_Foundation                  .setConfigLocation(configLocation);
  symbol:   method setConfigLocation(String)
  location: class Lib_Foundation
</code>```

Any information that can help me avoid this problem in the future will be appreciated.

答:
It would appear that either “Loaders_v03” or “Text2D_v03” contains its own version of Foundation, including an incompatible Lib_Foundation class.  A classpath is searched in order, so your current solution—reordering javac.classpath—will always work, assuming NetBeans doesn’t mess with it the next time you make any change to your project.

Whether that will break Loaders and Text2D depends upon how well Foundation adheres to object-oriented design: public classes and their public members are never supposed to be changed or removed in successive versions. (That is why 20-year-old code written for Java 1.1 will still compile in Java 8.)

Body:
Basic background data:  Windows 7, Netbeans 8.0.2, LWJGL 2.9.3, Slick Util.
The rest of the code is my own.

So, periodically, I was having what I thought was a bug, that caused my program to run within the IDE, but would fail when I used "Clean and Build" on the project.

Today, when it happened again, I decided to get to the bottom of it.  So, taking a copy of the whole project folder, that was working and otherwise identical, and replacing 1 file at a time, and testing it, I was able to narrow it down to the /nbproject/project.properties file.

Every other file could be replaced and the problem persisted.  Replace ONLY this file, and the problem went away.  So then I loaded up both files and compared them side by side (using the Netbeans "Diff to..." feature) and narrowed it down to the following lines:

javac.classpath=\
${libs.LWJGL-2.9.3.classpath}:\
${libs.0-Slick_Util.classpath}:\
${libs.0-Loaders_v03.classpath}:\
${libs.0-Text2D_v03.classpath}:\
${libs.0-Foundation_v04.classpath}:\
${libs.0-Abstracts_v04.classpath}

Now this code, looks like it is telling the compiler the ORDER in which the libraries should be loaded (I may be wrong).

With that in mind, I decided to test it.  I copied this block from the working file, to the non-working file, and it worked just fine.  The working code btw is this:

javac.classpath=\
${libs.LWJGL-2.9.3.classpath}:\
${libs.0-Slick_Util.classpath}:\
${libs.0-Foundation_v04.classpath}:\
${libs.0-Abstracts_v04.classpath}:\
${libs.0-Loaders_v03.classpath}:\
${libs.0-Text2D_v03.classpath}

The only differences, you may notice, is the ORDER.  Continuing my test, I went into the non-working project's Library properties page, and simply re-ordered the libraries to match the working list.  PROBLEM WENT AWAY!  If I simply moved the Foundation and Abstracts libraries down in the list, the PROBLEM CAME BACK!

I must have tried a dozen different order combinations, and got about 2/3 that failed, and 1/3 that worked.  The ones that worked all involved Foundation and/or Abstracts to be near the top.

Why is this happening? How can I know what order my libraries need to be loaded to avoid the error?

The error btw is this:

F:\Dropbox\2-Documents\4-Java Programming\Library\0-LoadingScreen_v04-Copy\src\A_Library\Test_LoadingScreen.java:94: error: cannot find symbol
    Lib_Foundation                  .setConfigLocation(configLocation);
  symbol:   method setConfigLocation(String)
  location: class Lib_Foundation

Any information that can help me avoid this problem in the future will be appreciated.


问:
Inserting Select from HTML to mysql
so i have this table in my html

```<code><form method = "POST" action="admin_event.php">
<table class = "table" id="dynamic_admin_add_price">
                                                        <thead>
                                                        <th>Deadline </th>
                                                        <th>Register Date</th>
                                                        <th>Price</th>
                                                        <th></th>
                                                        <th></th>
                                                        </thead>

                                                        <tbody>
                                                        <tr>
                                                            <td>
                                                                <select name="admin_add_deadline[]" class="form-control">
                                                                    <option value="early_bird">Early Bird</option>
                                                                    <option value="middle">Middle</option>
                                                                    <option value="normal">Normal</option>
                                                                </select>
                                                            </td>
                                                            <td><input type="text" name="admin_add_register_date[]" class="form-control registerDate" required></td>
                                                            <td><label>Rp.</label></td>
                                                            <td><input type="number" name="admin_add_price[]" class="form-control" value=""  required></td>
                                                            <td><button type="submit" name="button_add_price" id="price" class="btn btn-success">Add more deadlines</button></td>
                                                            <!--<td><button type="button" name=button_remove_event_time id="remove_event-time" class="btn btn-danger" disabled>Remove</button></td>-->
                                                        </tr>
                                                        </tbody>
                                                    </table>

 <button type="submit" class="btn btn-primary" name="admin_add_event_datas">Save</button>
</form>
</code>```

And i have created the javascript so that the user can add as many rows as they want

```<code>    $('#add_price').click(function(){
    j++;
    $('#dynamic_admin_add_price').append(
        '<tr id="row2'+j+'">' +
        '<td><select name="admin_add_deadline[]" class="form-control"><option value="early_bird">Early Bird</option><option value="middle">Middle</option><option value="normal">Normal</option></select></td>'+
        '<td><input type="text" name="admin_add_register_date[]" class="form-control registerDate" required></td>' +
        '<td><label>Rp.</label></td>' +
        '<td><input type="number" name="admin_add_price[]" class="form-control" value="" required></td>' +
        '<td><button type="submit" name="button_remove_event_time" id="'+j+'" class="btn btn-danger btn_remove2" required>Remove</button></td>' +
        '</tr>');
});

$(document).on('click', '.btn_remove2', function(){
    var button_id = $(this).attr("id");
    $('#row2'+button_id+'').remove();
});
</code>```

The adding rows work fine and the rest of the data can be inputted into the mysql, EXCEPT for the select fields,where it returns incorrectly and doesn't get any input at all from the non-static rows.

What i want to do is that if the user chose early bird, it gave the number 1 in the php, 2 for the middle option, and 3 for the normal ones, as it matches the id_deadline in another table that is used as the foreign key in the table i want to insert the data to. This is the snippet of the php script(i only put the one for the deadline):

```<code>if(isset($_POST['admin_add_deadline'])){
$deadline = $_POST['admin_add_deadline'];

$one = 1;
$two = 2;
$three = 3;
if($deadline == 'early_bird'){

        $deadline = $one;
}

if($deadline == 'middle'){
        $deadline = $two;
}

else{
$deadline = $three
}

}
</code>```

and this is the foreach to insert the data

```<code>    foreach ($register_date as $key => $value) {

    $post_register_date = $db->real_escape_string($value);

    $post_insert_price = $db->real_escape_string($register_price[$key]);

    $post_deadline = $deadline[$key];

    $query = "INSERT INTO register_time(id_event, id_deadline, register_date, price, created_at, status)
                          VALUES('$row_id_event','$post_deadline', '$post_register_date', '$post_insert_price', '$time', '$status')";

    if(mysqli_query($db, $query)){
        $succ = "New record created successfully";
    }

    else{
        echo "Error: " . $query . "<br>" . mysqli_error($db);
    }

}
</code>```

Again, the problem is that if i have 3 rows generated and i clicked the submit button, the inserted value for the id_deadline column in the table will always be 3 for the first row, and the other 2 rows will return an error as the value is '' for the id_deadline in the insert query

Can you guys help me with this problem?Thank you, i hope my question is clear enough.

EDIT: Fixing the typos

答: Got it working now, just moved the ifs and elses from the deadline to the foreach</p>

Title: Inserting Select from HTML to mysql

Body:
so i have this table in my html

<form method = "POST" action="admin_event.php">

                                                        Deadline
                                                        Register Date
                                                        Price

                                                                <select name="admin_add_deadline[]" class="form-control">
                                                                    <option value="early_bird">Early Bird</option>
                                                                    <option value="middle">Middle</option>
                                                                    <option value="normal">Normal</option>
                                                                </select>

                                                            <input type="text" name="admin_add_register_date[]" class="form-control registerDate" required>
                                                            Rp.
                                                            <input type="number" name="admin_add_price[]" class="form-control" value=""  required>
                                                            <button type="submit" name="button_add_price" id="price" class="btn btn-success">Add more deadlines</button>

 <button type="submit" class="btn btn-primary" name="admin_add_event_datas">Save</button>
</form>

And i have created the javascript so that the user can add as many rows as they want

    $('#add_price').click(function(){
    j++;
    $('#dynamic_admin_add_price').append(
        '
' +
        '<select name="admin_add_deadline[]" class="form-control"><option value="early_bird">Early Bird</option><option value="middle">Middle</option><option value="normal">Normal</option></select>	'+
        '<input type="text" name="admin_add_register_date[]" class="form-control registerDate" required>	' +
        'Rp.	' +
        '<input type="number" name="admin_add_price[]" class="form-control" value="" required>	' +
        '<button type="submit" name="button_remove_event_time" id="'+j+'" class="btn btn-danger btn_remove2" required>Remove</button>	' +
        '
');
});

$(document).on('click', '.btn_remove2', function(){
    var button_id = $(this).attr("id");
    $('#row2'+button_id+'').remove();
});

The adding rows work fine and the rest of the data can be inputted into the mysql, EXCEPT for the select fields,where it returns incorrectly and doesn't get any input at all from the non-static rows.

What i want to do is that if the user chose early bird, it gave the number 1 in the php, 2 for the middle option, and 3 for the normal ones, as it matches the id_deadline in another table that is used as the foreign key in the table i want to insert the data to. This is the snippet of the php script(i only put the one for the deadline):

if(isset($_POST['admin_add_deadline'])){
$deadline = $_POST['admin_add_deadline'];

$one = 1;
$two = 2;
$three = 3;
if($deadline == 'early_bird'){

        $deadline = $one;
}

if($deadline == 'middle'){
        $deadline = $two;
}

else{
$deadline = $three
}

}

and this is the foreach to insert the data

    foreach ($register_date as $key => $value) {

    $post_register_date = $db->real_escape_string($value);

    $post_insert_price = $db->real_escape_string($register_price[$key]);

    $post_deadline = $deadline[$key];

    $query = "INSERT INTO register_time(id_event, id_deadline, register_date, price, created_at, status)
                          VALUES('$row_id_event','$post_deadline', '$post_register_date', '$post_insert_price', '$time', '$status')";

    if(mysqli_query($db, $query)){
        $succ = "New record created successfully";
    }

    else{
        echo "Error: " . $query . "
" . mysqli_error($db);
    }

}

Again, the problem is that if i have 3 rows generated and i clicked the submit button, the inserted value for the id_deadline column in the table will always be 3 for the first row, and the other 2 rows will return an error as the value is '' for the id_deadline in the insert query

Can you guys help me with this problem?Thank you, i hope my question is clear enough.

EDIT: Fixing the typos


问:
One app with many servers
Let say I have an Angular 2 application. I need to get data from many pages by REST API. I have also node js server which communicates with database. How should I call APIs from Angular 2 app? Should I call APIs directly from Angular 2 app or through node js server? Option 1 is faster but option 2 gives me control what is going to be send to front end. Which option is better?

Option 1:

```<code>    Angular 2 app
    /     \      \
   /       \      ....
node      API 1   API N
server
</code>```

Option 2:

```<code>Angular 2 app
     |
     |
 node server
 /       \
/    ...  \
API 1      API N
</code>```

Regards

答: I dont see how this directly relates to angular. This is more related to the question: do you want to use the node server as the only entry point for your HTTP requests or not. Your client app will just send http requests to different endpoints through a service, it doesnt care if its 1, 2 or 3 web apis behind it

Title: One app with many servers

Body:
Let say I have an Angular 2 application. I need to get data from many pages by REST API. I have also node js server which communicates with database. How should I call APIs from Angular 2 app? Should I call APIs directly from Angular 2 app or through node js server? Option 1 is faster but option 2 gives me control what is going to be send to front end. Which option is better?

Option 1:

    Angular 2 app
    /     \      \
   /       \      ....
node      API 1   API N
server

Option 2:

Angular 2 app
     |
     |
 node server
 /       \
/    ...  \
API 1      API N

Regards


问:
How to remove all markers in google map (with xml. file)
I'm trying to remove all markers on my map.

I've tried to use:

```<code>marker.setMap(null)
</code>```

But it only removes one marker.

How can I remove all markers on the map?

Here is my code: https://jsfiddle.net/j027mww1/67/

答:
The Problem is that your marker variable only stores the last marker.

You have to push all marker into an array. using this array you will be able to remove each marker from your map. Take a look at the comments inside the code. ;)

var customLabel = {
  restaurant: {
    label: 'R'
  },
  bar: {
    label: 'B'
  }
};
var map;
var markers;
var point;
var xml;
var markerArr = []; // NEW ARRAY

function initMap() {
  map = new google.maps.Map(document.getElementById('map'), {
    center: new google.maps.LatLng(-33.863276, 151.207977),
    zoom: 12
  });

}

function drop() {
  var infoWindow = new google.maps.InfoWindow;
  downloadUrl('https://storage.googleapis.com/mapsdevsite/json/mapmarkers2.xml', function(data) {
    xml = data.responseXML;
    markers = xml.documentElement.getElementsByTagName('marker');
    Array.prototype.forEach.call(markers, function(markerElem) {
      var id = markerElem.getAttribute('id');
      var name = markerElem.getAttribute('name');
      var address = markerElem.getAttribute('address');
      var type = markerElem.getAttribute('type');
      point = new google.maps.LatLng(
        parseFloat(markerElem.getAttribute('lat')),
        parseFloat(markerElem.getAttribute('lng')));

      var infowincontent = document.createElement('div');
      var strong = document.createElement('strong');
      strong.textContent = name
      infowincontent.appendChild(strong);
      infowincontent.appendChild(document.createElement('br'));

      var text = document.createElement('text');
      text.textContent = address
      infowincontent.appendChild(text);
      var icon = customLabel[type] || {};
      marker = new google.maps.Marker({
        map: map,
        position: point,
        animation: google.maps.Animation.DROP
      });
      marker.addListener('click', function() {
        infoWindow.setContent(infowincontent);
        infoWindow.open(map, marker);
      });
      markerArr.push(marker); // PUSH EACH MARKER INTO AN ARRAY
    });

  });
}

function clearMarkers() {
  for (var i = 0; i < markerArr.length; i++) {
    markerArr[i].setMap(null); // REMOVE EACH MARKER
  }
}

function downloadUrl(url, callback) {
  var request = window.ActiveXObject ?
      new ActiveXObject('Microsoft.XMLHTTP') :
  new XMLHttpRequest;

  request.onreadystatechange = function() {
    if (request.readyState == 4) {
      request.onreadystatechange = doNothing;
      callback(request, request.status);
    }
  };

  request.open('GET', url, true);
  request.send(null);
}

function doNothing() {}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* Always set the map height explicitly to define the size of the div
 * element that contains the map. */

#map {
  height: 100%;
}

/* Optional: Makes the sample page fill the window. */

html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}</code>```

  <button id="drop" onclick="drop()">Drop Markers</button>
  <button id="clearMarkers" onclick="clearMarkers()">clear Markers</button>

```

Body:
I'm trying to remove all markers on my map.

I've tried to use:

marker.setMap(null)

But it only removes one marker.

How can I remove all markers on the map?

Here is my code: https://jsfiddle.net/j027mww1/67/

Body:
The Problem is that your marker variable only stores the last marker.

You have to push all marker into an array. using this array you will be able to remove each marker from your map. Take a look at the comments inside the code. ;)

var customLabel = {
  restaurant: {
    label: 'R'
  },
  bar: {
    label: 'B'
  }
};
var map;
var markers;
var point;
var xml;
var markerArr = []; // NEW ARRAY

function initMap() {
  map = new google.maps.Map(document.getElementById('map'), {
    center: new google.maps.LatLng(-33.863276, 151.207977),
    zoom: 12
  });

}

function drop() {
  var infoWindow = new google.maps.InfoWindow;
  downloadUrl('https://storage.googleapis.com/mapsdevsite/json/mapmarkers2.xml', function(data) {
    xml = data.responseXML;
    markers = xml.documentElement.getElementsByTagName('marker');
    Array.prototype.forEach.call(markers, function(markerElem) {
      var id = markerElem.getAttribute('id');
      var name = markerElem.getAttribute('name');
      var address = markerElem.getAttribute('address');
      var type = markerElem.getAttribute('type');
      point = new google.maps.LatLng(
        parseFloat(markerElem.getAttribute('lat')),
        parseFloat(markerElem.getAttribute('lng')));

      var infowincontent = document.createElement('div');
      var strong = document.createElement('strong');
      strong.textContent = name
      infowincontent.appendChild(strong);
      infowincontent.appendChild(document.createElement('br'));

      var text = document.createElement('text');
      text.textContent = address
      infowincontent.appendChild(text);
      var icon = customLabel[type] || {};
      marker = new google.maps.Marker({
        map: map,
        position: point,
        animation: google.maps.Animation.DROP
      });
      marker.addListener('click', function() {
        infoWindow.setContent(infowincontent);
        infoWindow.open(map, marker);
      });
      markerArr.push(marker); // PUSH EACH MARKER INTO AN ARRAY
    });

  });
}

function clearMarkers() {
  for (var i = 0; i < markerArr.length; i++) {
    markerArr[i].setMap(null); // REMOVE EACH MARKER
  }
}

function downloadUrl(url, callback) {
  var request = window.ActiveXObject ?
      new ActiveXObject('Microsoft.XMLHTTP') :
  new XMLHttpRequest;

  request.onreadystatechange = function() {
    if (request.readyState == 4) {
      request.onreadystatechange = doNothing;
      callback(request, request.status);
    }
  };

  request.open('GET', url, true);
  request.send(null);
}

function doNothing() {}

/* Always set the map height explicitly to define the size of the div
 * element that contains the map. */

#map {
  height: 100%;
}

/* Optional: Makes the sample page fill the window. */

html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}

<div id="floating-panel">
  <button id="drop" onclick="drop()">Drop Markers</button>
  <button id="clearMarkers" onclick="clearMarkers()">clear Markers</button>
</div>
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="https://maps.googleapis.com/maps/api/js?callback=initMap"></script>


答:
Use Case as next demo:-

```<code>declare @MyTable table (id int identity, name varchar(10), name_2 varchar(10))

insert into @MyTable values ('T001',NULL),('T001T','T001X'),('T002',' ')

select id, case
        when name_2 is null or name_2 = '' or name_2 = ' '
        then name
        else name_2
        end The_name
 from @MyTable
</code>```

Result:-

```<code>1   T001
2   T001X
3   T002
</code>```

Title: Can I use complex in a view?

Body:
Use Case as next demo:-

declare @MyTable table (id int identity, name varchar(10), name_2 varchar(10))

insert into @MyTable values ('T001',NULL),('T001T','T001X'),('T002',' ')

select id, case
        when name_2 is null or name_2 = '' or name_2 = ' '
        then name
        else name_2
        end The_name
 from @MyTable

Result:-

1   T001
2   T001X
3   T002


问:
DataStage error - Oracle ORA-03135 connection lost contact
In DataStage 9.1.2 I am getting this message error when I try to extract some data within a Oracle Connector

```<code>ORA_MONTO: The OCI function OCISessionEnd returned status -1. Error code: 3,135, Error message: ORA-03135: connection lost contact
Process ID: 0
Session ID: 901 Serial number: 13587.
</code>```

It is into a parallel job that merge data from 6 differents sources (Oracle queries) and write it into a dataset file.

I tried to add more nodes but in log I see this:

ORACLE_CONNECTOR: The connector will run in sequential mode.

答:
I had to ask for parallel read permissions to the DBA and then I could run my job in parallel mode (including access to database)</p>

```<code>grant select on sys.dba_extents to [user];
</code>```

Body:
In DataStage 9.1.2 I am getting this message error when I try to extract some data within a Oracle Connector

ORA_MONTO: The OCI function OCISessionEnd returned status -1. Error code: 3,135, Error message: ORA-03135: connection lost contact
Process ID: 0
Session ID: 901 Serial number: 13587.

It is into a parallel job that merge data from 6 differents sources (Oracle queries) and write it into a dataset file.

I tried to add more nodes but in log I see this:

ORACLE_CONNECTOR: The connector will run in sequential mode.

Body:
I had to ask for parallel read permissions to the DBA and then I could run my job in parallel mode (including access to database)

grant select on sys.dba_extents to [user];


问:
Elastic Beanstalk running mod_wsgi Django app with multi processes causing 302 loop
I have been investigating for a while now, and all the docs seem to say this is possible, but whenever I increase our elastic beanstalk mod_wsgi NumProcesses config above 1, our admin site is inaccessible.

I have created a reduction where I tested with a default django app, and the behaviour is still present. I have also tried to replicate locally, however my apache and mod_wsgi config cannot replicate the issue.

Basically, what I am seeing, is that every attempted login, causes a 302 Found redirect back to the login page. I have cleared the sessions out of the database, and I can confirm that the application creates a new entry during the login POST, but the user is still directed back to the login page (see config and logs below). We also have a load balancer and sticky sessions configured on the Elastic Beanstalk instance(s).

Here is the python contained config from our .ebextensions

```<code>option_settings:
  "aws:elasticbeanstalk:container:python":
    WSGIPath: site/settings/wsgi/__init__.py
    NumProcesses: 4
    NumThreads: 15
</code>```

Here is the resulting wsgi.conf taken from the instance

```<code>WSGIPythonHome /opt/python/run/baselinenv
WSGISocketPrefix run/wsgi
WSGIRestrictEmbedded On

<VirtualHost *:80>

Alias /static/ /opt/python/current/app/site/static/
<Directory /opt/python/current/app/site/static/>
Order allow,deny
Allow from all
</Directory>

WSGIScriptAlias / /opt/python/current/app/site/settings/wsgi/__init__.py

<Directory /opt/python/current/app/>
  Require all granted
</Directory>

WSGIDaemonProcess wsgi processes=4 threads=15 display-name=%{GROUP} \
  python-path=/opt/python/current/app:/opt/python/run/venv/lib64/python3.4/site-packages:/opt/python/run/venv/lib/python3.4/site-packages user=wsgi group=wsgi \
  home=/opt/python/current/app
WSGIProcessGroup wsgi
</VirtualHost>
</code>```

Here is a grab of the access_log showing the redirect

```<code>::1 - - [05/Jun/2017:13:26:18 +0000] "POST /admin/login/?next=/admin/ HTTP/1.1" 302 -
::1 - - [05/Jun/2017:13:26:18 +0000] "GET /admin/ HTTP/1.1" 302 -
::1 - - [05/Jun/2017:13:26:18 +0000] "GET /admin/login/?next=/admin/ HTTP/1.1" 200 1650
</code>```

Now, the following set of configs and info is taken from my local installation.

```<code># wsgi.conf

WSGIVerboseDebugging 'On'
WSGIPythonHome /usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7
WSGISocketPrefix /tmp/wsgi
WSGIRestrictEmbedded On

<VirtualHost *:80>

Alias /static/ /Users/www/app/site/static/
<Directory /Users/www/app/site/static/>
Order allow,deny
Allow from all
</Directory>

WSGIProcessGroup _www
WSGIScriptAlias / /Users/www/app/site/settings/wsgi/__init__.py \
        process-group=_www

<Directory /Users/www/app/>
  Require all granted
</Directory>

WSGIDaemonProcess _www processes=4 threads=15 display-name=%{GROUP} group=_www user=_www \
  python-path=/Users/www/app:/usr/local/lib/python2.7 \
  home=/Users/www/app/site
</VirtualHost>
</code>```

expected access_log

```<code>::1 - - [05/Jun/2017:23:27:48 +1000] "POST /admin/login/?next=/admin/ HTTP/1.1" 302 -
::1 - - [05/Jun/2017:23:27:48 +1000] "GET /admin/ HTTP/1.1" 200 2783
</code>```

The question I have, is why does one work, and one produce a loop? I can see an option on the WSGIScriptAlias, but that's not available on the elastic beanstalk config, and the documentation still says this is feasible. What am I missing here? Why does having multiple processes cause this issue?

Extra Notes

Failing mod_wsgi version 3.5

Working mod_wsgi version 4.5.15

I was also able to get my local wsgi app working with python 3.6

答:
After some time I found a Session data corrupted entry in the apache error_log

Turns out, the code to generate the SECRET_KEY was randomly assigning one in production.

Meaning, when the request was passed to another process, the session key did not match, logging the user out and sending the back to the login page. Hence the 302 Found loop.

Found this helpful Django Login/Session Not Sticking

Body:
I have been investigating for a while now, and all the docs seem to say this is possible, but whenever I increase our elastic beanstalk mod_wsgi NumProcesses config above 1, our admin site is inaccessible.

I have created a reduction where I tested with a default django app, and the behaviour is still present. I have also tried to replicate locally, however my apache and mod_wsgi config cannot replicate the issue.

Basically, what I am seeing, is that every attempted login, causes a 302 Found redirect back to the login page. I have cleared the sessions out of the database, and I can confirm that the application creates a new entry during the login POST, but the user is still directed back to the login page (see config and logs below). We also have a load balancer and sticky sessions configured on the Elastic Beanstalk instance(s).

Here is the python contained config from our .ebextensions

option_settings:
  "aws:elasticbeanstalk:container:python":
    WSGIPath: site/settings/wsgi/__init__.py
    NumProcesses: 4
    NumThreads: 15

Here is the resulting wsgi.conf taken from the instance

WSGIPythonHome /opt/python/run/baselinenv
WSGISocketPrefix run/wsgi
WSGIRestrictEmbedded On

<VirtualHost *:80>

Alias /static/ /opt/python/current/app/site/static/
<Directory /opt/python/current/app/site/static/>
Order allow,deny
Allow from all
</Directory>

WSGIScriptAlias / /opt/python/current/app/site/settings/wsgi/__init__.py

<Directory /opt/python/current/app/>
  Require all granted
</Directory>

WSGIDaemonProcess wsgi processes=4 threads=15 display-name=%{GROUP} \
  python-path=/opt/python/current/app:/opt/python/run/venv/lib64/python3.4/site-packages:/opt/python/run/venv/lib/python3.4/site-packages user=wsgi group=wsgi \
  home=/opt/python/current/app
WSGIProcessGroup wsgi
</VirtualHost>

Here is a grab of the access_log showing the redirect

::1 - - [05/Jun/2017:13:26:18 +0000] "POST /admin/login/?next=/admin/ HTTP/1.1" 302 -
::1 - - [05/Jun/2017:13:26:18 +0000] "GET /admin/ HTTP/1.1" 302 -
::1 - - [05/Jun/2017:13:26:18 +0000] "GET /admin/login/?next=/admin/ HTTP/1.1" 200 1650

Now, the following set of configs and info is taken from my local installation.

# wsgi.conf

WSGIVerboseDebugging 'On'
WSGIPythonHome /usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7
WSGISocketPrefix /tmp/wsgi
WSGIRestrictEmbedded On

<VirtualHost *:80>

Alias /static/ /Users/www/app/site/static/
<Directory /Users/www/app/site/static/>
Order allow,deny
Allow from all
</Directory>

WSGIProcessGroup _www
WSGIScriptAlias / /Users/www/app/site/settings/wsgi/__init__.py \
        process-group=_www

<Directory /Users/www/app/>
  Require all granted
</Directory>

WSGIDaemonProcess _www processes=4 threads=15 display-name=%{GROUP} group=_www user=_www \
  python-path=/Users/www/app:/usr/local/lib/python2.7 \
  home=/Users/www/app/site
</VirtualHost>

expected access_log

::1 - - [05/Jun/2017:23:27:48 +1000] "POST /admin/login/?next=/admin/ HTTP/1.1" 302 -
::1 - - [05/Jun/2017:23:27:48 +1000] "GET /admin/ HTTP/1.1" 200 2783

The question I have, is why does one work, and one produce a loop? I can see an option on the WSGIScriptAlias, but that's not available on the elastic beanstalk config, and the documentation still says this is feasible. What am I missing here? Why does having multiple processes cause this issue?

Extra Notes

Failing mod_wsgi version 3.5

Working mod_wsgi version 4.5.15

I was also able to get my local wsgi app working with python 3.6


问:
How to recursively find the latest modified file in a directory?
It seems that ls doesn't sort the files correctly when doing a recursive call:

```<code>ls -altR . | head -n 3
</code>```

How can I find the most recently modified file in a directory (including subdirectories)?

答:
I find the following shorter and with more interpretable output:

```<code>find . -type f -printf '%TF %TT %p\n' | sort | tail -1
</code>```

Given the fixed length of the standardised ISO format datetimes, lexicographical sorting is fine and we don't need the -n option on the sort.

If you want to remove the timestamps again, you can use:

```<code>find . -type f -printf '%TFT%TT %p\n' | sort | tail -1 | cut -f2- -d' '
</code>```

Body:
It seems that ls doesn't sort the files correctly when doing a recursive call:

ls -altR . | head -n 3

How can I find the most recently modified file in a directory (including subdirectories)?

Body:
I find the following shorter and with more interpretable output:

find . -type f -printf '%TF %TT %p\n' | sort | tail -1

Given the fixed length of the standardised ISO format datetimes, lexicographical sorting is fine and we don't need the -n option on the sort.

If you want to remove the timestamps again, you can use:

find . -type f -printf '%TFT%TT %p\n' | sort | tail -1 | cut -f2- -d' '


问:
Looking for WP 3.0 sample posts data
I'm looking for quality sample posts data for WP 3.0 and up (for theme development). Any suggestion ?</p>

答: Couldn't you use some Lipsum text? They'll let you generate just about as much as you want.</p>

Title: Looking for WP 3.0 sample posts data