问: When and how do browsers render

答:
Scope of CSS

A style element applies to the whole document, regardless of its position. It is applied as soon as it's loaded.

Reason for putting style tags in

Since every browser has a limited number of threads for downloading a page's files (like JS, CSS, images and asynchronously loaded HTML, JSON or XML), people tend to include CSS files at the end of the body element instead of the classic approach of including them in the head element. This way the rest of the page can be loaded and rendered, and the styling is applied last. You would go this way if your CSS is purely for the looks (i.e. no required element hiding) in order to improve the user experience.

CSS files vs style rules in HTML

Including an external CSS file or putting the same rules in a style element have equivalent results regarding layout and styling. The external file has the downside of a little HTTP overhead, but the benefit of being cached for any further request. If your site consists of more than one page, you usually want to have one or more CSS files that are downloaded only once and re-used for most pages. In addition you can have page-specific rules in another file or within the HTML page.

Body: I noticed that if I place

Body:
Scope of CSS

A style element applies to the whole document, regardless of its position. It is applied as soon as it's loaded.

Reason for putting style tags in <body>

Since every browser has a limited number of threads for downloading a page's files (like JS, CSS, images and asynchronously loaded HTML, JSON or XML), people tend to include CSS files at the end of the body element instead of the classic approach of including them in the head element. This way the rest of the page can be loaded and rendered, and the styling is applied last. You would go this way if your CSS is purely for the looks (i.e. no required element hiding) in order to improve the user experience.

CSS files vs style rules in HTML

Including an external CSS file or putting the same rules in a style element have equivalent results regarding layout and styling. The external file has the downside of a little HTTP overhead, but the benefit of being cached for any further request. If your site consists of more than one page, you usually want to have one or more CSS files that are downloaded only once and re-used for most pages. In addition you can have page-specific rules in another file or within the HTML page.


来源: stackexchange

问:
Filter divs based on dropdown select - is there an easy way?
I have a grid made up of divs that have wordpress page IDs as classes, they also have the common class 'set'.

I have a dropdown select that contain each page as an <option> with the page ID as the value.

I want to be able to select a page title in the dropdown menu, and have any corresponding div in the grid with the class 'patient-pageID' only to be visible, and all others hidden.

```<code>$('#filterPatient_dropdown').change(function() {
    var patientID = $("#filterPatient_dropdown option:selected").val();
    $('.set').hide();
    if ($(this).val() == 'patient'+patientID) {
        $(this).show();
    }
});
</code>```

This just hides all the divs when I click on an option.

How can I perform a simple yet effective filter where I click on an option, where the value is the page ID, and it finds the matching class of all divs and only shows these?

答:
How about this one?</p>

```<code>$('#filterPatient_dropdown').change(function() {
    var patientID = $(this).find("option:selected").val();
    $('.set').hide();
    $('div.patient-'+patientID).show();
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a grid made up of divs that have wordpress page IDs as classes, they also have the common class 'set'.

I have a dropdown select that contain each page as an <option> with the page ID as the value.

I want to be able to select a page title in the dropdown menu, and have any corresponding div in the grid with the class 'patient-pageID' only to be visible, and all others hidden.

$('#filterPatient_dropdown').change(function() {
    var patientID = $("#filterPatient_dropdown option:selected").val();
    $('.set').hide();
    if ($(this).val() == 'patient'+patientID) {
        $(this).show();
    }
});

This just hides all the divs when I click on an option.

How can I perform a simple yet effective filter where I click on an option, where the value is the page ID, and it finds the matching class of all divs and only shows these?

Body:
How about this one?

$('#filterPatient_dropdown').change(function() {
    var patientID = $(this).find("option:selected").val();
    $('.set').hide();
    $('div.patient-'+patientID).show();
});


问:
In MDX how can I filter a dimension/axis based on a TopCount
I have cube which contains geographic sales data. I want to pull sales of product items from all stores, based on the top 5 sellers from an arbitrary known store (BTW this is a simplified version of the real issue).

In sql (shame on me) this would be

```<code>select StoreId, ProductId, Sales from cube where ProductId in
    (select top 5 ProductId from cube where Store = @Store order by Sales desc)
</code>```

答:
You can use the Topcount function for this. Provided you have dimensions named Product and Store and a measure named [Sales]:

```<code>Select [Measures].[Sales] On Columns,
       CrossJoin([Store].Members,Generate(Topcount(Crossjoin({[Store].@[<StoreId>]},[Product].Members),5,[Measures].[Sales]),[Product].CurrentMember)) On Rows
  From [Yourcube]
</code>```

Replace <StoreId> with the specific store you're interested in. Generate will loop through the top 5 found for the specific store and return only the Product members. This result is then crossjoined with all the stores.

ContentLicense: CC BY-SA 2.5

Body:
I have cube which contains geographic sales data. I want to pull sales of product items from all stores, based on the top 5 sellers from an arbitrary known store (BTW this is a simplified version of the real issue).

In sql (shame on me) this would be

select StoreId, ProductId, Sales from cube where ProductId in
    (select top 5 ProductId from cube where Store = @Store order by Sales desc)

Body:
You can use the Topcount function for this. Provided you have dimensions named Product and Store and a measure named [Sales]:

Select [Measures].[Sales] On Columns,
       CrossJoin([Store].Members,Generate(Topcount(Crossjoin({[Store].@[<StoreId>]},[Product].Members),5,[Measures].[Sales]),[Product].CurrentMember)) On Rows
  From [Yourcube]

Replace <StoreId> with the specific store you're interested in. Generate will loop through the top 5 found for the specific store and return only the Product members. This result is then crossjoined with all the stores.


问:
Why doesn't my wait method wait until 30 seconds?
Why doesn't my wait method wait until 30 seconds?

My method should timeout after 30seconds if the method cannot find the element, currently return true or false without any timeout, any ideas?

```<code>    public boolean WaitUntilWebElementIsVisiblePredicate(WebElement element) {
FluentWait<WebElement> wait = new FluentWait<WebElement>(element)
        .withTimeout(30, TimeUnit.SECONDS)
        .pollingEvery(100, TimeUnit.MILLISECONDS)
        .ignoring(NoSuchFieldException.class);

Function<WebElement, Boolean> f = new Function<WebElement, Boolean>() {
    @Override
    public Boolean apply(WebElement element) {
        if (!element.isDisplayed()) {
            System.out.println("Method failed: WaitUntilWebElementIsVisiblepPredicate, using locator: " + element.toString());
            return false;
        }
        System.out.println("Element visible, using method: WaitUntilWebElementIsVisiblepPredicate, Locator: " + element.toString());
        return true;
    }
};
return wait.until(f);
}
</code>```

答:
Once the condition in apply(WebElement element) returned false, the code wait for the time defined in pollingEvery. Then, the actual start time (which is captured at the start by FluentWait) is compared with the current time. If the difference of the wait start time and the current time is less than the time set in withTimeout(30, TimeUnit.SECONDS) the function f is executed again until either the timeout expires or the condition becomes true.

So IMO, if it has returned earlier than the timeout period, the apply(WebElement element) seems to have returned true.

Look at the method signature here.

Body:
Why doesn't my wait method wait until 30 seconds?

My method should timeout after 30seconds if the method cannot find the element, currently return true or false without any timeout, any ideas?

    public boolean WaitUntilWebElementIsVisiblePredicate(WebElement element) {
FluentWait<WebElement> wait = new FluentWait<WebElement>(element)
        .withTimeout(30, TimeUnit.SECONDS)
        .pollingEvery(100, TimeUnit.MILLISECONDS)
        .ignoring(NoSuchFieldException.class);

Function<WebElement, Boolean> f = new Function<WebElement, Boolean>() {
    @Override
    public Boolean apply(WebElement element) {
        if (!element.isDisplayed()) {
            System.out.println("Method failed: WaitUntilWebElementIsVisiblepPredicate, using locator: " + element.toString());
            return false;
        }
        System.out.println("Element visible, using method: WaitUntilWebElementIsVisiblepPredicate, Locator: " + element.toString());
        return true;
    }
};
return wait.until(f);
}


问:
How to create/generate/export a file from my webpack 2 config to be used inside of my React code?
I am passing in NODE_ENV variables into my webpack.config from package.json in order to return an object that either contains API endpoints for localhost or production.

1) package.json

```<code>"scripts": {
    "dev": "NODE_ENV=development webpack-dev-server --history-api-fallback",
    "prod": "NODE_ENV=production webpack -p",
    "build": "NODE_ENV=production webpack -p"
}
</code>```

2) endpoints.js

```<code>function endpoints(env) {
    let prefix = env === 'development' ? 'http://localhost' : '';

    return {
        "login": `${prefix}/app/api/login`
    }
}

module.exports = endpoints;
</code>```

3) webpack.config

```<code>const webpack = require('webpack')
const HtmlWebpackPlugin = require("html-webpack-plugin");
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const CopyWebpackPlugin = require("copy-webpack-plugin");
const path = require("path");
const dist = path.resolve(__dirname, "dist");
const src = path.resolve(__dirname, "src");
const endpoints = require("./src/endpoints");
const api = endpoints(process.env.NODE_ENV);

console.log('webpack api', api);

module.exports = {
  context: src,
  entry: [
    "./index.js"
  ],
  output: {
    path: dist,
    // ....
</code>```

Here below I can see the console.log of the const api.

Now my question is, how do I now generate or export out an actual file api to be used inside of my src/services/api file:

```<code>import axios from 'axios'
// import api from '../../webpack.config' <-- ?
// import api from '../../api.js <-- ?

const log = (method, err) => {
    console.error(`%c${method}`, 'background: #393939; color: #F25A43', err);
    return null;
};

export const userLogin = (username, password) => {
    const post_data = { username, password };
    return axios.post('http://localhost/app/api/login', post_data)  // <-- api to be used here
        .then(res => res)
        .catch((err) => log('api.userLogin', err));
};
</code>```

答: I think this is an XY problem. You could generate the files with a bit of Node (something like fs.writeFileSync('api.js', contents), or you could do it with a bit of shell scripting, but you could also just use env in your code using DefinePlugin (example: new webpack.DefinePlugin({ env: JSON.stringify(process.env.NODE_ENV) }). Then you'd be able to access env in your code directly.

Body:
I am passing in NODE_ENV variables into my webpack.config from package.json in order to return an object that either contains API endpoints for localhost or production.

1) package.json

"scripts": {
    "dev": "NODE_ENV=development webpack-dev-server --history-api-fallback",
    "prod": "NODE_ENV=production webpack -p",
    "build": "NODE_ENV=production webpack -p"
}

2) endpoints.js

function endpoints(env) {
    let prefix = env === 'development' ? 'http://localhost' : '';

    return {
        "login": `${prefix}/app/api/login`
    }
}

module.exports = endpoints;

3) webpack.config

const webpack = require('webpack')
const HtmlWebpackPlugin = require("html-webpack-plugin");
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const CopyWebpackPlugin = require("copy-webpack-plugin");
const path = require("path");
const dist = path.resolve(__dirname, "dist");
const src = path.resolve(__dirname, "src");
const endpoints = require("./src/endpoints");
const api = endpoints(process.env.NODE_ENV);

console.log('webpack api', api);

module.exports = {
  context: src,
  entry: [
    "./index.js"
  ],
  output: {
    path: dist,
    // ....

Here below I can see the console.log of the const api.

Now my question is, how do I now generate or export out an actual file api to be used inside of my src/services/api file:

import axios from 'axios'
// import api from '../../webpack.config' <-- ?
// import api from '../../api.js <-- ?

const log = (method, err) => {
    console.error(`%c${method}`, 'background: #393939; color: #F25A43', err);
    return null;
};

export const userLogin = (username, password) => {
    const post_data = { username, password };
    return axios.post('http://localhost/app/api/login', post_data)  // <-- api to be used here
        .then(res => res)
        .catch((err) => log('api.userLogin', err));
};


问:
Countif with dates does not work
I couldn't find a similar question that's why I asked a new one.

I have a worksheet with two columns - first column shows month and year in the following format "mon.year", for example "apr.2017" and the second one shows a number. The number must represent the count of some other dates filtered by specific criteria. I have those dates in another sheet - one column with name and one with a date.
What I want to do is count the number of dates for example from june 2017 from the second sheet and place the number  in the second column in the first sheet.

Here is how the first sheet looks like:

And this is how the second sheet with data looks like:

The result I'm looking for is this:

So, I tried the following code but I can't figure out why it doesn't work.

Any suggestions how to improve the formula?

EDIT: So, both the comments below were helpful for me but as the formula had to be simplified at most (my colleagues work with the excel file, not me) I chose to calculate the month and year in two hidden columns, then use the countif formula on them.

Title: Countif with dates does not work

Body:
You will need to bracket the dates:

=COUNTIFS('1'$B$2:$B$26,">=" & EOMONTH(A2,-1)+1,'1'$B$2:$B$26, "<" & EOMONTH(A2,0)+1)


问:
Count keywords occurrence in a file to another file
I have two files File1 and File2. I have to find keywords in File2 to File1 and count it. Lines in File1 that don't have any keywords in File2 shall be counted as OTHERS and probably save it in File3 (for validation).

File1

```<code> 000001111YYYY0000
 122334YYYY9999
 89898989AAAA89899
 AAAA7678989812234
 ZZZZ878098098098
 0000000000000000
</code>```

File2

```<code>YYYY
AAAA
ZZZZ
</code>```

Output

```<code>YYYY: 2
AAAA: 2
ZZZZ: 1
OTHERS: 1
</code>```

File3 (OTHERS)

```<code>0000000000000000
</code>```

The way I know is to count the keywords using grep and wc -l, and its not ideal especially when I have many keywords to find.

答:
awk solution (including saving "others" into separate file file3.txt):

```<code>awk 'NR==FNR{ group=(group)?group"|"$0 : $0; next }
     { if(match($0,group)){ a[substr($0,RSTART,RLENGTH)]++ }
       else { a["OTHERS"]++; print >> "file3.txt" }
     } END { for(i in a) print i": "a[i] }' file2 file1
</code>```

The output:

```<code>ZZZZ: 1
AAAA: 2
YYYY: 2
OTHERS: 1
</code>```

Others:

```<code>cat file3.txt
0000000000000000
</code>```

Body:
I have two files File1 and File2. I have to find keywords in File2 to File1 and count it. Lines in File1 that don't have any keywords in File2 shall be counted as OTHERS and probably save it in File3 (for validation).

File1

 000001111YYYY0000
 122334YYYY9999
 89898989AAAA89899
 AAAA7678989812234
 ZZZZ878098098098
 0000000000000000

File2

YYYY
AAAA
ZZZZ

Output

YYYY: 2
AAAA: 2
ZZZZ: 1
OTHERS: 1

File3 (OTHERS)

0000000000000000

The way I know is to count the keywords using grep and wc -l, and its not ideal especially when I have many keywords to find.

Body:
awk solution (including saving "others" into separate file file3.txt):

awk 'NR==FNR{ group=(group)?group"|"$0 : $0; next }
     { if(match($0,group)){ a[substr($0,RSTART,RLENGTH)]++ }
       else { a["OTHERS"]++; print >> "file3.txt" }
     } END { for(i in a) print i": "a[i] }' file2 file1

The output:

ZZZZ: 1
AAAA: 2
YYYY: 2
OTHERS: 1

Others:

cat file3.txt
0000000000000000


问:
cannot set property 'color' of undefined
I'm trying to create a custom error message and styling based on validation (I know about plugins, but the time involved in coordinating the validation plugin with Materialize is too much for a single field).

HTML:

```<code><div class="input-field inline center-align">
  <input id="quantity" name="quantity" type="number" class="">
  <label for="qty" data-error="wrong" data-success="right"
       class="active">Qty</label>
  <span id="qty-error">really?</span>
</div>
</code>```

JS:

```<code>$('#quantity').change(function(){
  var $Qty = $(this).val();
  var $Label = $('#qty-error');
  if ($Qty > 0 && $Qty <= $AvailTix){
      $Label.html('seems reasonable');
      $Label.style.color = '#8e8ef5';
      $(this).addClass('valid');
  } else if ($Qty < 1){
      $Label.html('really?');
      $Label.style.color ='#f96d63';
      $(this).addClass('invalid');
  }
});
</code>```

What's confusing me is that the $Label.html piece is working. It changes the text. But I get this error in the console for the $Label.style.color line:

Uncaught TypeError: Cannot set property 'color' of undefined

答:
Your problem is that you are trying to access a DOM property styleon a jQuery object, that's why you got Cannot set property 'color' of undefined.

In your code $Label is a jQuery object and don't have a style property because .style is a DOM object property so you can't use it with a jQuery object.

You need to use .css() method instead:

```<code>$Label.css('color', '#8e8ef5');
</code>```

For more details you can read jQuery object and DOM element.

Body:
I'm trying to create a custom error message and styling based on validation (I know about plugins, but the time involved in coordinating the validation plugin with Materialize is too much for a single field).

HTML:

  <input id="quantity" name="quantity" type="number" class="">
  Qty
  really?

JS:

$('#quantity').change(function(){
  var $Qty = $(this).val();
  var $Label = $('#qty-error');
  if ($Qty > 0 && $Qty <= $AvailTix){
      $Label.html('seems reasonable');
      $Label.style.color = '#8e8ef5';
      $(this).addClass('valid');
  } else if ($Qty < 1){
      $Label.html('really?');
      $Label.style.color ='#f96d63';
      $(this).addClass('invalid');
  }
});

What's confusing me is that the $Label.html piece is working. It changes the text. But I get this error in the console for the $Label.style.color line:

Uncaught TypeError: Cannot set property 'color' of undefined

Body:
Your problem is that you are trying to access a DOM property styleon a jQuery object, that's why you got Cannot set property 'color' of undefined.

In your code $Label is a jQuery object and don't have a style property because .style is a DOM object property so you can't use it with a jQuery object.

You need to use .css() method instead:

$Label.css('color', '#8e8ef5');

For more details you can read jQuery object and DOM element.


问:
using dynamic linq to filter a list of objects
I have two class like this

```<code>public class Error{
   public string Code{get;set;}
   public string Description{get;set;}
}

public class Row{
   public List<Error> Errors {get;set;}
   ....
}
</code>```

So, for each row, can exists more errors.
It's possible using dynamic linq select the row that have an error code(for example Code1)?

So, if the row contains Code1 and Code2, i want select the row.

if in the example below query has a list of rows i want a query like this

```<code>query.Where("Errors != null && Errors.Code.contains('Code1')")
</code>```

答:
It's possible using dynamic linq select the row that have an error code(for example Code1)?

The way I understand it, you have something like this

```<code>IQueryable<Row> query = ...;
string code = "Code1";
</code>```

and you want the Dynamic LINQ equivalent of the following static query:

```<code>var result = query
   .Where(row => row.Errors != null && row.Errors.Any(error => error.Code == code));
</code>```

Since in Dynamic LINQ every Enumerable extension method lambda enters a separate "scope", the members inside are accessible through special it identifier or no identifier at all. Also it allows you to pass parameters and refer to them inside the query string by index using @p0, @p1 etc.

Hence the equivalent Dynamic LINQ query of the above could be like this:

```<code>var result = query
    .Where("Errors != null && Errors.Any(Code == @0)", code);
</code>```

If instead of exact match you want string.Contains, simply replace Code == @0 with Code.Contains(@p0).

Of course you could embed the string literal value inside, but keep it mind it requires to be surrounded with double quotation marks ("):

```<code>var result = query
    .Where("Errors != null && Errors.Any(Code == \"Code1\")");
</code>```

Body:
I have two class like this

public class Error{
   public string Code{get;set;}
   public string Description{get;set;}
}

public class Row{
   public List<Error> Errors {get;set;}
   ....
}

So, for each row, can exists more errors.
It's possible using dynamic linq select the row that have an error code(for example Code1)?

So, if the row contains Code1 and Code2, i want select the row.

if in the example below query has a list of rows i want a query like this

query.Where("Errors != null && Errors.Code.contains('Code1')")

Body:
It's possible using dynamic linq select the row that have an error code(for example Code1)?

The way I understand it, you have something like this

IQueryable<Row> query = ...;
string code = "Code1";

and you want the Dynamic LINQ equivalent of the following static query:

var result = query
   .Where(row => row.Errors != null && row.Errors.Any(error => error.Code == code));

Since in Dynamic LINQ every Enumerable extension method lambda enters a separate "scope", the members inside are accessible through special it identifier or no identifier at all. Also it allows you to pass parameters and refer to them inside the query string by index using @p0, @p1 etc.

Hence the equivalent Dynamic LINQ query of the above could be like this:

var result = query
    .Where("Errors != null && Errors.Any(Code == @0)", code);

If instead of exact match you want string.Contains, simply replace Code == @0 with Code.Contains(@p0).

Of course you could embed the string literal value inside, but keep it mind it requires to be surrounded with double quotation marks ("):

var result = query
    .Where("Errors != null && Errors.Any(Code == \"Code1\")");


问:
C++ Printing Odd numbers instead of Prime Numbers
I have been working on an assignment question for days and cannot seem to get the correct output (I've tried so many things!) The question is:

Write a program that uses two nested for loops and the modulus operator (%) to detect and print the prime numbers from 1 to 10,000.

I have been doing from 1 to 10 as a small test to ensure its working. I am getting 2,3,5,7,9 as my output, so I know something is wrong. When I increase the number from 10 to 20 it is printing 2 plus all odd numbers. I am including my code below. Thanks!!

```<code>int main() {

        for (int i=2; i <=10; i++){
            for (int j=2; j<=i; j++){
                if (i%j==0 && j!=i) {

                    break;
                }

                else {

                    cout<< i <<endl;
                    break;
                }
            }
        }
}
</code>```

答:
You are breaking the inner loop after the first iteration itself, which is checking if the number(ie i) is different from j and is  divisible by 2 or not (since j=2 for the first iteration)

I am getting 2,3,5,7,9 as my output

This is because every odd number fails the if and is printed in else condition

Body:
I have been working on an assignment question for days and cannot seem to get the correct output (I've tried so many things!) The question is:

Write a program that uses two nested for loops and the modulus operator (%) to detect and print the prime numbers from 1 to 10,000.

I have been doing from 1 to 10 as a small test to ensure its working. I am getting 2,3,5,7,9 as my output, so I know something is wrong. When I increase the number from 10 to 20 it is printing 2 plus all odd numbers. I am including my code below. Thanks!!

int main() {

        for (int i=2; i <=10; i++){
            for (int j=2; j<=i; j++){
                if (i%j==0 && j!=i) {

                    break;
                }

                else {

                    cout<< i <<endl;
                    break;
                }
            }
        }
}


问:
How to get a specific part of a URL using PHP
I've had a look around and can't find an answer specific to my needs...

This is the URL being sent back to my redirect page from an identity server: http://localhost/?code=92092c2f65560d835a73cda852393316&state=random_state&session_state=CEwifhoy_x1RJWH-DoV_9Q1yJVNUXV4z5YRGGuXsUvs.39c667f469b8f6585a9f699d0b7d76f3

I need to get the code between "code=" and "&state".

Then put it in the <> part of "grant_type=authorization_code&code=<>&redirect_uri=<>" so I can request a token. This part I can do, I just can't figure out how to get the code out of the URL.

Thanks.

答:
You should just use $_GET environment variable.
All these data after the file address itself (in your case /) and ? sign are GET data.
To retrieve "code" value you should use:

```<code>$variable = $_GET['code'];
</code>```

It's just as simple as that.

Body:
You should just use $_GET environment variable.
All these data after the file address itself (in your case /) and ? sign are GET data.
To retrieve "code" value you should use:

$variable = $_GET['code'];

It's just as simple as that.


问:
Runtime issues while using Proguard to minify
My app is completely ready to deploy and its using many libraries. I want to minify the code using Proguard and also want to remove unused classes and resources but while using proguard I am getting Runtime error

```<code>java.lang.RuntimeException: Unable to create application com.rig.onblick.App: java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.hashCode()' on a null object reference
</code>```

I gone through many tutorial but its seems too complicated to write proguard configuration because I have to write many rules to make sure my app will run perfectly. I have never used proguard in this kind of big project. Can anyone tell me the minimal configuration which make sure at least my code will be minified and will not get any runtime error.

My present configuration is as below.

```<code>-dontwarn com.witt.mspapp.**

-keep class com.github.mikephil.** { *; }
-dontwarn com.github.mikephil.**

-keep class com.github.mikephil.** { *; }
-dontwarn org.apache.**

-keep class com.google.gms.** { *; }
-dontwarn com.google.gms.**

-keep class com.viewpagerindicator.** { *; }
-dontwarn com.viewpagerindicator.**

-keep class org.jivesoftware.smackx.** { *; }
-dontwarn org.jivesoftware.smackx.**
</code>```

I am testing in debug env. and my gradle configuration is as below

```<code>debug {
            minifyEnabled true
            shrinkResources true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
</code>```

答: There is nothing "minimal configuration" for proguard configuration. You will get the proguard configuration for each library on his official repo page. So whatever dependencies you have used go through these and add proguard configuration for each of that dependency.</p>

Body:
My app is completely ready to deploy and its using many libraries. I want to minify the code using Proguard and also want to remove unused classes and resources but while using proguard I am getting Runtime error

java.lang.RuntimeException: Unable to create application com.rig.onblick.App: java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.hashCode()' on a null object reference

I gone through many tutorial but its seems too complicated to write proguard configuration because I have to write many rules to make sure my app will run perfectly. I have never used proguard in this kind of big project. Can anyone tell me the minimal configuration which make sure at least my code will be minified and will not get any runtime error.

My present configuration is as below.

-dontwarn com.witt.mspapp.**

-keep class com.github.mikephil.** { *; }
-dontwarn com.github.mikephil.**

-keep class com.github.mikephil.** { *; }
-dontwarn org.apache.**

-keep class com.google.gms.** { *; }
-dontwarn com.google.gms.**

-keep class com.viewpagerindicator.** { *; }
-dontwarn com.viewpagerindicator.**

-keep class org.jivesoftware.smackx.** { *; }
-dontwarn org.jivesoftware.smackx.**

I am testing in debug env. and my gradle configuration is as below

debug {
            minifyEnabled true
            shrinkResources true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }


问:
How to set up a web service to talk to my Windows Phone app?
Hi and thanks for looking. Is there a way I can take in parameters from the user in my Windows Phone app, and use something like SOAP to talk to a web service and have it return an xml file? How can I host that web service for the minimum possible cost and hassle? If you could even point me to a link/tutorial, that'd be great.</p>

答:
Yes, you can do this using a number of technologies. You can use WCF for example.

There's two things for you to look at.

First is implementing the service. Here's a quick walkthrough for that - refer the first screencast.

WCF Screencasts

Second is referencing the service from your WP7 app. Here's a quick walkthrough for that. Scroll right to his first tutorial.

AfricanGeek Silverlight 3 Video Tutorials

For hosting you can look at any of the many shared web service hosting providers.


问:
UICollectionView horizantal scrolling Photo Gallery with swift
I'm trying to make a Photo Gallery using UICollectionView with Swift. I want to display photos in full screen and swipe right to get to the next image. I have a working code for the portrait frame but as soon as I go to landscape it seems like my cell doesn't re-adjust itself to the correct position and size.

Meaning that it keeps the same width,height, x position and y position of the portrait screen at all times. I also get this error on both portrait and landscape frame:

->the behavior of the UICollectionViewFlowLayout is not defined because:

->the item height must be less that the height of the UICollectionView minus the section insets top and bottom values.

I have looked all over the web for an answer and have tried all possible solutions but it doesn't seem to be working for me. Let me know if anyone can help out with this. Much appreciated.

Here is my code :

```<code>import UIKit

class ImageDetailViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout,UINavigationControllerDelegate {

@IBOutlet weak var imgDetailCollectionView: UICollectionView!

var index: Int!
var imageItems: Array<Items> = []
var currentIndex: CGFloat!
var size = UIScreen.mainScreen().bounds.size
init(index: Int , imageItems: Array<Items>) {
    self.index = index
    self.imageItems = imageItems
    super.init(nibName: "ImageDetailViewController", bundle: NSBundle.mainBundle())
}

required init(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

override func viewDidLoad() {
    super.viewDidLoad()

    imgDetailCollectionView.registerNib(UINib(nibName: "ImageDetailCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "ImageDetailCollectionViewCell")
    //self.automaticallyAdjustsScrollViewInsets = false
    imgDetailCollectionView.setZoomScale(0.5, animated: true)

}

override func viewDidLayoutSubviews() {
    imgDetailCollectionView.scrollRectToVisible(CGRectMake(320 * CGFloat(index), 0, 320 , 240), animated: false)
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{

    return self.imageItems.count
}

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell{

    var cell = imgDetailCollectionView.dequeueReusableCellWithReuseIdentifier("ImageDetailCollectionViewCell", forIndexPath: indexPath) as ImageDetailCollectionViewCell

    cell.setup(imageItems[indexPath.row].url!)

    if(UIDeviceOrientationIsPortrait(UIDevice.currentDevice().orientation)){

        self.imgDetailCollectionView.collectionViewLayout.invalidateLayout()

        var frame = cell.frame
        frame.size = CGSizeMake(size.width, size.height)
        cell.frame = frame

    }else{
        self.imgDetailCollectionView.collectionViewLayout.invalidateLayout()

        var frame = cell.frame
        frame.size = CGSizeMake(size.height, size.width)
        cell.frame = frame
    }

    return cell

}

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {

    var size = UIScreen.mainScreen().bounds.size

    if(UIDeviceOrientationIsPortrait(UIDevice.currentDevice().orientation)){

        return CGSizeMake(size.width, size.height)

    }else{

        return CGSizeMake(size.height, size.width)
    }

}

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat {
    return 0
}

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat {
    return 0
}

override func willRotateToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) {
    self.imgDetailCollectionView.collectionViewLayout.invalidateLayout()

    var currentOffset = self.imgDetailCollectionView.contentOffset
    self.currentIndex = currentOffset.x / imgDetailCollectionView.frame.size.width

}

override func didRotateFromInterfaceOrientation(fromInterfaceOrientation: UIInterfaceOrientation) {

    var currentSize = imgDetailCollectionView.bounds.size
    var offset = self.currentIndex * currentSize.width
    imgDetailCollectionView.setContentOffset(CGPointMake(offset, 0), animated: false)

    imgDetailCollectionView.reloadData()
}

override func willAnimateRotationToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) {

    self.imgDetailCollectionView.collectionViewLayout.invalidateLayout()
}
}
</code>```

答:
This error might be printed because of next line:

var size = UIScreen.mainScreen().bounds.size

For fast check you can type for example:

var size = UIScreen.mainScreen().bounds.size * 0.25

If error message dissapear, you should follow instructions from message and subtract collectionView's contentInsets and sectionInsets from available height (collectionView.bounds.height).

Doing so, you will avoid situation in which cell height is trying to be 'higher' than it's collectionView.

Body:
I'm trying to make a Photo Gallery using UICollectionView with Swift. I want to display photos in full screen and swipe right to get to the next image. I have a working code for the portrait frame but as soon as I go to landscape it seems like my cell doesn't re-adjust itself to the correct position and size.

Meaning that it keeps the same width,height, x position and y position of the portrait screen at all times. I also get this error on both portrait and landscape frame:

->the behavior of the UICollectionViewFlowLayout is not defined because:

->the item height must be less that the height of the UICollectionView minus the section insets top and bottom values.

I have looked all over the web for an answer and have tried all possible solutions but it doesn't seem to be working for me. Let me know if anyone can help out with this. Much appreciated.

Here is my code :

import UIKit

class ImageDetailViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout,UINavigationControllerDelegate {

@IBOutlet weak var imgDetailCollectionView: UICollectionView!

var index: Int!
var imageItems: Array<Items> = []
var currentIndex: CGFloat!
var size = UIScreen.mainScreen().bounds.size
init(index: Int , imageItems: Array<Items>) {
    self.index = index
    self.imageItems = imageItems
    super.init(nibName: "ImageDetailViewController", bundle: NSBundle.mainBundle())
}

required init(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

override func viewDidLoad() {
    super.viewDidLoad()

    imgDetailCollectionView.registerNib(UINib(nibName: "ImageDetailCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "ImageDetailCollectionViewCell")
    //self.automaticallyAdjustsScrollViewInsets = false
    imgDetailCollectionView.setZoomScale(0.5, animated: true)

}

override func viewDidLayoutSubviews() {
    imgDetailCollectionView.scrollRectToVisible(CGRectMake(320 * CGFloat(index), 0, 320 , 240), animated: false)
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{

    return self.imageItems.count
}

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell{

    var cell = imgDetailCollectionView.dequeueReusableCellWithReuseIdentifier("ImageDetailCollectionViewCell", forIndexPath: indexPath) as ImageDetailCollectionViewCell

    cell.setup(imageItems[indexPath.row].url!)

    if(UIDeviceOrientationIsPortrait(UIDevice.currentDevice().orientation)){

        self.imgDetailCollectionView.collectionViewLayout.invalidateLayout()

        var frame = cell.frame
        frame.size = CGSizeMake(size.width, size.height)
        cell.frame = frame

    }else{
        self.imgDetailCollectionView.collectionViewLayout.invalidateLayout()

        var frame = cell.frame
        frame.size = CGSizeMake(size.height, size.width)
        cell.frame = frame
    }

    return cell

}

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {

    var size = UIScreen.mainScreen().bounds.size

    if(UIDeviceOrientationIsPortrait(UIDevice.currentDevice().orientation)){

        return CGSizeMake(size.width, size.height)

    }else{

        return CGSizeMake(size.height, size.width)
    }

}

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat {
    return 0
}

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat {
    return 0
}

override func willRotateToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) {
    self.imgDetailCollectionView.collectionViewLayout.invalidateLayout()

    var currentOffset = self.imgDetailCollectionView.contentOffset
    self.currentIndex = currentOffset.x / imgDetailCollectionView.frame.size.width

}

override func didRotateFromInterfaceOrientation(fromInterfaceOrientation: UIInterfaceOrientation) {

    var currentSize = imgDetailCollectionView.bounds.size
    var offset = self.currentIndex * currentSize.width
    imgDetailCollectionView.setContentOffset(CGPointMake(offset, 0), animated: false)

    imgDetailCollectionView.reloadData()
}

override func willAnimateRotationToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) {

    self.imgDetailCollectionView.collectionViewLayout.invalidateLayout()
}
}


问:
How to return object with its ManyToManyField related object
I have a model, for example, A has a field xxx (ManyToManyField with B model). How can I query and return like:

```<code>{
   'f1': 'xxx',
   'f2': 'yyy',
    photos: [{photo1}, {photo2},...]
}
</code>```

Any help is appreciated. I'm django newbie :D

答:
```<code>B.objects.get(pk=1).a.all().values()
</code>```

You can try this and get all the columns,  if you need specific you can pass them inside values.

Remember a is the model A or the model you want to use in all small letter

Body:
I have a model, for example, A has a field xxx (ManyToManyField with B model). How can I query and return like:

{
   'f1': 'xxx',
   'f2': 'yyy',
    photos: [{photo1}, {photo2},...]
}

Any help is appreciated. I'm django newbie :D

Body:
B.objects.get(pk=1).a.all().values()

You can try this and get all the columns,  if you need specific you can pass them inside values.

Remember a is the model A or the model you want to use in all small letter


问:
Counting coloured pixels on the GPU - Theory
I have a 128 by 128 pixel image.

It's broken down into an 8 by 8 grid.

Each grid block contains 16 by 16 pixels.

Requirement

I want to count how many black pixels my image contains.

The straight forward way:

I could do this by going row by row, column by column, over the whole image and checking if the pixel was black or not.

The GPU way

...but I'd like to know if using the GPU, I could break down the image into chunks/blocks and count all pixels in each block and then sum the results.

For example:

If you look at the top left of the image:

First block, 'A1' (Row A, Column 1) contains a grid of 16 by 16 pixels, I know by counting them manually, there are 16 blacks pixels.

Second block: 'A2', (Row A, Column 2) contains a grid of 16 by 16 pixels, I know by counting them manually, there are 62 blacks pixels.

All other blocks for this example are blank/empty.

If I ran my image through my program, I should get the answer: 16 + 62 = 78 Black pixels.

Reasoning

It's my understanding that the GPU can operate on a lot of data in parallel, effectively running a small program on a chunk of data spread across multiple GPU threads.
I'm not worried about speed/performance, I'd just like to know if this is something the GPU can/could do?

答:
There is a lot a GPU can do here.

I am not sure if you are looking for an algorithm here but I can point you to a wide used GPU library which implements an efficient counting procedure. Take a look at the count function within the thrust library: https://thrust.github.io/doc/group__counting.html

It works taking as an input a predicate function. It counts the number of occurrences of the input data which satisfy the predicate.

The follows counts the number of elements in data which are equals to zero.

```<code>template <typename T>
struct zero_pixel{
  __host__ __device__ bool operator()(const T &x) const {return x == 0;}
};
thrust::count_if(data.begin(), data.end(), zero_pixel<T>())
</code>```

A working example here:  https://github.com/thrust/thrust/blob/master/testing/count.cu

You should code a predicate which tests whether a pixel is black or not (depending on what a pixel is for you (it could be an RGB triplet and in this case, the predicate should be a bit more elaborate).

I would also linearize the pixels into a linear and iterable data structure (but that depends on what your data actually is).

If you are interested in the histogram approach what you can do is sort the pixels of the image (using any GPU efficient algorithm or, why not the thrust implementation of sort, thrust::sort(...) ) data in order to group equal elements together and then perform a reduction by key thrust::reduce_by_key.

Take a look at this example: https://github.com/thrust/thrust/blob/master/examples/histogram.cu

Note that the histogram approach is a bit more costly because it solves a bigger problem (counts the number of occurrences of all the unique elements).

Body:
There is a lot a GPU can do here.

I am not sure if you are looking for an algorithm here but I can point you to a wide used GPU library which implements an efficient counting procedure. Take a look at the count function within the thrust library: https://thrust.github.io/doc/group__counting.html

It works taking as an input a predicate function. It counts the number of occurrences of the input data which satisfy the predicate.

The follows counts the number of elements in data which are equals to zero.

template <typename T>
struct zero_pixel{
  __host__ __device__ bool operator()(const T &x) const {return x == 0;}
};
thrust::count_if(data.begin(), data.end(), zero_pixel<T>())

A working example here:  https://github.com/thrust/thrust/blob/master/testing/count.cu

You should code a predicate which tests whether a pixel is black or not (depending on what a pixel is for you (it could be an RGB triplet and in this case, the predicate should be a bit more elaborate).

I would also linearize the pixels into a linear and iterable data structure (but that depends on what your data actually is).

If you are interested in the histogram approach what you can do is sort the pixels of the image (using any GPU efficient algorithm or, why not the thrust implementation of sort, thrust::sort(...) ) data in order to group equal elements together and then perform a reduction by key thrust::reduce_by_key.

Take a look at this example: https://github.com/thrust/thrust/blob/master/examples/histogram.cu

Note that the histogram approach is a bit more costly because it solves a bigger problem (counts the number of occurrences of all the unique elements).


答:
For Excel, a date/time is just a formatted number, the number of days since a fixed epoch.

"="&MONTH(A2) is an expression which concatenates the string = with the result of the function MONTH(A2), which is 1. The result of the expression is =1, which is what COUNTIFS sees.

You're actually telling COUNTIFS to match the date/time whose serial number is 1 (December 31, 1999 at midnight). Similarly, the second criteria will match exactly on July 9, 1905 at midnight.

My suggestion for you is to compute the month and year of each date on separate columns, and use COUNTIFS on these columns.

Title: Countif with dates does not work

Body:
I couldn't find a similar question that's why I asked a new one.

I have a worksheet with two columns - first column shows month and year in the following format "mon.year", for example "apr.2017" and the second one shows a number. The number must represent the count of some other dates filtered by specific criteria. I have those dates in another sheet - one column with name and one with a date.
What I want to do is count the number of dates for example from june 2017 from the second sheet and place the number  in the second column in the first sheet.

Here is how the first sheet looks like:

And this is how the second sheet with data looks like:

The result I'm looking for is this:

So, I tried the following code but I can't figure out why it doesn't work.

Any suggestions how to improve the formula?

EDIT: So, both the comments below were helpful for me but as the formula had to be simplified at most (my colleagues work with the excel file, not me) I chose to calculate the month and year in two hidden columns, then use the countif formula on them.


问:
Getting App Crashed error when deploying Rails application to Heroku
I followed all the guidelines given on the heroku blog for deploying a Rails app. I also my app got pushed successfully and created an app in my account. But when I try to run my site it gives me the following error:

```<code>App crashed
This application is temporarily offline.

If you're the administrator of this app, please check your heroku logs for the
backtrace.
</code>```

I tried to check the logs and here's what I got

```<code>C:\Users\raw\Desktop\html\rohit>heroku logs
Missing the Rails 2.3.8 gem. Please `gem install -v=2.3.8 rails`, update your RAILS_GEM_
VERSION setting in config/environment.rb for the Rails version you do have installed, or
 comment out RAILS_GEM_VERSION to use the latest version installed.

==> dyno-3674485.log (crash) <==
Missing the Rails 2.3.8 gem. Please `gem install -v=2.3.8 rails`, update your RAILS_GEM_
VERSION setting in config/environment.rb for the Rails version you do have installed, or
 comment out RAILS_GEM_VERSION to use the latest version installed.

-----> Rails can't find the expected version.

       Check to ensure you have specified the correct version of Rails in your
       Gemfile or .gems.  See http://docs.heroku.com/gems for details.

       You may also be affected by a gem dependency issue with rack.
       See http://docs.heroku.com/gem-dependency for details.

       Examine the backtrace above this message to debug.
</code>```

II have made a .gems file in my Rails_App directory:

```<code>rails -v '2.3.8'
pg
rack -v '1.1.0'
haml -v '3.0.13'
formtastic -v '0.9.8'
authlogic -v '2.1.5'
subdomain-fu -v '0.5.4'
compass -v '0.10.2'
compass-colors -v '0.3.1'
paperclip -v '2.3.3'
activemerchant -v '1.9.0'
icalendar
</code>```

What can I do to get this to work?

答:
Rails 2.3.8 is not compatible with rack 1.2.1 You can't define you .gems like that you have a "gem dependency issue with rack" like define.

Try with rake -v=1.1.0 the dependency of ActionPack 2.3.8 ( http://rubygems.org/gems/actionpack/versions/2.3.8)

Body:
I followed all the guidelines given on the heroku blog for deploying a Rails app. I also my app got pushed successfully and created an app in my account. But when I try to run my site it gives me the following error:

App crashed
This application is temporarily offline.

If you're the administrator of this app, please check your heroku logs for the
backtrace.

I tried to check the logs and here's what I got

C:\Users\raw\Desktop\html\rohit>heroku logs
Missing the Rails 2.3.8 gem. Please `gem install -v=2.3.8 rails`, update your RAILS_GEM_
VERSION setting in config/environment.rb for the Rails version you do have installed, or
 comment out RAILS_GEM_VERSION to use the latest version installed.

==> dyno-3674485.log (crash) <==
Missing the Rails 2.3.8 gem. Please `gem install -v=2.3.8 rails`, update your RAILS_GEM_
VERSION setting in config/environment.rb for the Rails version you do have installed, or
 comment out RAILS_GEM_VERSION to use the latest version installed.

-----> Rails can't find the expected version.

       Check to ensure you have specified the correct version of Rails in your
       Gemfile or .gems.  See http://docs.heroku.com/gems for details.

       You may also be affected by a gem dependency issue with rack.
       See http://docs.heroku.com/gem-dependency for details.

       Examine the backtrace above this message to debug.

II have made a .gems file in my Rails_App directory:

rails -v '2.3.8'
pg
rack -v '1.1.0'
haml -v '3.0.13'
formtastic -v '0.9.8'
authlogic -v '2.1.5'
subdomain-fu -v '0.5.4'
compass -v '0.10.2'
compass-colors -v '0.3.1'
paperclip -v '2.3.3'
activemerchant -v '1.9.0'
icalendar

What can I do to get this to work?


问:
How to generate multiple records based on column?
I have records like below. I would like to convert a single record into two records with values EXTERNAL and INTERNAL each if the 3rd attribute is All.

Input dataset:

```<code>Surender,cts,INTERNAL
Raja,cts,EXTERNAL
Ajay,tcs,All
</code>```

Expected output:

```<code>Surender,cts,INTERNAL
Raja,cts,EXTERNAL
Ajay,tcs,INTERNAL
Ajay,tcs,EXTERNAL
</code>```

My Spark Code :

```<code>case class Customer(name:String,organisation:String,campaign_type:String)

val custRDD = sc.textFile("/user/cloudera/input_files/customer.txt")

val mapRDD = custRDD.map(record => record.split(","))
    .map(arr => (arr(0),arr(1),arr(2))
    .map(tuple => {
      val name            = tuple._1.trim
      val organisation    = tuple._2.trim
      val campaign_type   = tuple._3.trim.toUpperCase
      Customer(name, organisation, campaign_type)
    })

mapRDD.toDF().registerTempTable("customer_processed")

sqlContext.sql("SELECT * FROM customer_processed").show
</code>```

Could Someone help me to fix this issue?

答:
Since it's Scala...

If you want to write a more idiomatic Scala code (and perhaps trading some performance due to lack of optimizations to have a more idiomatic code), you can use flatMap operator (removed the implicit parameter):

flatMap[U](func: (T) ⇒ TraversableOnce[U]): Dataset[U] Returns a new Dataset by first applying a function to all elements of this Dataset, and then flattening the results.

NOTE: flatMap is equivalent to explode function, but you don't have to register a UDF (as in the other answer).

A solution could be as follows:

```<code>// I don't care about the names of the columns since we use Scala
// as you did when you tried to write the code
scala> input.show
+--------+---+--------+
|     _c0|_c1|     _c2|
+--------+---+--------+
|Surender|cts|INTERNAL|
|    Raja|cts|EXTERNAL|
|    Ajay|tcs|     All|
+--------+---+--------+

val result = input.
  as[(String, String, String)].
  flatMap { case r @ (name, org, campaign) =>
    if ("all".equalsIgnoreCase(campaign)) {
      Seq("INTERNAL", "EXTERNAL").map { cname =>
        (name, org, cname)
      }
    } else Seq(r)
  }
scala> result.show
+--------+---+--------+
|      _1| _2|      _3|
+--------+---+--------+
|Surender|cts|INTERNAL|
|    Raja|cts|EXTERNAL|
|    Ajay|tcs|INTERNAL|
|    Ajay|tcs|EXTERNAL|
+--------+---+--------+
</code>```

Comparing performance of the two queries, i.e. flatMap-based vs explode-based queries, I think explode-based may be slightly faster and optimized better as some code is under Spark's control (using logical operators before they get mapped to physical couterparts). In flatMap the entire optimization is your responsibility as a Scala developer.

The below red-bounded area corresponds to flatMap-based code and the warning sign are very cost expensive DeserializeToObject and SerializeFromObject operators.

What's interesting is the number of Spark jobs per query and their durations. It appears that explode-based query takes 2 Spark jobs and 200 ms while flatMap-based take only 1 Spark job and 43 ms.

That surprises me a lot and suggests that flatMap-based query could be faster (!)

Body:
I have records like below. I would like to convert a single record into two records with values EXTERNAL and INTERNAL each if the 3rd attribute is All.

Input dataset:

Surender,cts,INTERNAL
Raja,cts,EXTERNAL
Ajay,tcs,All

Expected output:

Surender,cts,INTERNAL
Raja,cts,EXTERNAL
Ajay,tcs,INTERNAL
Ajay,tcs,EXTERNAL

My Spark Code :

case class Customer(name:String,organisation:String,campaign_type:String)

val custRDD = sc.textFile("/user/cloudera/input_files/customer.txt")

val mapRDD = custRDD.map(record => record.split(","))
    .map(arr => (arr(0),arr(1),arr(2))
    .map(tuple => {
      val name            = tuple._1.trim
      val organisation    = tuple._2.trim
      val campaign_type   = tuple._3.trim.toUpperCase
      Customer(name, organisation, campaign_type)
    })

mapRDD.toDF().registerTempTable("customer_processed")

sqlContext.sql("SELECT * FROM customer_processed").show

Could Someone help me to fix this issue?

Body:
Since it's Scala...

If you want to write a more idiomatic Scala code (and perhaps trading some performance due to lack of optimizations to have a more idiomatic code), you can use flatMap operator (removed the implicit parameter):

flatMap[U](func: (T) ⇒ TraversableOnce[U]): Dataset[U] Returns a new Dataset by first applying a function to all elements of this Dataset, and then flattening the results.

NOTE: flatMap is equivalent to explode function, but you don't have to register a UDF (as in the other answer).

A solution could be as follows:

// I don't care about the names of the columns since we use Scala
// as you did when you tried to write the code
scala> input.show
+--------+---+--------+
|     _c0|_c1|     _c2|
+--------+---+--------+
|Surender|cts|INTERNAL|
|    Raja|cts|EXTERNAL|
|    Ajay|tcs|     All|
+--------+---+--------+

val result = input.
  as[(String, String, String)].
  flatMap { case r @ (name, org, campaign) =>
    if ("all".equalsIgnoreCase(campaign)) {
      Seq("INTERNAL", "EXTERNAL").map { cname =>
        (name, org, cname)
      }
    } else Seq(r)
  }
scala> result.show
+--------+---+--------+
|      _1| _2|      _3|
+--------+---+--------+
|Surender|cts|INTERNAL|
|    Raja|cts|EXTERNAL|
|    Ajay|tcs|INTERNAL|
|    Ajay|tcs|EXTERNAL|
+--------+---+--------+

Comparing performance of the two queries, i.e. flatMap-based vs explode-based queries, I think explode-based may be slightly faster and optimized better as some code is under Spark's control (using logical operators before they get mapped to physical couterparts). In flatMap the entire optimization is your responsibility as a Scala developer.

The below red-bounded area corresponds to flatMap-based code and the warning sign are very cost expensive DeserializeToObject and SerializeFromObject operators.

What's interesting is the number of Spark jobs per query and their durations. It appears that explode-based query takes 2 Spark jobs and 200 ms while flatMap-based take only 1 Spark job and 43 ms.

That surprises me a lot and suggests that flatMap-based query could be faster (!)


问:
New gradle is downloaded but not really works
After I got this error while compiling my library of volley

Error:Execution failed for task ':app:compileDebugJavaWithJavac'. Could not open local class set analysis write cache (C:\Users\Vaibhav\AndroidStudioProjects\Volley.gradle\3.3\tasks_app_compileDebugJavaWithJavac\localClassSetAnalysis). Unexpected lock protocol found in lock file. Expected 3, found 0.

I deleted the .gradle folder in my user directory as told by other users But when I restart Android Studio a popup appears saying Downloading .gradle 3.3-all.zip.It downloads the whole and takes approx 15 minutes to do it and takes approx 170 mb to do it.But in the end,I get a warning saying

Error:C:\Users\Vaibhav.gradle\wrapper\dists\gradle-3.3-all\55gk2rcmfc6p2dg9u9ohc3hw9\gradle-3.3-all.zip (The system cannot find the file specified)

答:
The 3.3 version of gradle is causing trouble to many users; update to 3.5

File->Project Structure->Project

set Gradle Version to 3.5, Android Plugin Version to 2.3.2 and click Ok


问:
Obtaining wi-fi connection status from Connection Manager
I have some code which successfully iterates over a list of wi-fi networks, and provides feedback about available networks. The essential calls shown here...

```<code>WlanOpenHandle(WLAN_API_VERSION, NULL, &dwVersion, &hSession);

PWLAN_INTERFACE_INFO_LIST pInterfaceInfoList = NULL;
WlanEnumInterfaces(hSession, NULL, &pInterfaceInfoList);

for(int i ...)
{
    PWLAN_AVAILABLE_NETWORK_LIST pAvailableNetworkList = NULL;
    WlanGetAvailableNetworkList(hSession, &interfaceGUID,
           WLAN_AVAILABLE_NETWORK_INCLUDE_ALL_ADHOC_PROFILES |
           WLAN_AVAILABLE_NETWORK_INCLUDE_ALL_MANUAL_HIDDEN_PROFILES,
           NULL, &pAvailableNetworkList);
    for(int j ...)
    {
        WLAN_AVAILABLE_NETWORK network = pAvailableNetworkList->Network[j];
        :
    }
}
</code>```

This all works fine, and inside the inner loop I'm able to access all of the attributes that I need, such as signal strength, security flags, etc via the network data structure.

One thing that I am not able to obtain is information regarding connection status, such as AUTHENTICATING or AUTHENTICATION_FAILED, etc, so I have tried to introduce another call inside the loop as follows...

```<code>CM_CONNECTION_DETAILS connectionDetails;
memset(&connectionDetails, 0, sizeof(CM_CONNECTION_DETAILS));

connectionDetails.Version = CM_CURRENT_VERSION;
const char* ccp = reinterpret_cast<const char*>(network.dot11Ssid.ucSSID);
mbstowcs(connectionDetails.szName, &ccp[0], network.dot11Ssid.uSSIDLength);

DWORD dwCount = sizeof(CM_CONNECTION_DETAILS);

CM_RESULT cmr = CmGetConnectionDetailsByName(connectionDetails.szName,
           &connectionDetails, &dwCount);

if (cmr == CMRE_SUCCESS)
{
    :
}
</code>```

Upon calling the CmGetConnectionDetailsByName() function, the details inside the CM_CONNECTION_DETAILS structure look correct (name and version), but the function returns with CMRE_INVALID_CONNECTION and the structure is not populated.

I haven't been able to find any examples of this call being successful (only a couple of references to the call returning the same CMRE_INVALID_CONNECTION code).

Does anyone have any experience of using the call successfully, or alternatively suggest a better way to find out the connection status of a network (ie if AUTHENTICATION is in progress or if AUTHENTICATION failed, etc)?

[I'm using Visual Studio 2013 C++ (native Windows app, not MFC), the target is 32-bit and Unicode, running on Windows Compact 2013]

答:
The function below doesn't quite give me the fine control that I was looking for, but it does at least give me the opportunity to find out the state a particular interface. This means that I can find out if the interface is currently in the process or authenticating, and depending whether the final state is connected or disconnected, I can find out if authentication was successful or not.

```<code>WLAN_INTERFACE_STATE getNetworkState(HANDLE hSession, GUID* pGUID, std::wstring& wsState, bool bReportState=true)
{
    WLAN_INTERFACE_STATE result = wlan_interface_state_not_ready;
    DWORD dwDataSize;
    void* pData;
    DWORD dwErrorCode = WlanQueryInterface(hSession, pGUID, wlan_intf_opcode_interface_state, NULL, &dwDataSize, &pData, NULL);
    if (dwErrorCode == ERROR_SUCCESS && pData != NULL)
    {
        WLAN_INTERFACE_STATE* pState = reinterpret_cast<WLAN_INTERFACE_STATE*>(pData);
        if (pState != NULL)
        {
            switch (*pState)
            {
            case wlan_interface_state_not_ready:                wsState = L"NOT_READY"; break;
            case wlan_interface_state_connected:                wsState = L"CONNECTED"; break;
            case wlan_interface_state_ad_hoc_network_formed:    wsState = L"AD_HOC_NETWORK_FORMED"; break;
            case wlan_interface_state_disconnecting:            wsState = L"DISCONNECTING"; break;
            case wlan_interface_state_disconnected:             wsState = L"DISCONNECTED";  break;
            case wlan_interface_state_associating:              wsState = L"ASSOCIATING";   break;
            case wlan_interface_state_discovering:              wsState = L"DISCOVERING";   break;
            case wlan_interface_state_authenticating:           wsState = L"AUTHENTICATING";    break;
            }
            result = *pState;
        }
        WlanFreeMemory(pData);
    }
    return result;
}
</code>```

A limitation of this check, is that it doesn't readily support multiple connections on the same interface, This query doesn't allow us to query to which of the connections the status refers.

If I arrive at a better solution, I will report it here.

Body:
I have some code which successfully iterates over a list of wi-fi networks, and provides feedback about available networks. The essential calls shown here...

WlanOpenHandle(WLAN_API_VERSION, NULL, &dwVersion, &hSession);

PWLAN_INTERFACE_INFO_LIST pInterfaceInfoList = NULL;
WlanEnumInterfaces(hSession, NULL, &pInterfaceInfoList);

for(int i ...)
{
    PWLAN_AVAILABLE_NETWORK_LIST pAvailableNetworkList = NULL;
    WlanGetAvailableNetworkList(hSession, &interfaceGUID,
           WLAN_AVAILABLE_NETWORK_INCLUDE_ALL_ADHOC_PROFILES |
           WLAN_AVAILABLE_NETWORK_INCLUDE_ALL_MANUAL_HIDDEN_PROFILES,
           NULL, &pAvailableNetworkList);
    for(int j ...)
    {
        WLAN_AVAILABLE_NETWORK network = pAvailableNetworkList->Network[j];
        :
    }
}

This all works fine, and inside the inner loop I'm able to access all of the attributes that I need, such as signal strength, security flags, etc via the network data structure.

One thing that I am not able to obtain is information regarding connection status, such as AUTHENTICATING or AUTHENTICATION_FAILED, etc, so I have tried to introduce another call inside the loop as follows...

CM_CONNECTION_DETAILS connectionDetails;
memset(&connectionDetails, 0, sizeof(CM_CONNECTION_DETAILS));

connectionDetails.Version = CM_CURRENT_VERSION;
const char* ccp = reinterpret_cast<const char*>(network.dot11Ssid.ucSSID);
mbstowcs(connectionDetails.szName, &ccp[0], network.dot11Ssid.uSSIDLength);

DWORD dwCount = sizeof(CM_CONNECTION_DETAILS);

CM_RESULT cmr = CmGetConnectionDetailsByName(connectionDetails.szName,
           &connectionDetails, &dwCount);

if (cmr == CMRE_SUCCESS)
{
    :
}

Upon calling the CmGetConnectionDetailsByName() function, the details inside the CM_CONNECTION_DETAILS structure look correct (name and version), but the function returns with CMRE_INVALID_CONNECTION and the structure is not populated.

I haven't been able to find any examples of this call being successful (only a couple of references to the call returning the same CMRE_INVALID_CONNECTION code).

Does anyone have any experience of using the call successfully, or alternatively suggest a better way to find out the connection status of a network (ie if AUTHENTICATION is in progress or if AUTHENTICATION failed, etc)?

[I'm using Visual Studio 2013 C++ (native Windows app, not MFC), the target is 32-bit and Unicode, running on Windows Compact 2013]

Body:
The function below doesn't quite give me the fine control that I was looking for, but it does at least give me the opportunity to find out the state a particular interface. This means that I can find out if the interface is currently in the process or authenticating, and depending whether the final state is connected or disconnected, I can find out if authentication was successful or not.

WLAN_INTERFACE_STATE getNetworkState(HANDLE hSession, GUID* pGUID, std::wstring& wsState, bool bReportState=true)
{
    WLAN_INTERFACE_STATE result = wlan_interface_state_not_ready;
    DWORD dwDataSize;
    void* pData;
    DWORD dwErrorCode = WlanQueryInterface(hSession, pGUID, wlan_intf_opcode_interface_state, NULL, &dwDataSize, &pData, NULL);
    if (dwErrorCode == ERROR_SUCCESS && pData != NULL)
    {
        WLAN_INTERFACE_STATE* pState = reinterpret_cast<WLAN_INTERFACE_STATE*>(pData);
        if (pState != NULL)
        {
            switch (*pState)
            {
            case wlan_interface_state_not_ready:                wsState = L"NOT_READY"; break;
            case wlan_interface_state_connected:                wsState = L"CONNECTED"; break;
            case wlan_interface_state_ad_hoc_network_formed:    wsState = L"AD_HOC_NETWORK_FORMED"; break;
            case wlan_interface_state_disconnecting:            wsState = L"DISCONNECTING"; break;
            case wlan_interface_state_disconnected:             wsState = L"DISCONNECTED";  break;
            case wlan_interface_state_associating:              wsState = L"ASSOCIATING";   break;
            case wlan_interface_state_discovering:              wsState = L"DISCOVERING";   break;
            case wlan_interface_state_authenticating:           wsState = L"AUTHENTICATING";    break;
            }
            result = *pState;
        }
        WlanFreeMemory(pData);
    }
    return result;
}

A limitation of this check, is that it doesn't readily support multiple connections on the same interface, This query doesn't allow us to query to which of the connections the status refers.

If I arrive at a better solution, I will report it here.


问:
Visual Paradigm Data Flow Diagrams
Am trying to design a Data Flow Diagram for a system using Visual Paradigm Community Edition on Ubuntu 14.04 but can't seem to find Data Flow Diagram in the list of diagrams, any clue why since according to visual paradigm website, there should be a data flow diagram in the list of diagrams??</p>

答:
It is worth mentionning that the Data Flow Diagram is only available in Visual Paradigm from version 14 (as well as many other diagrams). You said you had Ubuntu 14.04 but in this case, only Visual Paradigm's version matters.

As shown as Pétur Ingi Egilsson's answer you can access it from the File menu but also in the standard list shown when doing Diagrams > New.

Title: Visual Paradigm Data Flow Diagrams


问:
Javascript accidental closure
I have this piece of code on my website which counts the number of image and then output a list each time the user clicks on desired category.

The problem is, my image counter variable (noIMG) does not clear itself every time the function is called. I tried adding a reset(noIMG) at the end of the function but it seemed like a bad idea.

I did some research and i've stumbled upon articles about closures. After trying numerous methods to fix it, my code is still not acting the way I want it to.

```<code>function thumbCounter(){

    var noIMG = $(".artwork img").size()+1;

        for (var count = 1; count < noIMG; count++){
            if (count == 1){
                 $('#list_here').append('<li class="active">' +count+ '</li>');
            } else{
                 $('#list_here').append('<li>' +count+ '</li>');
            }
        }
};
</code>```

答:
If you mean you want to clear the list every time the function is called, then do it like this:</p>

```<code>function thumbCounter() {
    var noIMG = $(".artwork img").size() + 1;
    var myList = $('#list_here'); // reference to list

    myList.html(""); // clear the contents
    for (var count = 1; count < noIMG; count++) {
        if (count == 1) {
             myList.append('<li class="active">' +count+ '</li>');
        } else {
             myList.append('<li>' +count+ '</li>');
        }
    }
};
</code>```

Title: Javascript accidental closure

Body:
I have this piece of code on my website which counts the number of image and then output a list each time the user clicks on desired category.

The problem is, my image counter variable (noIMG) does not clear itself every time the function is called. I tried adding a reset(noIMG) at the end of the function but it seemed like a bad idea.

I did some research and i've stumbled upon articles about closures. After trying numerous methods to fix it, my code is still not acting the way I want it to.

function thumbCounter(){

    var noIMG = $(".artwork img").size()+1;

        for (var count = 1; count < noIMG; count++){
            if (count == 1){
                 $('#list_here').append('
' +count+ '
');
            } else{
                 $('#list_here').append('
' +count+ '
');
            }
        }
};

Body:
If you mean you want to clear the list every time the function is called, then do it like this:

function thumbCounter() {
    var noIMG = $(".artwork img").size() + 1;
    var myList = $('#list_here'); // reference to list

    myList.html(""); // clear the contents
    for (var count = 1; count < noIMG; count++) {
        if (count == 1) {
             myList.append('<li class="active">' +count+ '</li>');
        } else {
             myList.append('<li>' +count+ '</li>');
        }
    }
};


问:
Test for existence of nested JavaScript object key
If I have a reference to an object:

```<code>var test = {};
</code>```

that will potentially (but not immediately) have nested objects, something like:

```<code>{level1: {level2: {level3: "level3"}}};
</code>```

What is the best way to check for the existence of property in deeply nested objects?

alert(test.level1); yields undefined, but alert(test.level1.level2.level3); fails.

I’m currently doing something like this:

```<code>if(test.level1 && test.level1.level2 && test.level1.level2.level3) {
    alert(test.level1.level2.level3);
}
</code>```

but I was wondering if there’s a better way.

答:
The very best and simplest answer is:

```<code>var isDefinedPath = function (path) {

    var items = path.split ('.');

    if (!items || items.length < 1 || !(items[0] in window)) { return false; }

    var buffer = [items[0]];
    for (var i = 1, e = items.length; i < e; i ++) {
        buffer.push (items[i]);
        if (eval ('typeof(' + buffer.join ('.') + ') == "undefined"')) {
            return false;
        }
    }

    return true;

}
</code>```

test:
isDefinedPath ('level1.level2.level3');

first level cannot be array, others can

ContentLicense: CC BY-SA 4.0

Body:
If I have a reference to an object:

var test = {};

that will potentially (but not immediately) have nested objects, something like:

{level1: {level2: {level3: "level3"}}};

What is the best way to check for the existence of property in deeply nested objects?

alert(test.level1); yields undefined, but alert(test.level1.level2.level3); fails.

I’m currently doing something like this:

if(test.level1 && test.level1.level2 && test.level1.level2.level3) {
    alert(test.level1.level2.level3);
}

but I was wondering if there’s a better way.

Body:
The very best and simplest answer is:

var isDefinedPath = function (path) {

    var items = path.split ('.');

    if (!items || items.length < 1 || !(items[0] in window)) { return false; }

    var buffer = [items[0]];
    for (var i = 1, e = items.length; i < e; i ++) {
        buffer.push (items[i]);
        if (eval ('typeof(' + buffer.join ('.') + ') == "undefined"')) {
            return false;
        }
    }

    return true;

}

test:
isDefinedPath ('level1.level2.level3');

first level cannot be array, others can


答:
Use parse_url with a component of PHP_URL_QUERY to get the query string.

Then parse_str to get the particular argument

http://php.net/manual/en/function.parse-url.php

http://php.net/manual/en/function.parse-str.php

Title: How to get a specific part of a URL using PHP

Body:
I've had a look around and can't find an answer specific to my needs...

This is the URL being sent back to my redirect page from an identity server: http://localhost/?code=92092c2f65560d835a73cda852393316&state=random_state&session_state=CEwifhoy_x1RJWH-DoV_9Q1yJVNUXV4z5YRGGuXsUvs.39c667f469b8f6585a9f699d0b7d76f3

I need to get the code between "code=" and "&state".

Then put it in the <> part of "grant_type=authorization_code&code=<>&redirect_uri=<>" so I can request a token. This part I can do, I just can't figure out how to get the code out of the URL.

Thanks.


问:
Is it okay to have a very long .htaccess file?
I am giving out URLs to people on a website, that actually point to something ugly (on the same website).

http://www.mydomain.com/cool-URL

actually points to

http://www.mydomain.com/boring.php?id=478547&sessid=34734asdf7&otherboringdetails

I'm planning to achieve this by modifying the .htaccess file whenever needed. I'm going to make the PHP script write to the .htaccess file, adding a new rewrite rule whenever there is a new hand-out of a url (from an admin area a non-programmer can control [specify the URL title for this new entry, admin : it will be assigned automagically]).

Is this going to be a problem, especially after 1000 or so such URLs? What is the actual number that is acceptable? Because, I can picture this: the server receives a request for a URL, then it searches the .htaccess file for the right page for this url, and finally sends the user to the right page. If this is anything like Database searching, it might take a long time for the user to actually get to the right page...

Any pointers on this, please?

答:
Having that much rules is really inadvisable. It’s not that they are in a .htaccess file or that they are tested for each request. (Depending on the configuration, that’s might also happen if you put them into your server’s or virtual host configuration.)

It’s the mere fact that it’s that huge amount of rules that is tested and, depending on the rules, every rule has to be tested until a match is found.

Well, you could counteract that by arranging the rules in the order of matching probability so that the probability of finding a match early is high. But it’s complexity is still O(n) in the worst case.

If you really need that much mappings and the mappings are fixed, you can use a RewriteMap hash file that has a complexity of O(1) instead of O(n) for the separated rules. Or you shift the mapping to your PHP application and do it there.


问:
jQuery menu with sub menu trigger
I am trying to create a trigger for an HTML menu which when clicked will toggle sub menus. The problem with the following code is when you click the trigger (class="open") it toggles all the submenu items at once. I'd like the trigger to toggle one sub menu at a time using jQuery. Here is my code:

HTML

```<code><ul>
 <li class="menu-item-has-children">Item 1</li>
   <a class="open">+</a>
   <ul class="sub-menu">
     <li>Sub Item 1</li>
     <li>Sub Item 2</li>
     <li class="menu-item-has-children">Sub Item 3</li>
     <a class="open">+</a>
       <ul class="sub-menu">
         <li>Sub Sub Item 1</li>
         <li>Sub Sub Item 2</li>
         <li>Sub Sub Item 3</li>
         <li>Sub Sub Item 4</li>
         <li>Sub Sub Item 5</li>
      </ul>
   <li>Sub Item 4</li>
   <li>Sub Item 5</li>
</ul>
</code>```

JQUERY

```<code>$(document).ready(function() {
  $('.open').click(function () {
    $('li.menu-item-has-children').parent().closest('.sub-menu').toggle();
  });
});
</code>```

CSS

```<code>ul li {
  list-style-type:none;
}
.open {
  width:20px;
  height:20px;
  background-color:red;
  color:#fff;
  display:block;
  cursor:pointer;
  text-align:center;
 }
 .sub-menu {
  display:none;
 }
</code>```

VIEW THE JS FIDDLE HERE

Thank you :)

答:
There's no contextual this here. It should be:

```<code>$(document).ready(function() {
  $('.open').click(function () {
    $(this).next('.sub-menu').toggle();
  });
});
</code>```

When you are using the $('li.menu-item-has-children'), it selects literally everything and not the one that's clicked upon. The current element that fired the click event can be got through the this keyword and I have used it above to make it work. Since you have a perfect structure like the submenu follows the , the above code works with .next().

Snippet

$(document).ready(function() {
  $('.open').click(function () {
    $(this).next('.sub-menu').toggle();
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>ul li {
 list-style-type:none;
}
.open {
  width:20px;
  height:20px;
  background-color:red;
  color:#fff;
  display:block;
  cursor:pointer;
  text-align:center;
}
.sub-menu {
  display:none;
}</code>```

Item 1

  +

Sub Item 1

Sub Item 2

Sub Item 3

    +

Sub Sub Item 1

Sub Sub Item 2

Sub Sub Item 3

Sub Sub Item 4

Sub Sub Item 5

Sub Item 4

Sub Item 5

```

JSFiddle: https://jsfiddle.net/bdh7seoh/

Title: jQuery menu with sub menu trigger

Body:
I am trying to create a trigger for an HTML menu which when clicked will toggle sub menus. The problem with the following code is when you click the trigger (class="open") it toggles all the submenu items at once. I'd like the trigger to toggle one sub menu at a time using jQuery. Here is my code:

HTML

Item 1

   +

Sub Item 1

Sub Item 2

Sub Item 3

     +

Sub Sub Item 1

Sub Sub Item 2

Sub Sub Item 3

Sub Sub Item 4

Sub Sub Item 5

Sub Item 4

Sub Item 5

JQUERY

$(document).ready(function() {
  $('.open').click(function () {
    $('li.menu-item-has-children').parent().closest('.sub-menu').toggle();
  });
});

CSS

ul li {
  list-style-type:none;
}
.open {
  width:20px;
  height:20px;
  background-color:red;
  color:#fff;
  display:block;
  cursor:pointer;
  text-align:center;
 }
 .sub-menu {
  display:none;
 }

VIEW THE JS FIDDLE HERE

Thank you :)

Body:
There's no contextual this here. It should be:

$(document).ready(function() {
  $('.open').click(function () {
    $(this).next('.sub-menu').toggle();
  });
});

When you are using the $('li.menu-item-has-children'), it selects literally everything and not the one that's clicked upon. The current element that fired the click event can be got through the this keyword and I have used it above to make it work. Since you have a perfect structure like the submenu follows the <a>, the above code works with .next().

Snippet

$(document).ready(function() {
  $('.open').click(function () {
    $(this).next('.sub-menu').toggle();
  });
});

ul li {
 list-style-type:none;
}
.open {
  width:20px;
  height:20px;
  background-color:red;
  color:#fff;
  display:block;
  cursor:pointer;
  text-align:center;
}
.sub-menu {
  display:none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li class="menu-item-has-children">Item 1</li>
  <a class="open">+</a>
  <ul class="sub-menu">
    <li>Sub Item 1</li>
    <li>Sub Item 2</li>
    <li class="menu-item-has-children">Sub Item 3</li>
    <a class="open">+</a>
    <ul class="sub-menu">
      <li>Sub Sub Item 1</li>
      <li>Sub Sub Item 2</li>
      <li>Sub Sub Item 3</li>
      <li>Sub Sub Item 4</li>
      <li>Sub Sub Item 5</li>
    </ul>
    <li>Sub Item 4</li>
    <li>Sub Item 5</li>
  </ul>
</ul>

JSFiddle: https://jsfiddle.net/bdh7seoh/


问:
How do you do hide an empty ACF field using PHP?
I figured that I would simplify my question.
This could be a PHP problem so I apologize in advanced because this may not be an ACF issue but it could be an issue of me not knowing enough PHP, I'm not sure why this isn’t working.

So I am using the ACF repeater field and I would like to hide the repeater Subfield when no data is entered in the field.

```<code>    <?php

    // check if the repeater field has rows of data

    $feature_posts = the_sub_field('feature_image_post');

    if( have_rows('repeat_field') ):

      // loop through the rows of data
        while ( have_rows('repeat_field') ) : the_row();

            // display a sub field value
              echo '<div style="float:left">';
                the_sub_field('restaurant_name');
              echo '</div>';
              echo '<div style="float:left">';
                the_sub_field('restaurant_state');
              echo '</div>';

              echo '<div style="float:left">';
                the_sub_field('restaurant_image_post');
               echo '</div>';

                  if (empty($feature_posts)) {
                    echo '<div style="display:none">';
                    the_sub_field('feature_image_post');
                    echo '</div>';
                  }

                  else {

                      the_sub_field('feature_image_post');
                  }

        endwhile;

    else :

        // no rows found

    endif;

    ?>
</code>```

答:
Add a conditional statement using get_sub_field to check if the field is empty. the_sub_field echos the value and get_sub_field returns the value, so it can be used in a conditional statement or stored in a variable.

```<code>if( get_sub_field('restaurant_name') != "" ) {
  echo '<div style="float:left">';
  the_sub_field('restaurant_name');
  echo '</div>';
}
</code>```

Body:
I figured that I would simplify my question.
This could be a PHP problem so I apologize in advanced because this may not be an ACF issue but it could be an issue of me not knowing enough PHP, I'm not sure why this isn’t working.

So I am using the ACF repeater field and I would like to hide the repeater Subfield when no data is entered in the field.

    <?php

    // check if the repeater field has rows of data

    $feature_posts = the_sub_field('feature_image_post');

    if( have_rows('repeat_field') ):

      // loop through the rows of data
        while ( have_rows('repeat_field') ) : the_row();

            // display a sub field value
              echo '
';
                the_sub_field('restaurant_name');
              echo '
';
              echo '
';
                the_sub_field('restaurant_state');
              echo '
';

              echo '
';
                the_sub_field('restaurant_image_post');
               echo '
';

                  if (empty($feature_posts)) {
                    echo '
';
                    the_sub_field('feature_image_post');
                    echo '
';
                  }

                  else {

                      the_sub_field('feature_image_post');
                  }

        endwhile;

    else :

        // no rows found

    endif;

    ?>

Body:
Add a conditional statement using get_sub_field to check if the field is empty. the_sub_field echos the value and get_sub_field returns the value, so it can be used in a conditional statement or stored in a variable.

if( get_sub_field('restaurant_name') != "" ) {
  echo '<div style="float:left">';
  the_sub_field('restaurant_name');
  echo '</div>';
}


问:
Users seeing inconsistent representation of unicode text across request cycle in Spring 3 MVC
While testing my app, I noticed the following issue where a string containing a unicode character, when passed to the controller and then back to the page, becomes garbled - or at least is not represented consistently - from the user's perspective.

```<code>1. Xáeso
2. Xßeso
3. X%E1eso
</code>```

Text that I pass as a RequestParam from the page to the controller.

How that is output in the log file immediately after reading it from the RequestParam in the controller

The text passed from the controller back to the client after the request handler exits.

This is the only valid representation of the text as far as what the user would expect to see:

```<code>1. Xáeso
</code>```

How can I ensure that the unicode character in position 2 of this string is represented consistently to the client-side user of the app?

答:
There are multiple places where encoding can go wrong.

A quick fix might be to use spring's CharacterEncodingFilter (or the equivalent interceptor), and set the encoding to utf-8. Also, your JSP pages better have <%@ page pageEncoding="utf8" %>

Body:
While testing my app, I noticed the following issue where a string containing a unicode character, when passed to the controller and then back to the page, becomes garbled - or at least is not represented consistently - from the user's perspective.

1. Xáeso
2. Xßeso
3. X%E1eso

Text that I pass as a RequestParam from the page to the controller.

How that is output in the log file immediately after reading it from the RequestParam in the controller

The text passed from the controller back to the client after the request handler exits.

This is the only valid representation of the text as far as what the user would expect to see:

1. Xáeso

How can I ensure that the unicode character in position 2 of this string is represented consistently to the client-side user of the app?


问:
No projects displaying in Eclipse Project Explorer
I'm using Eclipse Neon.3 Release (4.6.3). For about a week, everything keeps disappearing from Project explorer, Navigator, and Package Explorer. In Project Explorer, if I click on the menu and then Deselect Working Set, the list comes back, but a couple hours later it will disappear again.

I saw a few solutions that say to go to File->Import->General->From Existing Project and import the project again, but I can't do that because it says the projects are already imported, I just can't see them. I was also trying to avoid creating a new workspace because then I lose all my settings and perspective layouts.

答:
Sounds like you accidentally set the "Top Level Elements" to be Working Sets instead of projects. If you do not have any Working Sets, the view will be empty.

If you click the down arrow on the right of the four buttons, you'll have the option to select "Top Level Elements" > "Projects".


问:
How to get TeamCity builds statistics for last quarter(3 month) from API or DB(SQL)?
TeamCity issue tracker link https://youtrack.jetbrains.com/issue/TW-50234

I want to calc "builds" latency for last week and compare to avg. last month and avg. last quarter.
last month can be easelly fetch via REST API like so:

```<code>https://teamcity/app/rest/builds?locator=buildType:(id:<BUILD_ID>)&fields=count,build(number,status,queuedDate,finishDate)
</code>```

Latest entrie from payload is 20170502T131511+0300

But how to fetch more data - for last 3 month?
I have access to SQL DB(We use PostgreSQL) and SQL is good solution.

答:
You could come across paginaton of the response: try to include nextHref attribute of the response entity (builds) for items collections (i.e. use &fields=count,nextHref instead of just &fields=count and you'll probably get the link to the second page of the output).

It it is your case, following locator dimensions are available to control the number of the builds in response:

count:<number> - serve only the specified number of builds

start:<number> - list the builds from the list starting from the position specified (zero-based)

lookupLimit:<number> - limit processing to the latest N builds only (the default is 5000). If none of the latest N builds match the other specified criteria of the build locator, 404 response is returned

There should be no limitation of the output based on the date, but in case there're some clean up rules configured, there could be no data, obviously.

Body:
TeamCity issue tracker link https://youtrack.jetbrains.com/issue/TW-50234

I want to calc "builds" latency for last week and compare to avg. last month and avg. last quarter.
last month can be easelly fetch via REST API like so:

https://teamcity/app/rest/builds?locator=buildType:(id:<BUILD_ID>)&fields=count,build(number,status,queuedDate,finishDate)

Latest entrie from payload is 20170502T131511+0300

But how to fetch more data - for last 3 month?
I have access to SQL DB(We use PostgreSQL) and SQL is good solution.


问:
Get stacktrace for crash, without running the app in a debugger
I normally use GDB (in Linux, with the Qt Creator debugger GUI) to debug. But right now I have a crash that refuses to ever happen when running under the debugger, yet happens easily when running outside of it.

How do I get a stack trace of my crash, in these circumstances?

A linux-specific solution is OK.

Note: I'm talking about running a debug build only, even when it's run outside the debugger.

答:
The easiest way to be sure you can obtain a stacktrace after a crash is to run

```<code>ulimit -c unlimited
</code>```

In your shell before starting the program.
This will ensure that the kernel is allowed to produce a "core dump" of unlimited size (for many distros the default size is 0) when a program crashes.

That core file can then be loaded into gdb as gdb programfile corefile and then the command thread apply all bt will give you stack traces for all threads for that specific crash (use just bt if you only care about the crashing thread).

You can also use the pstack program to get a stacktrace from a running program.

Body:
The easiest way to be sure you can obtain a stacktrace after a crash is to run

ulimit -c unlimited

In your shell before starting the program.
This will ensure that the kernel is allowed to produce a "core dump" of unlimited size (for many distros the default size is 0) when a program crashes.

That core file can then be loaded into gdb as gdb programfile corefile and then the command thread apply all bt will give you stack traces for all threads for that specific crash (use just bt if you only care about the crashing thread).

You can also use the pstack program to get a stacktrace from a running program.


问:
Remove redundant spaces when render inside a
 tag
I'd like to render a paragraph without redundant spaces. For example:

```<code><p>There are cars, dogs, computers and houses!</p>
</code>```

I have written the following code:

```<code>var objects = new List<string> { "cars", "dogs", "computers", "houses" };

<p>
    There are
    for (var i = 0; i < objects.Count; ++i)
    {
        if (objects.Count > 1 && i == objects.Count - 1)
        {
            @:and
        }
        else if (i > 0)
        {
            @:,
        }
        @objects[i]
    }
    !
<p>

@* This code will be rendered incorrectly by the browser like *@
<p>There are cars , dogs , computers and houses!</p>
</code>```

How can I remove the spaces inside the
 tag?

答:
You could use string.Join(string, IEnumerable<string>) to join n-1 elements with ", " and then add last element with " and ".

```<code><p>There are @string.Join(", ", objects.Take(objects.Count() - 1)) and @{objects.Last()}!</p>
</code>```

Title: Remove redundant spaces when render inside a <p> tag

Body:
I'd like to render a paragraph without redundant spaces. For example:

There are cars, dogs, computers and houses!

I have written the following code:

var objects = new List<string> { "cars", "dogs", "computers", "houses" };

    There are
    for (var i = 0; i < objects.Count; ++i)
    {
        if (objects.Count > 1 && i == objects.Count - 1)
        {
            @:and
        }
        else if (i > 0)
        {
            @:,
        }
        @objects[i]
    }
    !

@* This code will be rendered incorrectly by the browser like *@

There are cars , dogs , computers and houses!

How can I remove the spaces inside the
 tag?

Body:
You could use string.Join(string, IEnumerable<string>) to join n-1 elements with ", " and then add last element with " and ".

<p>There are @string.Join(", ", objects.Take(objects.Count() - 1)) and @{objects.Last()}!</p>