问:
Disabling UAC with Powershell
I'm trying to disable UAC (i.e. set to the minimum level) using Powershell. So I'm running:

```<code>Set-ItemProperty -Path REGISTRY::HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System -Name EnableLUA -Value 0
</code>```

I've also tried this with -Force added on the end.

This code has the intended effect of setting UAC to minimum but also the undesired effect of preventing built-in Windows applications (including Edge) from running, returning an error that the application can't be run using the built-in administrator account (despite the fact that it's being run with a user account that simply has UAC disabled).

So if anyone has some insight as to why this is happening and how to resolve it, that would be ideal. Failing that, if there's an alternative Powershell command I can run to disable UAC then that could also be worth a shot.

答:
This is an issue specifically with Windows 10 and Windows 8. You cannot have Minimal/No UAC and be a local administrator on the machine. This actually affects more than just Edge including all modern apps like the Calculator as well. This was changed due to a security risk, as running the browser as an administrator is actually a really bad and insecure thing to do. Take a look at this article for more information

Via GPO, if you enable "Admin Approval Mode", you will then be able to launch apps without UAC but this comes with some drawbacks as well.

At my company, we put this in a GPO for a specific OU and dropped all Win10/Win8 devices into it so that the admin approval affects as few devices as possible.

You notice that it works when disabled by the GUI because you cannot disable UAC completely with the GUI, the only way to do it is with the registry key. So even though you think you're disabling it via the GUI, you're not disabling it completely.

Title: Disabling UAC with Powershell

Body:
I'm trying to disable UAC (i.e. set to the minimum level) using Powershell. So I'm running:

Set-ItemProperty -Path REGISTRY::HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System -Name EnableLUA -Value 0

I've also tried this with -Force added on the end.

This code has the intended effect of setting UAC to minimum but also the undesired effect of preventing built-in Windows applications (including Edge) from running, returning an error that the application can't be run using the built-in administrator account (despite the fact that it's being run with a user account that simply has UAC disabled).

So if anyone has some insight as to why this is happening and how to resolve it, that would be ideal. Failing that, if there's an alternative Powershell command I can run to disable UAC then that could also be worth a shot.


来源: stackexchange

问:
Python and C++ modulus
I am learning c++ and in trying to code a little program i found something strange. It is about modulus :
c++ code

```<code>cout << -325 - (-325 % 100) << endl;
// -300
cout << 325 - (325 % 100);
// 300
</code>```

and python code

```<code>print(-325 - (-325 % 100))
# -400
print(325 - (325 % 100))
# 300
</code>```

Can someone explain me that pls ? Thq

答:
It looks phyton doesn't accept negative modulus results, so adds 100 to -25.

print(-325 - (-325 % 100))

ContentLicense: CC BY-SA 3.0

Title: Python and C++ modulus

Body:
I am learning c++ and in trying to code a little program i found something strange. It is about modulus :
c++ code

cout << -325 - (-325 % 100) << endl;
// -300
cout << 325 - (325 % 100);
// 300

and python code

print(-325 - (-325 % 100))
# -400
print(325 - (325 % 100))
# 300

Can someone explain me that pls ? Thq


问:
website load time is too long because of too many image links on the main page
I have a website that is built using Hugo Static site generator. The theme I have used is called Dimension and is a single page theme. I have a number of pages each written in a markdown file (.md file) but when I use hugo it combines all the files in the index.html. The theme uses overyal (modals) to create different pages. Here is an example of how it works and looks. Here for example if you click on INTRO link you go to this URL: http://themes.gohugo.io/theme/dimension/#intro and the content of intro is inside intro.md file. So the INTRO page is called modal or overlay.

As I have a lot of links to web images (about 1000) and as all of them are placed in `index.html' it takes a long time to load, although I don't need all of them at once. Is there a way to load only images that are needed for a specific overlay?

答: Try out the Lazysizes script. It's lightweight and powerful: https://github.com/aFarkas/lazysizes</p>


问:
Randomize images on imageview with "if" function working strange
I'm trying to randomize images when a button is clicked and if the image is what I want it to be, randomize again, but if it's not, close the activity.

I cant randomize in my code, it closes always, but if I delete the call to the finish() function, it will randomize normally.

I just want that imageview to recognize the image without a sqlite DB

```<code>@Override
            public void onClick(View v) {
                int[] cards={R.drawable.bg,R.drawable.bg1};
                Random r = new Random();
                int n = r.nextInt(2);
                ImageView imgview1 = (ImageView) findViewById(R.id.imgv1);
                imgview1.setImageResource(cards[n]);

                if (imgview1.equals(R.drawable.bg){
                    imgview1.setImageResource(cards[n]);
                }
                else  {
                    finish();
                }
            }
</code>```

答:
Change this condition if (imgview1.equals(R.drawable.bg) to

if (cards[n ] == R.drawable.bg)

Your problem is that you are comparing the ImageView reference to the ImageResource

Body:
I'm trying to randomize images when a button is clicked and if the image is what I want it to be, randomize again, but if it's not, close the activity.

I cant randomize in my code, it closes always, but if I delete the call to the finish() function, it will randomize normally.

I just want that imageview to recognize the image without a sqlite DB

@Override
            public void onClick(View v) {
                int[] cards={R.drawable.bg,R.drawable.bg1};
                Random r = new Random();
                int n = r.nextInt(2);
                ImageView imgview1 = (ImageView) findViewById(R.id.imgv1);
                imgview1.setImageResource(cards[n]);

                if (imgview1.equals(R.drawable.bg){
                    imgview1.setImageResource(cards[n]);
                }
                else  {
                    finish();
                }
            }


问:
React router - outer html containers
I'm learning how to use React Router and have managed to successfully setup my routes. I have a question though with regards to having outer html containers that you want to display across all pages (these containers then have different components that render within them depending what route you are on). Here is my code:

index.js:

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import siteFeedback from './sections/comments/site-feedback';
import { BrowserRouter,Switch, Route  } from 'react-router-dom';

ReactDOM.render(
<BrowserRouter>
    <Switch>
        <Route path='/site-feedback' component={siteFeedback}/>
    </Switch>
</BrowserRouter>,
  document.getElementById('root')
);
</code>```

siteFeedback.js

```<code>import React, {Component} from 'react';

class siteFeedback extends Component {
    render() {
        return (
            <div className="outer-container">

                {/* some other code and containers here */}

            </div>
        )
    }
}

export default siteFeedback;
</code>```

I've simplified my code above as much as possible for sake of clarity. I want the div "outer-container" to wrap every route I have and in my example above its hard coded in the render function of siteFeedback.

My first thought was that "outer-container" div needs to be made into a component itself which could look something like this:

outer-container.js

```<code>import React, {Component} from 'react';

class outerContainer extends Component {
    render() {
        return (
            <div className="outer-container">
                {/* the componenets displayed in here would depend on what route you are on*/}
            </div>
        )
    }
}

export default outerContainer;
</code>```

But the part I am struggling with is the components that would then have to go within the

. As this would need to be dynamic depending what page you are on, would I need to pass this down as props somehow?

I see that location is passed down as a prop from the router. Would I need an if statement in my render function of outer-container.js that says something like if route is /siteFeedback then render siteFeedback componenets inside of outer-container?

Looking for advice on the best approach here, cheers

答:
Adding Route to the outer most url

```<code><Switch>
    <Route path='/' component={outerContainer}/>
    <Route path='/site-feedback' component={siteFeedback}/>
</Switch>
</code>```

and modifying outerContainer as below

```<code>return (
      <div className="outer-container">
           { this.props.children }
      </div>
)
</code>```

should work.

Title: React router - outer html containers

Body:
I'm learning how to use React Router and have managed to successfully setup my routes. I have a question though with regards to having outer html containers that you want to display across all pages (these containers then have different components that render within them depending what route you are on). Here is my code:

index.js:

import React from 'react';
import ReactDOM from 'react-dom';
import siteFeedback from './sections/comments/site-feedback';
import { BrowserRouter,Switch, Route  } from 'react-router-dom';

ReactDOM.render(
<BrowserRouter>
    <Switch>
        <Route path='/site-feedback' component={siteFeedback}/>
    </Switch>
</BrowserRouter>,
  document.getElementById('root')
);

siteFeedback.js

import React, {Component} from 'react';

class siteFeedback extends Component {
    render() {
        return (

                {/* some other code and containers here */}

        )
    }
}

export default siteFeedback;

I've simplified my code above as much as possible for sake of clarity. I want the div "outer-container" to wrap every route I have and in my example above its hard coded in the render function of siteFeedback.

My first thought was that "outer-container" div needs to be made into a component itself which could look something like this:

outer-container.js

import React, {Component} from 'react';

class outerContainer extends Component {
    render() {
        return (

                {/* the componenets displayed in here would depend on what route you are on*/}

        )
    }
}

export default outerContainer;

But the part I am struggling with is the components that would then have to go within the

. As this would need to be dynamic depending what page you are on, would I need to pass this down as props somehow?

I see that location is passed down as a prop from the router. Would I need an if statement in my render function of outer-container.js that says something like if route is /siteFeedback then render siteFeedback componenets inside of outer-container?

Looking for advice on the best approach here, cheers

Body:
Adding Route to the outer most url

<Switch>
    <Route path='/' component={outerContainer}/>
    <Route path='/site-feedback' component={siteFeedback}/>
</Switch>

and modifying outerContainer as below

return (
      <div className="outer-container">
           { this.props.children }
      </div>
)

should work.


问:
How to Map a Complex native Query Result Set to a Pojo Class in Spring Data JPA
My Repository

```<code> public interface ProductRepository extends JpaRepository<Product,Integer> {

           @Query(value = "select mp.*,u.name,p.name, p.ext_id from merchant_product mp join campaign c on c.product_id = mp.id and c.status in (4, 8)join product p on p.id = mp.product_id join user u on u.id = mp.user_id where mp.status = 4 and mp.availability = 'Y';", nativeQuery = true)

            List<Object> getAllProduct();

    }
</code>```

This is my Query in Spring Boot  i am using Spring data JPA . I need to map this to a Pojo class . So that i can use it for further processing .

can anyone help me with this.

My pojo

```<code>@Data
@AllArgsConstructor
public class Product {
    @Id
    //data of merchant product table
    //data of user table
    private int id;
    private String name;
    private String ext_id;

}
</code>```

答:
Id create a constructor for the params you want on Product and call -

```<code> public interface ProductRepository extends JpaRepository<Product,Integer> {
           @Query(value = "select new Product(u.name,p.name, p.ext_id) from merchant_product mp join campaign c on c.product_id = mp.id and c.status in (4, 8)join product p on p.id = mp.product_id join user u on u.id = mp.user_id where mp.status = 4 and mp.availability = 'Y';", nativeQuery = true)
            List<Product> getAllProduct();
    }
</code>```

You will need to define the params from the wildcard mp.* in your object for mapping

Body:
My Repository

 public interface ProductRepository extends JpaRepository<Product,Integer> {

           @Query(value = "select mp.*,u.name,p.name, p.ext_id from merchant_product mp join campaign c on c.product_id = mp.id and c.status in (4, 8)join product p on p.id = mp.product_id join user u on u.id = mp.user_id where mp.status = 4 and mp.availability = 'Y';", nativeQuery = true)

            List<Object> getAllProduct();

    }

This is my Query in Spring Boot  i am using Spring data JPA . I need to map this to a Pojo class . So that i can use it for further processing .

can anyone help me with this.

My pojo

@Data
@AllArgsConstructor
public class Product {
    @Id
    //data of merchant product table
    //data of user table
    private int id;
    private String name;
    private String ext_id;

}

Body:
Id create a constructor for the params you want on Product and call -

 public interface ProductRepository extends JpaRepository<Product,Integer> {
           @Query(value = "select new Product(u.name,p.name, p.ext_id) from merchant_product mp join campaign c on c.product_id = mp.id and c.status in (4, 8)join product p on p.id = mp.product_id join user u on u.id = mp.user_id where mp.status = 4 and mp.availability = 'Y';", nativeQuery = true)
            List<Product> getAllProduct();
    }

You will need to define the params from the wildcard mp.* in your object for mapping


问:
show 100% width child within non 100% width parent
I have a div that has max-width of let's say 1024px and I have it's child that needs to take 100% width starting at the left of the screen.

Is it possible without introducing additional markup? I understand that can make child 100% with width: 100vw; but can't seem to push it to the left.

CODE

.parent {
  max-width: 800px;
  margin: 0 auto;
}

.child {
  margin-top: 20px;
  padding: 20px;
  width: 100vw;
  background: grey;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent">
  Toggle content
  <div class="child">Content</div>
</div></code>```

https://codepen.io/anon/pen/QgbPJj

答:
Is it possible without introducing additional markup? I understand that can make child 100% with width: 100vw; but can't seem to push it to the left.

What do you want to push to the left? The child element? If so, the parent has margin-left: auto and margin-right: auto (shorthand margin: 0 auto). With that you are centering the parent element, hence the child element goes with it.

You might wanna use margin: 0; instead.

ContentLicense: CC BY-SA 4.0

Body:
I have a div that has max-width of let's say 1024px and I have it's child that needs to take 100% width starting at the left of the screen.

Is it possible without introducing additional markup? I understand that can make child 100% with width: 100vw; but can't seem to push it to the left.

CODE

.parent {
  max-width: 800px;
  margin: 0 auto;
}

.child {
  margin-top: 20px;
  padding: 20px;
  width: 100vw;
  background: grey;
}

  Toggle content

Content

https://codepen.io/anon/pen/QgbPJj


问:
Save file as PDF/A using Office.Interop.Excel
How can I export an Excel spreadsheet to PDF/A (ISO 19005-1)?

EDIT: I'm asking for PDF/A, and not plain old PDF 1.5 as it exports by default. I've even emphasized the A in my original question.

I can already export Word and PowerPoint documents to PDF/A, using the ExportAsFixedFormat() function, since the Word and PowerPoint functions both have an optional UseISO19005_1 parameter, but the Excel version is very different, and is missing lots of parameters.

I can't seem to find any way to export a PDF/A using the COM Interop.

Here's the code I use to export from a docx:

```<code>Dim ExportFormat As WdExportFormat = WdExportFormat.wdExportFormatPDF
Dim OpenAfterExport As Boolean = False
Dim OptimizeFor As WdExportOptimizeFor = WdExportOptimizeFor.wdExportOptimizeForPrint
Dim Range As WdExportRange = WdExportRange.wdExportAllDocument
Dim Item As WdExportItem = WdExportItem.wdExportDocumentWithMarkup
Dim IncludeDocProps As Boolean = True
Dim KeepIRM As Boolean = False
Dim CreateBookmarks As WdExportCreateBookmarks = WdExportCreateBookmarks.wdExportCreateWordBookmarks
Dim DocStructureTags As Boolean = True
Dim BitmapMissingFonts As Boolean = True
Dim UseISO19005_1 As Boolean = False

If exportPDFA Then
    UseISO19005_1 = True
    Dim wordApp As New Word.Application()
    Dim doc As Word.Document = wordApp.Documents.Open(FileName)
    doc.ExportAsFixedFormat(pathToDestFile, ExportFormat, OpenAfterExport, OptimizeFor, Range, 0, 0, Item, IncludeDocProps, KeepIRM, CreateBookmarks, DocStructureTags, BitmapMissingFonts, UseISO19005_1)
End If
</code>```

But for xlsx, the ExportAsFixedFormat() function accepts very different parameters (this was taken directly from the Microsoft.Office.Interop.Excel class):

```<code>Sub ExportAsFixedFormat(Type As XlFixedFormatType, Optional Filename As Object = Nothing, Optional Quality As Object = Nothing, Optional IncludeDocProperties As Object = Nothing, Optional IgnorePrintAreas As Object = Nothing, Optional From As Object = Nothing, Optional [To] As Object = Nothing, Optional OpenAfterPublish As Object = Nothing, Optional FixedFormatExtClassPtr As Object = Nothing)
</code>```

答:
Use below method for converting the excel to pdf and mark as answer if it works</p>

```<code>Public Function ExportWorkbookToPdf(ByVal workbookPath As String, ByVal outputPath As String) As Boolean

    ' If either required string is null or empty, stop and bail out
    If String.IsNullOrEmpty(workbookPath) OrElse String.IsNullOrEmpty(outputPath) Then
        Return False
    End If

    ' Create COM Objects
    Dim excelApplication As Microsoft.Office.Interop.Excel.Application
    Dim excelWorkbook As Microsoft.Office.Interop.Excel.Workbook

    ' Create new instance of Excel
    excelApplication = New Microsoft.Office.Interop.Excel.Application()

    ' Make the process invisible to the user
    excelApplication.ScreenUpdating = False

    ' Make the process silent
    excelApplication.DisplayAlerts = False

    ' Open the workbook that you wish to export to PDF
    excelWorkbook = excelApplication.Workbooks.Open(workbookPath)

    ' If the workbook failed to open, stop, clean up, and bail out
    If excelWorkbook Is Nothing Then
        excelApplication.Quit()

        excelApplication = Nothing
        excelWorkbook = Nothing

        Return False
    End If

    Dim exportSuccessful = True
    Try
        ' Call Excel's native export function (valid in Office 2007 and Office 2010, AFAIK)
        excelWorkbook.ExportAsFixedFormat(Microsoft.Office.Interop.Excel.XlFixedFormatType.xlTypePDF, outputPath)
    Catch ex As System.Exception
        ' Mark the export as failed for the return value...

        ' Do something with any exceptions here, if you wish...
        ' MessageBox.Show...
        exportSuccessful = False
    Finally
        ' Close the workbook, quit the Excel, and clean up regardless of the results...
        excelWorkbook.Close()
        excelApplication.Quit()

        excelApplication = Nothing
        excelWorkbook = Nothing
    End Try

    ' You can use the following method to automatically open the PDF after export if you wish
    ' Make sure that the file actually exists first...
    If System.IO.File.Exists(outputPath) Then
        System.Diagnostics.Process.Start(outputPath)
    End If

    Return exportSuccessful
End Function
</code>```

Body:
How can I export an Excel spreadsheet to PDF/A (ISO 19005-1)?

EDIT: I'm asking for PDF/A, and not plain old PDF 1.5 as it exports by default. I've even emphasized the A in my original question.

I can already export Word and PowerPoint documents to PDF/A, using the ExportAsFixedFormat() function, since the Word and PowerPoint functions both have an optional UseISO19005_1 parameter, but the Excel version is very different, and is missing lots of parameters.

I can't seem to find any way to export a PDF/A using the COM Interop.

Here's the code I use to export from a docx:

Dim ExportFormat As WdExportFormat = WdExportFormat.wdExportFormatPDF
Dim OpenAfterExport As Boolean = False
Dim OptimizeFor As WdExportOptimizeFor = WdExportOptimizeFor.wdExportOptimizeForPrint
Dim Range As WdExportRange = WdExportRange.wdExportAllDocument
Dim Item As WdExportItem = WdExportItem.wdExportDocumentWithMarkup
Dim IncludeDocProps As Boolean = True
Dim KeepIRM As Boolean = False
Dim CreateBookmarks As WdExportCreateBookmarks = WdExportCreateBookmarks.wdExportCreateWordBookmarks
Dim DocStructureTags As Boolean = True
Dim BitmapMissingFonts As Boolean = True
Dim UseISO19005_1 As Boolean = False

If exportPDFA Then
    UseISO19005_1 = True
    Dim wordApp As New Word.Application()
    Dim doc As Word.Document = wordApp.Documents.Open(FileName)
    doc.ExportAsFixedFormat(pathToDestFile, ExportFormat, OpenAfterExport, OptimizeFor, Range, 0, 0, Item, IncludeDocProps, KeepIRM, CreateBookmarks, DocStructureTags, BitmapMissingFonts, UseISO19005_1)
End If

But for xlsx, the ExportAsFixedFormat() function accepts very different parameters (this was taken directly from the Microsoft.Office.Interop.Excel class):

Sub ExportAsFixedFormat(Type As XlFixedFormatType, Optional Filename As Object = Nothing, Optional Quality As Object = Nothing, Optional IncludeDocProperties As Object = Nothing, Optional IgnorePrintAreas As Object = Nothing, Optional From As Object = Nothing, Optional [To] As Object = Nothing, Optional OpenAfterPublish As Object = Nothing, Optional FixedFormatExtClassPtr As Object = Nothing)

Body:
Use below method for converting the excel to pdf and mark as answer if it works

Public Function ExportWorkbookToPdf(ByVal workbookPath As String, ByVal outputPath As String) As Boolean

    ' If either required string is null or empty, stop and bail out
    If String.IsNullOrEmpty(workbookPath) OrElse String.IsNullOrEmpty(outputPath) Then
        Return False
    End If

    ' Create COM Objects
    Dim excelApplication As Microsoft.Office.Interop.Excel.Application
    Dim excelWorkbook As Microsoft.Office.Interop.Excel.Workbook

    ' Create new instance of Excel
    excelApplication = New Microsoft.Office.Interop.Excel.Application()

    ' Make the process invisible to the user
    excelApplication.ScreenUpdating = False

    ' Make the process silent
    excelApplication.DisplayAlerts = False

    ' Open the workbook that you wish to export to PDF
    excelWorkbook = excelApplication.Workbooks.Open(workbookPath)

    ' If the workbook failed to open, stop, clean up, and bail out
    If excelWorkbook Is Nothing Then
        excelApplication.Quit()

        excelApplication = Nothing
        excelWorkbook = Nothing

        Return False
    End If

    Dim exportSuccessful = True
    Try
        ' Call Excel's native export function (valid in Office 2007 and Office 2010, AFAIK)
        excelWorkbook.ExportAsFixedFormat(Microsoft.Office.Interop.Excel.XlFixedFormatType.xlTypePDF, outputPath)
    Catch ex As System.Exception
        ' Mark the export as failed for the return value...

        ' Do something with any exceptions here, if you wish...
        ' MessageBox.Show...
        exportSuccessful = False
    Finally
        ' Close the workbook, quit the Excel, and clean up regardless of the results...
        excelWorkbook.Close()
        excelApplication.Quit()

        excelApplication = Nothing
        excelWorkbook = Nothing
    End Try

    ' You can use the following method to automatically open the PDF after export if you wish
    ' Make sure that the file actually exists first...
    If System.IO.File.Exists(outputPath) Then
        System.Diagnostics.Process.Start(outputPath)
    End If

    Return exportSuccessful
End Function


问:
cakephp performances in a big project
I have to develop a big application (an advertising platform, will get more than 10K users and 100K's of listings ) Is it a good idea to choose cakephp for building such a site ?

Thank a  lot

答:
Considering the fact that you expect to serve quite some users, I would advise you to either make your own script (I don't know how experienced you are though), or hiring someone to do it for you.

However, since you give hardly any details on your specific case, I'd suggest you either rephrase your question with more details, or visit an expert to have a chat. That would really help you, especially if you aren't experienced.

ContentLicense: CC BY-SA 2.5

Title: cakephp performances in a big project


问:
Oracle db table data loading is too slow in DBeaver
I'm using DBeaver to connect to an Oracle database. Database connection and table properties view functions are working fine without any delay. But fetching table data is too slow(sometimes around 50 seconds).

Any settings to speed up fetching table data in DBeaver?

答:
I've never used DBeaver, but I often see applications which use too small an "array fetch size"**, which often poses fetch issues.

** Array fetch size note:
As per the Oracle documentation the Fetch Buffer Size is an application side memory setting that affects the number of rows returned by a single fetch.  Generally you balance the number of rows returned with a single fetch (a.k.a. array fetch size) with the number of rows needed to be fetched.

A low array fetch size compared to the number of rows needed to be returned will manifest as delays from increased network and client side processing needed to process each fetch (i.e. the high cost of each network round trip [SQL*Net protocol]).

If this is the case, you will likely see very high waits on “SQLNet message from client” [in gv$session or elsewhere].

SQLNet message from client
This wait event is posted by the session when it is waiting for a message from the client to arrive. Generally, this means that the session is just sitting idle, however, in a Client/Server environment it could also means that either the client process is running slow or there are network latency delays. The database performance is not degraded by high wait times for this wait event.


问:
How can I use the built in WooCommerce geolocation?
I know that WooCommerce has a built in GeoLocation function, I was wondering how can I use it on other sections of the site, for example, display certain elements based on the location. Thanks.</p>

答:
You can use the WC_Geolocation class for this: https://docs.woocommerce.com/wc-apidocs/class-WC_Geolocation.html

Either you build a custom theme or child-theme using that functionality or you build your own shortcodes for the current theme: https://codex.wordpress.org/Shortcode_API


答:
Your Activity always closes because you compare ImageView and Resource, it always false. To provide logic which you want, you can use setTag() method, to set tag as image resource and then compare them:

```<code>ImageView imgview1 = (ImageView) findViewById(R.id.imgv1);
imgview1.setImageResource(cards[n]);
imgview1.setTag(cards[n]);

if (imgview1.getTag().equals(R.drawable.bg) {
    imgview1.setImageResource(cards[n]);
} else {
    finish();
}
</code>```

Title: Randomize images on imageview with "if" function working strange

Body:
Your Activity always closes because you compare ImageView and Resource, it always false. To provide logic which you want, you can use setTag() method, to set tag as image resource and then compare them:

ImageView imgview1 = (ImageView) findViewById(R.id.imgv1);
imgview1.setImageResource(cards[n]);
imgview1.setTag(cards[n]);

if (imgview1.getTag().equals(R.drawable.bg) {
    imgview1.setImageResource(cards[n]);
} else {
    finish();
}


问:
How do you count the elements of an array in java
Say i have the array

```<code>int theArray = new int[20];
</code>```

The length of the array is 20 but the count is 0. How can i get the count?

答:
If you assume that 0 is not a valid item in the array then the following code should work:</p>

```<code>   public static void main( String[] args )
   {
      int[] theArray = new int[20];
      theArray[0] = 1;
      theArray[1] = 2;

      System.out.println(count(theArray));
   }

   private static int count(int[] array)
   {
      int count = 0;
      for(int i : array)
      {
         if(i > 0)
         {
            count++;
         }
      }
      return count;
   }
</code>```

Body:
Say i have the array

int theArray = new int[20];

The length of the array is 20 but the count is 0. How can i get the count?

Body:
If you assume that 0 is not a valid item in the array then the following code should work:

   public static void main( String[] args )
   {
      int[] theArray = new int[20];
      theArray[0] = 1;
      theArray[1] = 2;

      System.out.println(count(theArray));
   }

   private static int count(int[] array)
   {
      int count = 0;
      for(int i : array)
      {
         if(i > 0)
         {
            count++;
         }
      }
      return count;
   }


问:
multiline text to hash to YAML conversion produces last line
1) I am trying to read strings from data.txt

```<code>Christopher Plummer;Dec 13, 1927
Christopher Walken;Mar 31, 1943
The King of Spain;Jan  5, 1938
</code>```

2) split all strings at ';' and convert them to hash

3) hash to YAML

4) write YAML to file

problem: writing YAML to file produces only the last line

```<code>data = Hash.new
require 'yaml'
filename = 'Ydata.txt'

File.read('Data.txt').each_line do |line|
  line = line.chomp
  line = line.split ';'
  data = { "#{line[0]}" => "#{line[1]}" }.to_yaml
end

File.open filename, 'w' do |f|
   f.write data
end
</code>```

答:
It looks like you are overriding data in every iteration with a new YAML string with only one entry. This is why you see only the last line. Try building the complete ruby hash and converting the whole hash to YAML at the end. Like this:

```<code>require 'yaml'

data = Hash.new
File.read('Data.txt').each_line do |line|
  k, v = line.chomp.split(';', 2)
  data[k] = v
end
File.open('Ydata.txt', 'w') do |f|
   f.write(data.to_yaml)
end
</code>```

Body:
1) I am trying to read strings from data.txt

Christopher Plummer;Dec 13, 1927
Christopher Walken;Mar 31, 1943
The King of Spain;Jan  5, 1938

2) split all strings at ';' and convert them to hash

3) hash to YAML

4) write YAML to file

problem: writing YAML to file produces only the last line

data = Hash.new
require 'yaml'
filename = 'Ydata.txt'

File.read('Data.txt').each_line do |line|
  line = line.chomp
  line = line.split ';'
  data = { "#{line[0]}" => "#{line[1]}" }.to_yaml
end

File.open filename, 'w' do |f|
   f.write data
end

Body:
It looks like you are overriding data in every iteration with a new YAML string with only one entry. This is why you see only the last line. Try building the complete ruby hash and converting the whole hash to YAML at the end. Like this:

require 'yaml'

data = Hash.new
File.read('Data.txt').each_line do |line|
  k, v = line.chomp.split(';', 2)
  data[k] = v
end
File.open('Ydata.txt', 'w') do |f|
   f.write(data.to_yaml)
end


问:
Reducing memory foot print in Apache Ignite 2.0
I am using Apache Ignite 2.0 as key-value store.  My key will be 10 to 15 digit number and value is a single integer. I intent to store around 500 million such key-value pairs.

On benchmarking, found that to store 1million such key-value entries, the memory utilisation is around 90MB. To store just an integer as value, I don't want to invest such huge memory. i.e., around 90Bytes per record having single integer as value.

Can someone throw some light on how can I reduce memory overheads used in key. Are there any configurations? As I don't need any compression, can I cut down BinaryObjectImpl which is using 40Bytes or some other meta info?

OR if someone can highlight on other kv-stores or technologies I can explore to store huge number of records (even few billions) with lesser memory foot print would be appreciated.

Update:
I am using example-cache.xml as my configuration which is shipped as is without any changes.

Thanks in Advance.

答:
If you only need a key-value store (no data grid) have you tried MapDB? http://www.mapdb.org/

It offers off-heap storage and scales well. We've used it successfully in a couple of projects for cache storage.


问:
Accessing Bloomberg API from client's browser in javascript
Is it possible to access blpapi from javascript running in the client's browser?

I wish to access bloomberg's API from javascript running in the client's browser, in the assumption that the client has an open bloomberg session and therefore bbcomm is running.

Conceptually, this would be the same as accessing the blpapi on the client side from python.

However, all existing solutions I found in js appear to be server-side:

blpapi-node (node-based)

blpapi-httm (creates a server where to post http request)

blpapi-react (cannot make this module work)

答:
This is obsolete, see Mourad Barakat's answer above

Conversation with Bloomberg Support confirms this is not possible**

BB say they don't support javascript access, and that one solution is to use their Server API to use the authentication of the client (who has a bb terminal open) to query data and return it to the client

An alternative hack

An alternative hack is to create an executable mini-server that the client downloads and launches, and that offers an http interface to get data to the webapp.

For example, this could be done in Flask in Python, and in fact it has already been done by blpapi-web (excluding the executable part, for which you can use PyInstaller and py2exe for Windows and py2app for Mac)


问:
How to make click to call in Ionic For IOS?
I have tried this method and it is working perfevtly in Android but not in IOS

```<code><a href="tel: 1111111">Call</a>
</code>```

And in my config.xml file

```<code><access origin="tel:*" launch-external="yes" />
</code>```

the above method is tested in real devices and it is working only for android, is there any other method to make it work in IOS

答:
For your code to work on IOS you need to add in the config.xml

```<code><allow-navigation href="tel:*" />
</code>```

Doing this breaks the functionality on android so make sure to add it inside

```<code><platform name="ios">
</code>```

Body:
I have tried this method and it is working perfevtly in Android but not in IOS

Call

And in my config.xml file

<access origin="tel:*" launch-external="yes" />

the above method is tested in real devices and it is working only for android, is there any other method to make it work in IOS

Body:
For your code to work on IOS you need to add in the config.xml

<allow-navigation href="tel:*" />

Doing this breaks the functionality on android so make sure to add it inside

<platform name="ios">


问:
"unbound method connect()" error while connecting to Testlink through python
```<code>from XMLRPC.TestLinkAPI.src import testlink
class ConnectToTestLink:

    TESTLINK_API_PYTHON_SERVER_URL = "abc.com";
    TESTLINK_API_PYTHON_DEVKEY = "e9e245fdhsgfdsghfd18e9"
    tls = testlink.TestLinkHelper.connect(testlink.TestlinkAPIClient)
    #tls.countProjects();
</code>```

I am getting the error below:

```<code>unbound method connect() must be called with TestLinkHelper instance as first argument (got type instance instead)
</code>```

(For reference, I am following this url:
https://pypi.python.org/pypi/TestLink-API-Python-client )

答:
```<code> tls = testlink.TestLinkHelper(ConnectToTestLink.TESTLINK_API_PYTHON_SERVER_URL,
                                  ConnectToTestLink.TESTLINK_API_PYTHON_DEVKEY).connect(testlink.TestlinkAPIClient)
</code>```

Body:
from XMLRPC.TestLinkAPI.src import testlink
class ConnectToTestLink:

    TESTLINK_API_PYTHON_SERVER_URL = "abc.com";
    TESTLINK_API_PYTHON_DEVKEY = "e9e245fdhsgfdsghfd18e9"
    tls = testlink.TestLinkHelper.connect(testlink.TestlinkAPIClient)
    #tls.countProjects();

I am getting the error below:

unbound method connect() must be called with TestLinkHelper instance as first argument (got type instance instead)

(For reference, I am following this url:
https://pypi.python.org/pypi/TestLink-API-Python-client )


问:
How to clear logon credentials from WebView?
I want to clear application data like i can do it from settings. I need to clear login information in WebView when i am login to facebook or twitter, because when i log on once for each of the following uses the same data automatically

I try this:
http://www.hrupin.com/2011/11/how-to-clear-user-data-in-your-android-application-programmatically

didn't work, login information are still in browser

I try reset app:

```<code>Intent i = getBaseContext().getPackageManager()
             .getLaunchIntentForPackage( getBaseContext().getPackageName() );
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
</code>```

also

```<code>@Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        view.clearCache(true);

        if(b){
            Log.d("WEBVIEW", "onFinisghed b true");
        Map<String, String> noCacheHeaders = new HashMap<String, String>(2);
        noCacheHeaders.put("Pragma", "no-cache");
        noCacheHeaders.put("Cache-Control", "no-cache");
        view.loadUrl(url, noCacheHeaders);
        b = false;
        }...
</code>```

Most of the entries refers to the first method which is described in the link, but it does not work in my case, any ideas?

答:
```<code>CookieManager.getInstance().removeAllCookie();
</code>```

above method will resolved problem but This method was deprecated in API level 21 so use removeAllCookies(ValueCallback) instead.

This method is asynchronous. If a ValueCallback is provided, onReceiveValue() will be called on the current thread's Looper once the operation is complete. The value provided to the callback indicates whether any cookies were removed. You can pass null as the callback if you don't need to know when the operation completes or whether any cookies were removed, and in this case it is safe to call the method from a thread without a Looper.

ValueCallback: a callback which is executed when the cookies have been removed

Body:
I want to clear application data like i can do it from settings. I need to clear login information in WebView when i am login to facebook or twitter, because when i log on once for each of the following uses the same data automatically

I try this:
http://www.hrupin.com/2011/11/how-to-clear-user-data-in-your-android-application-programmatically

didn't work, login information are still in browser

I try reset app:

Intent i = getBaseContext().getPackageManager()
             .getLaunchIntentForPackage( getBaseContext().getPackageName() );
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);

also

@Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        view.clearCache(true);

        if(b){
            Log.d("WEBVIEW", "onFinisghed b true");
        Map<String, String> noCacheHeaders = new HashMap<String, String>(2);
        noCacheHeaders.put("Pragma", "no-cache");
        noCacheHeaders.put("Cache-Control", "no-cache");
        view.loadUrl(url, noCacheHeaders);
        b = false;
        }...

Most of the entries refers to the first method which is described in the link, but it does not work in my case, any ideas?

Body:
CookieManager.getInstance().removeAllCookie();

above method will resolved problem but This method was deprecated in API level 21 so use removeAllCookies(ValueCallback) instead.

This method is asynchronous. If a ValueCallback is provided, onReceiveValue() will be called on the current thread's Looper once the operation is complete. The value provided to the callback indicates whether any cookies were removed. You can pass null as the callback if you don't need to know when the operation completes or whether any cookies were removed, and in this case it is safe to call the method from a thread without a Looper.

ValueCallback: a callback which is executed when the cookies have been removed


问:
rails form_for ActionView::Template::Error: undefined method `journals_path
I have a journal model for every user.

In routes.rb I have:

```<code>resources :users do
  resources :journals
end
</code>```

In user model:

```<code>has_many :journals
</code>```

In journals model:

```<code>belongs_to :user
</code>```

When try to use form_for(journal) I get:

```<code>undefined method `journals_path'
</code>```

I do not know how fix this.

form_for the first line:

```<code><%= form_for(journal) do |f| %>
</code>```

答:
Since it is a nested resource, you have to include parent user like this:

```<code><%= form_for [@user, @journal] do |f| %>
</code>```

To get the correct path

Body:
I have a journal model for every user.

In routes.rb I have:

resources :users do
  resources :journals
end

In user model:

has_many :journals

In journals model:

belongs_to :user

When try to use form_for(journal) I get:

undefined method `journals_path'

I do not know how fix this.

form_for the first line:

<%= form_for(journal) do |f| %>

Body:
Since it is a nested resource, you have to include parent user like this:

<%= form_for [@user, @journal] do |f| %>

To get the correct path


问:
Div content misalignment
Here is my jsfiddle : DEMO

```<code>The text content written within the <div>'s moves up
</code>```

Can someone tell me why is this happening?
What's the fix for this?

Any help would be much appreciated. Thanks!

答: Try to get rid off the line-height: 8%; property from .rule class.

Title: Div content misalignment

Body:
Here is my jsfiddle : DEMO

The text content written within the
's moves up

Can someone tell me why is this happening?
What's the fix for this?

Any help would be much appreciated. Thanks!


问:
Read Named Range Names into VBA array
I'm trying to figure out how I can get the names of ranges in a given worksheet into an array. I've got as far as the listnames function but that seems to list them all in one go. Any ideas?</p>

答:
My version is I used dynamic array:</p>

```<code>    Sub TestNamedRange()
    Dim i As Long
    Dim intCount As Long
    Dim NameArray() As String
    'count number of named ranges
    intCount = ThisWorkbook.Names.Count
    ReDim NameArray(intCount)  'for dynamic number of named ranges
    'assign all names to each array element
    For i = 1 To intCount
      NameArray(i) = ThisWorkbook.Names(i).Name 'remove .Name if you want address range only
    Next
   'check array elements
   For Each ele In NameArray
     Debug.Print ele
   Next
  'manipulate your array here
  End Sub
</code>```

Title: Read Named Range Names into VBA array

Body:
My version is I used dynamic array:

    Sub TestNamedRange()
    Dim i As Long
    Dim intCount As Long
    Dim NameArray() As String
    'count number of named ranges
    intCount = ThisWorkbook.Names.Count
    ReDim NameArray(intCount)  'for dynamic number of named ranges
    'assign all names to each array element
    For i = 1 To intCount
      NameArray(i) = ThisWorkbook.Names(i).Name 'remove .Name if you want address range only
    Next
   'check array elements
   For Each ele In NameArray
     Debug.Print ele
   Next
  'manipulate your array here
  End Sub


问:
The service certificate is not provided for target '###' Specify a service certificate in ClientCredentials
I have implemented a test Client / Server that implements UserName message authentication over WCF.  It almost all works however I have fallen at the last hurdle.

I get an InvalidOperationException that reads

The service certificate is not provided for target 'http://localhost:8732/Design_Time_Addresses/EvalServiceLibrary/Service1/'. Specify a service certificate in ClientCredentials.

Can anyone shed any light?

Thanks

答: Sounds like your requiring a certificate for security and your client code is not supplying the certificate on request.  WCF Security</p>


问:
Filtering Ruby array of hashes by another hash
Perhaps I'm missing something obvious.  It seems tricky to filter a hash by another hash or multiple key/value pairs.

```<code>fruit = [
  { name: "apple",   color: "red",    pieable: true  },
  { name: "orange",  color: "orange", pieable: false },
  { name: "grape",   color: "purple", pieable: false },
  { name: "cherry",  color: "red",    pieable: true  },
  { name: "banana",  color: "yellow", pieable: true  },
  { name: "tomato",  color: "red",    pieable: false }
]
filter = { color: "red", pieable: true }

# some awesome one-liner? would return
[
  { name: "apple",   color: "red",    pieable: true  },
  { name: "cherry",  color: "red",    pieable: true  }
]
</code>```

The array of hashes I don't think is the problem.  I don't even know how to test a hash by another arbitrary hash.  I'm using Rails so anything out of active_support etc is fine.

答:
Try this</p>

```<code>fruit.select{ |hash| (filter.to_a & hash.to_a) == filter.to_a }

=> [{:name=>"apple", :color=>"red", :pieable=>true},
    {:name=>"cherry", :color=>"red", :pieable=>true}]
</code>```

Body:
Perhaps I'm missing something obvious.  It seems tricky to filter a hash by another hash or multiple key/value pairs.

fruit = [
  { name: "apple",   color: "red",    pieable: true  },
  { name: "orange",  color: "orange", pieable: false },
  { name: "grape",   color: "purple", pieable: false },
  { name: "cherry",  color: "red",    pieable: true  },
  { name: "banana",  color: "yellow", pieable: true  },
  { name: "tomato",  color: "red",    pieable: false }
]
filter = { color: "red", pieable: true }

# some awesome one-liner? would return
[
  { name: "apple",   color: "red",    pieable: true  },
  { name: "cherry",  color: "red",    pieable: true  }
]

The array of hashes I don't think is the problem.  I don't even know how to test a hash by another arbitrary hash.  I'm using Rails so anything out of active_support etc is fine.

Body:
Try this

fruit.select{ |hash| (filter.to_a & hash.to_a) == filter.to_a }

=> [{:name=>"apple", :color=>"red", :pieable=>true},
    {:name=>"cherry", :color=>"red", :pieable=>true}]


问:
ERROR AFTER CHANGING NAMESPACE OF ASP.net MVC PROJECT
Recently i have changed the namespace using the project properties. After that, application was compiling successfully, but at run-time it throws error  "The type or namespace name ‘sample’ could not be found (are you missing a using directive or an assembly reference?)".
Error:
Line 23:     using System.Web.Routing;
Line 24:     using Sample;

Source File: c:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET Files......\App_Web_index.cs    Line:

I tried to locate the string  “using Sample” and didn’t find anywhere in my solution.
Tried removing the temporary files from framework folder but no luck.

答:
The problem was with my Web.config file

```<code><system.web.webPages.razor>
 <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
 <pages pageBaseType="System.Web.Mvc.WebViewPage">
  <namespaces>
    <add namespace="System.Web.Mvc" />
    <add namespace="System.Web.Mvc.Ajax" />
    <add namespace="System.Web.Mvc.Html" />
    <add namespace="System.Web.Optimization"/>
    <add namespace="System.Web.Routing" />
    <add namespace="Sample" />
  </namespaces>
</pages>
</code>```

I just replaced the old value "Sample" with new namespace name, and everything starts working again.

Body:
The problem was with my Web.config file

<system.web.webPages.razor>
 <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
 <pages pageBaseType="System.Web.Mvc.WebViewPage">
  <namespaces>
    <add namespace="System.Web.Mvc" />
    <add namespace="System.Web.Mvc.Ajax" />
    <add namespace="System.Web.Mvc.Html" />
    <add namespace="System.Web.Optimization"/>
    <add namespace="System.Web.Routing" />
    <add namespace="Sample" />
  </namespaces>
</pages>

I just replaced the old value "Sample" with new namespace name, and everything starts working again.


问:
Error inflating class com.mapbox.mapboxsdk.views.MapView
I am trying to put a mapbox in a fragment and it is not inflating. Here is my logcat:

```<code>android.view.InflateException: Binary XML file line #9: Error inflating class com.mapbox.mapboxsdk.views.MapView
            at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:757)
            at android.view.LayoutInflater.rInflate(LayoutInflater.java:806)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:504)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:414)
            at inscope.inscope.Map.onCreateView(Map.java:33)
            at android.support.v4.app.Fragment.performCreateView(Fragment.java:1962)
            at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067)
            at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1248)
            at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738)
            at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1613)
            at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:570)
            at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
            at android.support.v4.view.ViewPager.populate(ViewPager.java:1106)
            at android.support.v4.view.ViewPager.populate(ViewPager.java:952)
            at android.support.v4.view.ViewPager$3.run(ViewPager.java:251)
            at android.view.Choreographer$CallbackRecord.run(Choreographer.java:767)
            at android.view.Choreographer.doCallbacks(Choreographer.java:580)
            at android.view.Choreographer.doFrame(Choreographer.java:549)
            at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:753)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5257)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
     Caused by: java.lang.ClassNotFoundException: Didn't find class "com.mapbox.mapboxsdk.views.MapView" on path: DexPathList[[zip file "/data/app/inscope.inscope-2/base.apk"],nativeLibraryDirectories=[/data/app/inscope.inscope-2/lib/x86, /vendor/lib, /system/lib]]
            at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
            at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
            at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
            at android.view.LayoutInflater.createView(LayoutInflater.java:571)
            at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:743)
            at android.view.LayoutInflater.rInflate(LayoutInflater.java:806)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:504)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:414)
            at inscope.inscope.Map.onCreateView(Map.java:33)
            at android.support.v4.app.Fragment.performCreateView(Fragment.java:1962)
            at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067)
            at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1248)
            at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738)
            at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1613)
            at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:570)
            at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
            at android.support.v4.view.ViewPager.populate(ViewPager.java:1106)
            at android.support.v4.view.ViewPager.populate(ViewPager.java:952)
            at android.support.v4.view.ViewPager$3.run(ViewPager.java:251)
            at android.view.Choreographer$CallbackRecord.run(Choreographer.java:767)
            at android.view.Choreographer.doCallbacks(Choreographer.java:580)
            at android.view.Choreographer.doFrame(Choreographer.java:549)
            at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:753)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5257)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
    Suppressed: java.lang.ClassNotFoundException: com.mapbox.mapboxsdk.views.MapView
            at java.lang.Class.classForName(Native Method)
            at java.lang.BootClassLoader.findClass(ClassLoader.java:781)
            at java.lang.BootClassLoader.loadClass(ClassLoader.java:841)
            at java.lang.ClassLoader.loadClass(ClassLoader.java:504)
            ... 29 more
     Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack available
03-31 02:37:53.714    1220-1569/system_process W/ActivityManager﹕ Force finishing activity 1 inscope.inscope/.Main
03-31 02:37:53.774   1220-17998/system_process I/OpenGLRenderer﹕ Initialized EGL, version 1.4
03-31 02:37:53.785   1220-17998/system_process W/EGL_emulation﹕ eglSurfaceAttrib not implemented
03-31 02:37:53.785   1220-17998/system_process W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0x9e00f7c0, error=EGL_SUCCESS
03-31 02:37:54.230    1220-1238/system_process W/ActivityManager﹕ Activity pause timeout for ActivityRecord{2177629c u0 inscope.inscope/.Main t149 f}
03-31 02:37:55.921    1220-1280/system_process W/AudioTrack﹕ AUDIO_OUTPUT_FLAG_FAST denied by client
03-31 02:37:55.956  19375-19375/inscope.inscope I/Process﹕ Sending signal. PID: 19375 SIG: 9
03-31 02:37:55.978   1220-17998/system_process D/OpenGLRenderer﹕ endAllStagingAnimators on 0xa21ea080 (RippleDrawable) with handle 0xa21faa00
03-31 02:37:56.005    1220-1389/system_process I/WindowState﹕ WIN DEATH: Window{21136934 u0 inscope.inscope/inscope.inscope.Main}
03-31 02:37:56.009    1220-1628/system_process I/WindowState﹕ WIN DEATH: Window{24af30ca u0 inscope.inscope/inscope.inscope.MainActivity}
03-31 02:37:56.051    1220-1282/system_process I/ActivityManager﹕ Process inscope.inscope (pid 19375) has died
03-31 02:37:56.265    1220-1243/system_process V/WindowManager﹕ Adding window Window{38d8443d u0 Starting inscope.inscope} at 2 of 9 (before Window{21136934 u0 inscope.inscope/inscope.inscope.Main EXITING})
03-31 02:37:56.288    1220-1282/system_process I/ActivityManager﹕ Start proc 19607:inscope.inscope/u0a60 for activity inscope.inscope/.MainActivity
03-31 02:37:56.362  19607-19607/? I/art﹕ Not late-enabling -Xcheck:jni (already on)
03-31 02:37:56.398  19607-19614/? E/art﹕ Failed sending reply to debugger: Broken pipe
03-31 02:37:56.404      934-934/? I/art﹕ Explicit concurrent mark sweep GC freed 710(30KB) AllocSpace objects, 0(0B) LOS objects, 91% free, 92KB/1116KB, paused 2.537ms total 97.855ms
03-31 02:37:56.398  19607-19614/? I/art﹕ Debugger is no longer active
03-31 02:37:56.420  19607-19614/? W/art﹕ Suspending all threads took: 6.845ms
03-31 02:37:56.450      934-934/? I/art﹕ Explicit concurrent mark sweep GC freed 6(208B) AllocSpace objects, 0(0B) LOS objects, 91% free, 92KB/1116KB, paused 1.423ms total 44.264ms
03-31 02:37:56.476  19607-19607/? D/test﹕ before login
03-31 02:37:56.492      934-934/? I/art﹕ Explicit concurrent mark sweep GC freed 5(160B) AllocSpace objects, 0(0B) LOS objects, 91% free, 92KB/1116KB, paused 24.549ms total 39.827ms
03-31 02:37:56.699  19607-19607/? D/test﹕ set view to login_screen
03-31 02:37:56.821  19607-19631/? D/OpenGLRenderer﹕ Use EGL_SWAP_BEHAVIOR_PRESERVED: true
03-31 02:37:56.825  19607-19607/? D/﹕ HostConnection::get() New Host Connection established 0xb42b3c30, tid 19607
03-31 02:37:56.833  19607-19607/? D/Atlas﹕ Validating map...
03-31 02:37:56.835    1220-1569/system_process V/WindowManager﹕ Adding window Window{18bdf5 u0 inscope.inscope/inscope.inscope.MainActivity} at 2 of 9 (before Window{38d8443d u0 Starting inscope.inscope})
03-31 02:37:56.852  19607-19619/? I/art﹕ Background partial concurrent mark sweep GC freed 347(41KB) AllocSpace objects, 0(0B) LOS objects, 10% free, 32MB/36MB, paused 6.947ms total 71.880ms
03-31 02:37:56.884  19607-19631/? D/﹕ HostConnection::get() New Host Connection established 0xb43fa370, tid 19631
03-31 02:37:56.895  19607-19631/? I/OpenGLRenderer﹕ Initialized EGL, version 1.4
03-31 02:37:56.914  19607-19631/? D/OpenGLRenderer﹕ Enabling debug mode 0
03-31 02:37:56.923  19607-19631/? W/EGL_emulation﹕ eglSurfaceAttrib not implemented
03-31 02:37:56.924  19607-19631/? W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xb43b2ae0, error=EGL_SUCCESS
03-31 02:37:57.223    1220-1243/system_process I/ActivityManager﹕ Displayed inscope.inscope/.MainActivity: +971ms
03-31 02:37:57.226    1220-1372/system_process W/InputMethodManagerService﹕ Got RemoteException sending setActive(false) notification to pid 19375 uid 10060
03-31 02:38:22.030    1220-2153/system_process I/art﹕ Explicit concurrent mark sweep GC freed 35331(1734KB) AllocSpace objects, 11(173KB) LOS objects, 33% free, 7MB/11MB, paused 1.285ms total 26.801ms
03-31 02:38:22.086   1685-19806/com.google.process.gapps I/GoogleURLConnFactory﹕ binding HttpService
03-31 02:38:22.086   1685-19806/com.google.process.gapps I/GoogleHttpClient﹕ Falling back to old SSLCertificateSocketFactory
03-31 02:38:22.147   1685-19806/com.google.process.gapps W/Uploader﹕ No account for auth token provided
03-31 02:38:22.287   1685-19806/com.google.process.gapps W/Uploader﹕ No account for auth token provided
03-31 02:38:22.404   1685-19806/com.google.process.gapps W/Uploader﹕ no longer exists, so no auth token.
03-31 02:38:22.549   1685-19806/com.google.process.gapps W/Uploader﹕ No account for auth token provided
03-31 02:38:22.643   1685-19806/com.google.process.gapps W/Uploader﹕ No account for auth token provided
03-31 02:38:22.743   1685-19806/com.google.process.gapps W/Uploader﹕ No account for auth token provided
03-31 02:38:22.885    1685-1696/com.google.process.gapps E/StrictMode﹕ A resource was acquired at attached stack trace but never released. See java.io.Closeable for information on avoiding resource leaks.
    java.lang.Throwable: Explicit termination method 'end' not called
            at dalvik.system.CloseGuard.open(CloseGuard.java:184)
            at java.util.zip.Inflater.<init>(Inflater.java:82)
            at com.android.okio.GzipSource.<init>(GzipSource.java:57)
            at com.android.okhttp.internal.http.HttpEngine.initContentStream(HttpEngine.java:490)
            at com.android.okhttp.internal.http.HttpEngine.readResponse(HttpEngine.java:680)
            at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:388)
            at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:332)
            at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:500)
            at com.android.okhttp.internal.http.DelegatingHttpsURLConnection.getResponseCode(DelegatingHttpsURLConnection.java:105)
            at com.android.okhttp.internal.http.HttpsURLConnectionImpl.getResponseCode(HttpsURLConnectionImpl.java:25)
            at com.google.android.gms.http.GoogleHttpClient.a(SourceFile:806)
            at com.google.android.gms.http.GoogleHttpClient.b(SourceFile:770)
            at com.google.android.gms.http.GoogleHttpClient.execute(SourceFile:673)
            at com.google.android.gms.http.GoogleHttpClient.execute(SourceFile:664)
            at com.google.android.gms.playlog.uploader.b.a(SourceFile:332)
            at com.google.android.gms.playlog.uploader.b.a(SourceFile:227)
            at com.google.android.gms.playlog.uploader.b.a(SourceFile:199)
            at com.google.android.gms.playlog.uploader.UploaderService.a(SourceFile:39)
            at com.google.android.gms.gcm.af.run(SourceFile:130)
03-31 02:38:27.903    1685-1696/com.google.process.gapps E/StrictMode﹕ A resource was acquired at attached stack trace but never released. See java.io.Closeable for information on avoiding resource leaks.
    java.lang.Throwable: Explicit termination method 'end' not called
            at dalvik.system.CloseGuard.open(CloseGuard.java:184)
            at java.util.zip.Inflater.<init>(Inflater.java:82)
            at com.android.okio.GzipSource.<init>(GzipSource.java:57)
            at com.android.okhttp.internal.http.HttpEngine.initContentStream(HttpEngine.java:490)
            at com.android.okhttp.internal.http.HttpEngine.readResponse(HttpEngine.java:680)
            at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:388)
            at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:332)
            at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:500)
            at com.android.okhttp.internal.http.DelegatingHttpsURLConnection.getResponseCode(DelegatingHttpsURLConnection.java:105)
            at com.android.okhttp.internal.http.HttpsURLConnectionImpl.getResponseCode(HttpsURLConnectionImpl.java:25)
            at     com.google.android.gms.http.GoogleHttpClient.a(SourceFile:806)
            at com.google.android.gms.http.GoogleHttpClient.b(SourceFile:770)
            at com.google.android.gms.http.GoogleHttpClient.execute(SourceFile:673)
            at com.google.android.gms.http.GoogleHttpClient.execute(SourceFile:664)
            at com.google.android.gms.playlog.uploader.b.a(SourceFile:332)
            at com.google.android.gms.playlog.uploader.b.a(SourceFile:227)
            at com.google.android.gms.playlog.uploader.b.a(SourceFile:199)
            at com.google.android.gms.playlog.uploader.UploaderService.a(SourceFile:39)
            at com.google.android.gms.gcm.af.run(SourceFile:130)
03-31 02:39:22.017    1685-1685/com.google.process.gapps W/GCM﹕ Heartbeat timeout, GCM connection reset
03-31 02:39:22.041    1220-1372/system_process D/ConnectivityService﹕ reportBadNetwork(NetworkAgentInfo [MOBILE (UMTS) - 100]) by 10007
03-31 02:39:22.049    1220-1679/system_process D/NetworkMonitor/NetworkAgentInfo [MOBILE (UMTS) - 100]﹕ ValidatedState{ when=-6ms what=532488 arg1=10007 target=com.android.internal.util.StateMachine$SmHandler }
03-31 02:39:22.049    1220-1679/system_process D/NetworkMonitor/NetworkAgentInfo [MOBILE (UMTS) - 100]﹕ DefaultState{ when=-8ms what=532488 arg1=10007 target=com.android.internal.util.StateMachine$SmHandler }
03-31 02:39:22.049    1220-1679/system_process D/NetworkMonitor/NetworkAgentInfo [MOBILE (UMTS) - 100]﹕ Forcing reevaluation
03-31 02:39:22.050    1220-1679/system_process D/NetworkMonitor/NetworkAgentInfo [MOBILE (UMTS) - 100]﹕ EvaluatingState{ when=-1ms what=532486 arg1=3 target=com.android.internal.util.StateMachine$SmHandler }
03-31 02:39:22.055    1220-1679/system_process D/NetworkMonitor/NetworkAgentInfo [MOBILE (UMTS) - 100]﹕ Checking http://connectivitycheck.android.com/generate_204 on epc.tmobile.com
03-31 02:39:22.087    1220-1679/system_process D/NetworkMonitor/NetworkAgentInfo [MOBILE (UMTS) - 100]﹕ isCaptivePortal: ret=204 headers={null=[HTTP/1.1 204 No Content], Content-Length=[0], Date=[Thu, 31 Mar 2016 06:40:08 GMT], X-Android-Received-Millis=[1459406362087], X-Android-Response-Source=[NETWORK 204], X-Android-Sent-Millis=[1459406362075]}
03-31 02:39:22.087    1220-1679/system_process D/NetworkMonitor/NetworkAgentInfo [MOBILE (UMTS) - 100]﹕ Don't send network conditions - lacking user consent.
03-31 02:39:22.087    1220-1679/system_process D/NetworkMonitor/NetworkAgentInfo [MOBILE (UMTS) - 100]﹕ Validated
03-31 02:39:22.089    1220-1276/system_process D/ConnectivityService﹕ setProvNotificationVisibleIntent: E visible=false networkType=0 extraInfo=null
03-31 02:39:22.090    1220-1276/system_process D/ConnectivityService﹕ Validated NetworkAgentInfo [MOBILE (UMTS) - 100]
03-31 02:39:31.679   1685-20285/com.google.process.gapps D/GCM﹕ Connected
03-31 02:39:31.719   1685-20285/com.google.process.gapps D/GCM﹕ Message class com.google.e.a.a.q
03-31 02:41:04.560  19607-19614/inscope.inscope W/art﹕ Suspending all threads took: 15.170ms
03-31 02:44:00.059    1220-1238/system_process I/ProcessStatsService﹕ Prepared write state in 1ms
</code>```

Here is my fragment class:

```<code>public class Map extends android.support.v4.app.Fragment {
private MapView mapView;

public Map() {
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View layout = inflater.inflate(R.layout.fragment_map, container, false);

    MapView mapView = (MapView) layout.findViewById(R.id.mapview);
    mapView.onCreate(savedInstanceState);
    mapView.getMapAsync(new OnMapReadyCallback() {
        @Override
        public void onMapReady(MapboxMap mapboxMap) {

            // Set map style
            mapboxMap.setStyleUrl(Style.MAPBOX_STREETS);

            // Set the camera's starting position
            CameraPosition cameraPosition = new CameraPosition.Builder()
                    .target(new LatLng(41.885, -87.679)) // set the camera's center position
                    .zoom(12)  // set the camera's zoom level
                    .tilt(20)  // set the camera's tilt
                    .build();

            // Move the camera to that position
            mapboxMap.moveCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

        }

    });
    return layout;
}
</code>```

Here is the xml:

```<code><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:mapbox="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="inscope.inscope.Map">

<!-- TODO: Update blank fragment layout -->
<com.mapbox.mapboxsdk.views.MapView
    android:id="@+id/mapview"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    mapbox:access_token="my Token" />
</code>```

I have followed the mapbox instructions on their website for gradle and permissions so I'm sure there is nothing wrong with those. It says something is wrong with the "View layout = inflater..." line, except I cant figure out what could be the problem.

答:
i would like to add a small point to @Tirth Allspark Rami answer.

```<code>Mapbox.getInstance(this,access_token)
</code>```

should come right after

```<code>super.onCreate()
</code>```

before assigning any layout to view.

Body:
I am trying to put a mapbox in a fragment and it is not inflating. Here is my logcat:

android.view.InflateException: Binary XML file line #9: Error inflating class com.mapbox.mapboxsdk.views.MapView
            at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:757)
            at android.view.LayoutInflater.rInflate(LayoutInflater.java:806)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:504)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:414)
            at inscope.inscope.Map.onCreateView(Map.java:33)
            at android.support.v4.app.Fragment.performCreateView(Fragment.java:1962)
            at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067)
            at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1248)
            at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738)
            at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1613)
            at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:570)
            at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
            at android.support.v4.view.ViewPager.populate(ViewPager.java:1106)
            at android.support.v4.view.ViewPager.populate(ViewPager.java:952)
            at android.support.v4.view.ViewPager$3.run(ViewPager.java:251)
            at android.view.Choreographer$CallbackRecord.run(Choreographer.java:767)
            at android.view.Choreographer.doCallbacks(Choreographer.java:580)
            at android.view.Choreographer.doFrame(Choreographer.java:549)
            at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:753)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5257)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
     Caused by: java.lang.ClassNotFoundException: Didn't find class "com.mapbox.mapboxsdk.views.MapView" on path: DexPathList[[zip file "/data/app/inscope.inscope-2/base.apk"],nativeLibraryDirectories=[/data/app/inscope.inscope-2/lib/x86, /vendor/lib, /system/lib]]
            at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
            at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
            at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
            at android.view.LayoutInflater.createView(LayoutInflater.java:571)
            at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:743)
            at android.view.LayoutInflater.rInflate(LayoutInflater.java:806)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:504)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:414)
            at inscope.inscope.Map.onCreateView(Map.java:33)
            at android.support.v4.app.Fragment.performCreateView(Fragment.java:1962)
            at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067)
            at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1248)
            at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738)
            at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1613)
            at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:570)
            at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
            at android.support.v4.view.ViewPager.populate(ViewPager.java:1106)
            at android.support.v4.view.ViewPager.populate(ViewPager.java:952)
            at android.support.v4.view.ViewPager$3.run(ViewPager.java:251)
            at android.view.Choreographer$CallbackRecord.run(Choreographer.java:767)
            at android.view.Choreographer.doCallbacks(Choreographer.java:580)
            at android.view.Choreographer.doFrame(Choreographer.java:549)
            at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:753)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5257)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
    Suppressed: java.lang.ClassNotFoundException: com.mapbox.mapboxsdk.views.MapView
            at java.lang.Class.classForName(Native Method)
            at java.lang.BootClassLoader.findClass(ClassLoader.java:781)
            at java.lang.BootClassLoader.loadClass(ClassLoader.java:841)
            at java.lang.ClassLoader.loadClass(ClassLoader.java:504)
            ... 29 more
     Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack available
03-31 02:37:53.714    1220-1569/system_process W/ActivityManager﹕ Force finishing activity 1 inscope.inscope/.Main
03-31 02:37:53.774   1220-17998/system_process I/OpenGLRenderer﹕ Initialized EGL, version 1.4
03-31 02:37:53.785   1220-17998/system_process W/EGL_emulation﹕ eglSurfaceAttrib not implemented
03-31 02:37:53.785   1220-17998/system_process W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0x9e00f7c0, error=EGL_SUCCESS
03-31 02:37:54.230    1220-1238/system_process W/ActivityManager﹕ Activity pause timeout for ActivityRecord{2177629c u0 inscope.inscope/.Main t149 f}
03-31 02:37:55.921    1220-1280/system_process W/AudioTrack﹕ AUDIO_OUTPUT_FLAG_FAST denied by client
03-31 02:37:55.956  19375-19375/inscope.inscope I/Process﹕ Sending signal. PID: 19375 SIG: 9
03-31 02:37:55.978   1220-17998/system_process D/OpenGLRenderer﹕ endAllStagingAnimators on 0xa21ea080 (RippleDrawable) with handle 0xa21faa00
03-31 02:37:56.005    1220-1389/system_process I/WindowState﹕ WIN DEATH: Window{21136934 u0 inscope.inscope/inscope.inscope.Main}
03-31 02:37:56.009    1220-1628/system_process I/WindowState﹕ WIN DEATH: Window{24af30ca u0 inscope.inscope/inscope.inscope.MainActivity}
03-31 02:37:56.051    1220-1282/system_process I/ActivityManager﹕ Process inscope.inscope (pid 19375) has died
03-31 02:37:56.265    1220-1243/system_process V/WindowManager﹕ Adding window Window{38d8443d u0 Starting inscope.inscope} at 2 of 9 (before Window{21136934 u0 inscope.inscope/inscope.inscope.Main EXITING})
03-31 02:37:56.288    1220-1282/system_process I/ActivityManager﹕ Start proc 19607:inscope.inscope/u0a60 for activity inscope.inscope/.MainActivity
03-31 02:37:56.362  19607-19607/? I/art﹕ Not late-enabling -Xcheck:jni (already on)
03-31 02:37:56.398  19607-19614/? E/art﹕ Failed sending reply to debugger: Broken pipe
03-31 02:37:56.404      934-934/? I/art﹕ Explicit concurrent mark sweep GC freed 710(30KB) AllocSpace objects, 0(0B) LOS objects, 91% free, 92KB/1116KB, paused 2.537ms total 97.855ms
03-31 02:37:56.398  19607-19614/? I/art﹕ Debugger is no longer active
03-31 02:37:56.420  19607-19614/? W/art﹕ Suspending all threads took: 6.845ms
03-31 02:37:56.450      934-934/? I/art﹕ Explicit concurrent mark sweep GC freed 6(208B) AllocSpace objects, 0(0B) LOS objects, 91% free, 92KB/1116KB, paused 1.423ms total 44.264ms
03-31 02:37:56.476  19607-19607/? D/test﹕ before login
03-31 02:37:56.492      934-934/? I/art﹕ Explicit concurrent mark sweep GC freed 5(160B) AllocSpace objects, 0(0B) LOS objects, 91% free, 92KB/1116KB, paused 24.549ms total 39.827ms
03-31 02:37:56.699  19607-19607/? D/test﹕ set view to login_screen
03-31 02:37:56.821  19607-19631/? D/OpenGLRenderer﹕ Use EGL_SWAP_BEHAVIOR_PRESERVED: true
03-31 02:37:56.825  19607-19607/? D/﹕ HostConnection::get() New Host Connection established 0xb42b3c30, tid 19607
03-31 02:37:56.833  19607-19607/? D/Atlas﹕ Validating map...
03-31 02:37:56.835    1220-1569/system_process V/WindowManager﹕ Adding window Window{18bdf5 u0 inscope.inscope/inscope.inscope.MainActivity} at 2 of 9 (before Window{38d8443d u0 Starting inscope.inscope})
03-31 02:37:56.852  19607-19619/? I/art﹕ Background partial concurrent mark sweep GC freed 347(41KB) AllocSpace objects, 0(0B) LOS objects, 10% free, 32MB/36MB, paused 6.947ms total 71.880ms
03-31 02:37:56.884  19607-19631/? D/﹕ HostConnection::get() New Host Connection established 0xb43fa370, tid 19631
03-31 02:37:56.895  19607-19631/? I/OpenGLRenderer﹕ Initialized EGL, version 1.4
03-31 02:37:56.914  19607-19631/? D/OpenGLRenderer﹕ Enabling debug mode 0
03-31 02:37:56.923  19607-19631/? W/EGL_emulation﹕ eglSurfaceAttrib not implemented
03-31 02:37:56.924  19607-19631/? W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xb43b2ae0, error=EGL_SUCCESS
03-31 02:37:57.223    1220-1243/system_process I/ActivityManager﹕ Displayed inscope.inscope/.MainActivity: +971ms
03-31 02:37:57.226    1220-1372/system_process W/InputMethodManagerService﹕ Got RemoteException sending setActive(false) notification to pid 19375 uid 10060
03-31 02:38:22.030    1220-2153/system_process I/art﹕ Explicit concurrent mark sweep GC freed 35331(1734KB) AllocSpace objects, 11(173KB) LOS objects, 33% free, 7MB/11MB, paused 1.285ms total 26.801ms
03-31 02:38:22.086   1685-19806/com.google.process.gapps I/GoogleURLConnFactory﹕ binding HttpService
03-31 02:38:22.086   1685-19806/com.google.process.gapps I/GoogleHttpClient﹕ Falling back to old SSLCertificateSocketFactory
03-31 02:38:22.147   1685-19806/com.google.process.gapps W/Uploader﹕ No account for auth token provided
03-31 02:38:22.287   1685-19806/com.google.process.gapps W/Uploader﹕ No account for auth token provided
03-31 02:38:22.404   1685-19806/com.google.process.gapps W/Uploader﹕ no longer exists, so no auth token.
03-31 02:38:22.549   1685-19806/com.google.process.gapps W/Uploader﹕ No account for auth token provided
03-31 02:38:22.643   1685-19806/com.google.process.gapps W/Uploader﹕ No account for auth token provided
03-31 02:38:22.743   1685-19806/com.google.process.gapps W/Uploader﹕ No account for auth token provided
03-31 02:38:22.885    1685-1696/com.google.process.gapps E/StrictMode﹕ A resource was acquired at attached stack trace but never released. See java.io.Closeable for information on avoiding resource leaks.
    java.lang.Throwable: Explicit termination method 'end' not called
            at dalvik.system.CloseGuard.open(CloseGuard.java:184)
            at java.util.zip.Inflater.<init>(Inflater.java:82)
            at com.android.okio.GzipSource.<init>(GzipSource.java:57)
            at com.android.okhttp.internal.http.HttpEngine.initContentStream(HttpEngine.java:490)
            at com.android.okhttp.internal.http.HttpEngine.readResponse(HttpEngine.java:680)
            at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:388)
            at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:332)
            at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:500)
            at com.android.okhttp.internal.http.DelegatingHttpsURLConnection.getResponseCode(DelegatingHttpsURLConnection.java:105)
            at com.android.okhttp.internal.http.HttpsURLConnectionImpl.getResponseCode(HttpsURLConnectionImpl.java:25)
            at com.google.android.gms.http.GoogleHttpClient.a(SourceFile:806)
            at com.google.android.gms.http.GoogleHttpClient.b(SourceFile:770)
            at com.google.android.gms.http.GoogleHttpClient.execute(SourceFile:673)
            at com.google.android.gms.http.GoogleHttpClient.execute(SourceFile:664)
            at com.google.android.gms.playlog.uploader.b.a(SourceFile:332)
            at com.google.android.gms.playlog.uploader.b.a(SourceFile:227)
            at com.google.android.gms.playlog.uploader.b.a(SourceFile:199)
            at com.google.android.gms.playlog.uploader.UploaderService.a(SourceFile:39)
            at com.google.android.gms.gcm.af.run(SourceFile:130)
03-31 02:38:27.903    1685-1696/com.google.process.gapps E/StrictMode﹕ A resource was acquired at attached stack trace but never released. See java.io.Closeable for information on avoiding resource leaks.
    java.lang.Throwable: Explicit termination method 'end' not called
            at dalvik.system.CloseGuard.open(CloseGuard.java:184)
            at java.util.zip.Inflater.<init>(Inflater.java:82)
            at com.android.okio.GzipSource.<init>(GzipSource.java:57)
            at com.android.okhttp.internal.http.HttpEngine.initContentStream(HttpEngine.java:490)
            at com.android.okhttp.internal.http.HttpEngine.readResponse(HttpEngine.java:680)
            at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:388)
            at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:332)
            at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:500)
            at com.android.okhttp.internal.http.DelegatingHttpsURLConnection.getResponseCode(DelegatingHttpsURLConnection.java:105)
            at com.android.okhttp.internal.http.HttpsURLConnectionImpl.getResponseCode(HttpsURLConnectionImpl.java:25)
            at     com.google.android.gms.http.GoogleHttpClient.a(SourceFile:806)
            at com.google.android.gms.http.GoogleHttpClient.b(SourceFile:770)
            at com.google.android.gms.http.GoogleHttpClient.execute(SourceFile:673)
            at com.google.android.gms.http.GoogleHttpClient.execute(SourceFile:664)
            at com.google.android.gms.playlog.uploader.b.a(SourceFile:332)
            at com.google.android.gms.playlog.uploader.b.a(SourceFile:227)
            at com.google.android.gms.playlog.uploader.b.a(SourceFile:199)
            at com.google.android.gms.playlog.uploader.UploaderService.a(SourceFile:39)
            at com.google.android.gms.gcm.af.run(SourceFile:130)
03-31 02:39:22.017    1685-1685/com.google.process.gapps W/GCM﹕ Heartbeat timeout, GCM connection reset
03-31 02:39:22.041    1220-1372/system_process D/ConnectivityService﹕ reportBadNetwork(NetworkAgentInfo [MOBILE (UMTS) - 100]) by 10007
03-31 02:39:22.049    1220-1679/system_process D/NetworkMonitor/NetworkAgentInfo [MOBILE (UMTS) - 100]﹕ ValidatedState{ when=-6ms what=532488 arg1=10007 target=com.android.internal.util.StateMachine$SmHandler }
03-31 02:39:22.049    1220-1679/system_process D/NetworkMonitor/NetworkAgentInfo [MOBILE (UMTS) - 100]﹕ DefaultState{ when=-8ms what=532488 arg1=10007 target=com.android.internal.util.StateMachine$SmHandler }
03-31 02:39:22.049    1220-1679/system_process D/NetworkMonitor/NetworkAgentInfo [MOBILE (UMTS) - 100]﹕ Forcing reevaluation
03-31 02:39:22.050    1220-1679/system_process D/NetworkMonitor/NetworkAgentInfo [MOBILE (UMTS) - 100]﹕ EvaluatingState{ when=-1ms what=532486 arg1=3 target=com.android.internal.util.StateMachine$SmHandler }
03-31 02:39:22.055    1220-1679/system_process D/NetworkMonitor/NetworkAgentInfo [MOBILE (UMTS) - 100]﹕ Checking http://connectivitycheck.android.com/generate_204 on epc.tmobile.com
03-31 02:39:22.087    1220-1679/system_process D/NetworkMonitor/NetworkAgentInfo [MOBILE (UMTS) - 100]﹕ isCaptivePortal: ret=204 headers={null=[HTTP/1.1 204 No Content], Content-Length=[0], Date=[Thu, 31 Mar 2016 06:40:08 GMT], X-Android-Received-Millis=[1459406362087], X-Android-Response-Source=[NETWORK 204], X-Android-Sent-Millis=[1459406362075]}
03-31 02:39:22.087    1220-1679/system_process D/NetworkMonitor/NetworkAgentInfo [MOBILE (UMTS) - 100]﹕ Don't send network conditions - lacking user consent.
03-31 02:39:22.087    1220-1679/system_process D/NetworkMonitor/NetworkAgentInfo [MOBILE (UMTS) - 100]﹕ Validated
03-31 02:39:22.089    1220-1276/system_process D/ConnectivityService﹕ setProvNotificationVisibleIntent: E visible=false networkType=0 extraInfo=null
03-31 02:39:22.090    1220-1276/system_process D/ConnectivityService﹕ Validated NetworkAgentInfo [MOBILE (UMTS) - 100]
03-31 02:39:31.679   1685-20285/com.google.process.gapps D/GCM﹕ Connected
03-31 02:39:31.719   1685-20285/com.google.process.gapps D/GCM﹕ Message class com.google.e.a.a.q
03-31 02:41:04.560  19607-19614/inscope.inscope W/art﹕ Suspending all threads took: 15.170ms
03-31 02:44:00.059    1220-1238/system_process I/ProcessStatsService﹕ Prepared write state in 1ms

Here is my fragment class:

public class Map extends android.support.v4.app.Fragment {
private MapView mapView;

public Map() {
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View layout = inflater.inflate(R.layout.fragment_map, container, false);

    MapView mapView = (MapView) layout.findViewById(R.id.mapview);
    mapView.onCreate(savedInstanceState);
    mapView.getMapAsync(new OnMapReadyCallback() {
        @Override
        public void onMapReady(MapboxMap mapboxMap) {

            // Set map style
            mapboxMap.setStyleUrl(Style.MAPBOX_STREETS);

            // Set the camera's starting position
            CameraPosition cameraPosition = new CameraPosition.Builder()
                    .target(new LatLng(41.885, -87.679)) // set the camera's center position
                    .zoom(12)  // set the camera's zoom level
                    .tilt(20)  // set the camera's tilt
                    .build();

            // Move the camera to that position
            mapboxMap.moveCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

        }

    });
    return layout;
}

Here is the xml:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:mapbox="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="inscope.inscope.Map">

<com.mapbox.mapboxsdk.views.MapView
    android:id="@+id/mapview"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    mapbox:access_token="my Token" />

I have followed the mapbox instructions on their website for gradle and permissions so I'm sure there is nothing wrong with those. It says something is wrong with the "View layout = inflater..." line, except I cant figure out what could be the problem.

Body:
i would like to add a small point to @Tirth Allspark Rami answer.

Mapbox.getInstance(this,access_token)

should come right after

super.onCreate()

before assigning any layout to view.


问:
Why does a function parameter call a constructor with an argument?
I have this code(stolen from cplusplus.com):

```<code>// explicit:
#include <iostream>
using namespace std;

class A {};

class B {
public:
  explicit B (const A& x) {}
  B& operator= (const A& x) {return *this;}
  operator A() {return A();}
};

void fn (B x) {}

int main ()
{
  A foo;
  B bar (foo);
  bar = foo;
  foo = bar;

//  fn (foo);  // not allowed for explicit ctor.
  fn (bar);

  return 0;
}
</code>```

So apparently the statement fn (foo); would call the constructor defined in class B, and I do not really get why. Why would that call a constructor with an argument, I mean aren't things simply copied to the function parameters when not using a reference? If fn (foo); calls the constructor B (const A& x) {}, shouldn't fn (bar); generate an error since there is no constructor defined for an argument of type B, such as B (const B& x) {}?

答:
It's all because of fn()'s signature:

```<code>void fn (B x) {}
</code>```

fn only accepts objects of type B, and passes them by value.

So what happens when calling fn() with an object of type A?

```<code> A foo;
 fn (foo);  // not allowed for explicit ctor.
</code>```

The compiler tries to find the best matching function - a function called fn and receives type A.  (Overload resolution)

Because there is no such function, it then tries to find the next best match by casting the object to a type that fn() accepts.

A conversion constructor would usually do the job :   B (const A& x) {}

But because it's marked with an explicit specifier the compiler can't do it implicitly.

You would have to explicitly cast the object for the compiler to find a match:

```<code>fn ((B)foo);  // Explicit conversion is allowed.
</code>```

Body:
I have this code(stolen from cplusplus.com):

// explicit:
#include <iostream>
using namespace std;

class A {};

class B {
public:
  explicit B (const A& x) {}
  B& operator= (const A& x) {return *this;}
  operator A() {return A();}
};

void fn (B x) {}

int main ()
{
  A foo;
  B bar (foo);
  bar = foo;
  foo = bar;

//  fn (foo);  // not allowed for explicit ctor.
  fn (bar);

  return 0;
}

So apparently the statement fn (foo); would call the constructor defined in class B, and I do not really get why. Why would that call a constructor with an argument, I mean aren't things simply copied to the function parameters when not using a reference? If fn (foo); calls the constructor B (const A& x) {}, shouldn't fn (bar); generate an error since there is no constructor defined for an argument of type B, such as B (const B& x) {}?

Body:
It's all because of fn()'s signature:

void fn (B x) {}

fn only accepts objects of type B, and passes them by value.

So what happens when calling fn() with an object of type A?

 A foo;
 fn (foo);  // not allowed for explicit ctor.

The compiler tries to find the best matching function - a function called fn and receives type A.  (Overload resolution)

Because there is no such function, it then tries to find the next best match by casting the object to a type that fn() accepts.

A conversion constructor would usually do the job :   B (const A& x) {}

But because it's marked with an explicit specifier the compiler can't do it implicitly.

You would have to explicitly cast the object for the compiler to find a match:

fn ((B)foo);  // Explicit conversion is allowed.


问:
How to find the css version?
How do I find the version of CSS that I am using?</p>

答:
Although the CSS specification is defined in several versions (v2, 2.1, 3), the CSS version isn't really relevant to the developer; you need to be more concerned with which web browsers support a given feature.

It is useful to know that a given feature was defined in CSS2, 2.1 or 3 because that can give you an idea of how old the feature is, and therefore how likely it is that browsers will support it -- for example border-radius is a CSS3 feature, so browsers more than a couple of years old may not support it fully.

You can find out what CSS features are supported in which browsers from the following sites:

http://www.quirksmode.org/css/contents.html

http://caniuse.com/

Title: How to find the css version?


问:
How to display a property from a class in a ListBox?
In my class Student I have a property studentName which I want to be displayed on each line of my ListBox.

My ListBox is bound to a List<Students> studentList

How do I display the name of each student in the list onto the ListBox ?

e.g

```<code>foreach(Student s in studentList){
    ListBox.DisplayOnNewLine(s.studentName);
}
</code>```

答:
A Listbox uses the ToString function of the class it has to display to present an element. If you override the function, you can define yourself what you want the Listbox to display. In your Students class, you then can override the function for something like this:

```<code>public override string ToString()
{
    return studentName;
}
</code>```

Body:
In my class Student I have a property studentName which I want to be displayed on each line of my ListBox.

My ListBox is bound to a List<Students> studentList

How do I display the name of each student in the list onto the ListBox ?

e.g

foreach(Student s in studentList){
    ListBox.DisplayOnNewLine(s.studentName);
}

Body:
A Listbox uses the ToString function of the class it has to display to present an element. If you override the function, you can define yourself what you want the Listbox to display. In your Students class, you then can override the function for something like this:

public override string ToString()
{
    return studentName;
}


问:
koa2 template string can not display properly
I am installing coat 2.0 and node 8.0, but when I test following code, it shows
Hello World ${date}, not Hello World 6/7/2017.

const Koa = require('koa');
const app = new Koa();

app.use(ctx => {

```<code>const date = new Date();

ctx.body = 'Hello World ${date}';
</code>```

});

app.listen(3000);

答:
You need to use backticks ` in a template string:</p>

```<code>const Koa = require('koa'); const app = new Koa();

app.use(ctx => {
    const date = new Date();
    ctx.body = `Hello World ${date}`;
});

app.listen(3000);
</code>```

Body:
I am installing coat 2.0 and node 8.0, but when I test following code, it shows
Hello World ${date}, not Hello World 6/7/2017.

const Koa = require('koa');
const app = new Koa();

app.use(ctx => {

const date = new Date();

ctx.body = 'Hello World ${date}';

});

app.listen(3000);

Body:
You need to use backticks ` in a template string:

const Koa = require('koa'); const app = new Koa();

app.use(ctx => {
    const date = new Date();
    ctx.body = `Hello World ${date}`;
});

app.listen(3000);


答:
Overwrite ToString in your class Student:</p>

```<code>public override string ToString()
{
    return this.studentName;
}
</code>```

Title: How to display a property from a class in a ListBox?

Body:
Overwrite ToString in your class Student:

public override string ToString()
{
    return this.studentName;
}


答:
Please add float:left to the rule class.

Your alignment fixed code. Only thing i added is float

```<code>.rule{
    height: 8%;
    line-height: 1%;
    width: 50%;
    background-color: #aaa;
    text-align: center;
    margin-bottom: 5%;
}
</code>```

Title: Div content misalignment

Body:
Please add float:left to the rule class.

Your alignment fixed code. Only thing i added is float

.rule{
    height: 8%;
    line-height: 1%;
    width: 50%;
    background-color: #aaa;
    text-align: center;
    margin-bottom: 5%;
}