问:
SecurityException: opening provider that is not exported from uid
I have an app which is not on Play Store. I was earlier able to start the app installer by the following code:

In Activity:

```<code>Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/app_path/app_name.apk")), "application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.startActivity(intent);
</code>```

Now, I've changed the targetSdkVersion to 25, and made some changes in my code but I'm getting the following error:

FATAL EXCEPTION: AsyncTask #1
      Process: com.android.packageinstaller, PID: 6499
      java.lang.RuntimeException: An error occurred while executing doInBackground()
      at android.os.AsyncTask$3.done(AsyncTask.java:326)
      at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
      at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
      at java.util.concurrent.FutureTask.run(FutureTask.java:242)
      at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:244)
      at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
      at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
      at java.lang.Thread.run(Thread.java:761)
       Caused by: java.lang.SecurityException: Permission Denial: opening provider in.namespace.appname.comp.GenericFileProvider from ProcessRecord{ba35e80 6499:com.android.packageinstaller/u0a17} (pid=6499, uid=10017) that is not exported from uid 10076
      at android.os.Parcel.readException(Parcel.java:1684)
      at android.os.Parcel.readException(Parcel.java:1637)
      at android.app.ActivityManagerProxy.getContentProvider(ActivityManagerNative.java:4213)
      at android.app.ActivityThread.acquireProvider(ActivityThread.java:5535)
      at android.app.ContextImpl$ApplicationContentResolver.acquireUnstableProvider(ContextImpl.java:2239)
      at android.content.ContentResolver.acquireUnstableProvider(ContentResolver.java:1517)
      at android.content.ContentResolver.openTypedAssetFileDescriptor(ContentResolver.java:1131)
      at android.content.ContentResolver.openAssetFileDescriptor(ContentResolver.java:984)
      at android.content.ContentResolver.openInputStream(ContentResolver.java:704)
      at com.android.packageinstaller.PackageInstallerActivity$StagingAsyncTask.doInBackground(PackageInstallerActivity.java:804)
      at com.android.packageinstaller.PackageInstallerActivity$StagingAsyncTask.doInBackground(PackageInstallerActivity.java:795)
      at android.os.AsyncTask$2.call(AsyncTask.java:306)
      at java.util.concurrent.FutureTask.run(FutureTask.java:237)
      at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:244)
      at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
      at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
      at java.lang.Thread.run(Thread.java:761)

These are the changes I've made in my code:

in Manifest:

```<code><permission
    android:name="in.namespace.appname.fp.READ"
    android:description="@string/file_provider_permission_description"
    android:label="in.namespace.appname.READ_FILE"/>

<uses-permission android:name="in.namespace.appname.fp.READ"/>

<application
    ...
    ...
    <provider
        android:name=".comp.GenericFileProvider"
        android:authorities="in.namespace.appname.fileprovider"
        android:exported="false"
        android:grantUriPermissions="true"
        android:readPermission="in.namespace.appname.fp.READ">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/provider_paths"/>
    </provider>
    .
    .
</application>
</code>```

Create an empty class GenericFileProvider in directory comp:

```<code>public class GenericFileProvider extends FileProvider { }
</code>```

Changed the Activity code to:

```<code>File updatedApk = new File(Environment.getExternalStorageDirectory() + "/file_path/appname.apk");
Uri updatedApkUri =  GenericFileProvider.getUriForFile(
     AppUpdateActivity.this,
     "in.namespace.appname.fileprovider",
     updatedApk);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(updatedApkUri, "application/vnd.android.package-archive");

intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.startActivity(intent);
</code>```

What's causing this error and how can I fix this ?

EDIT #1

Changed my manifest:

```<code><provider
        android:name=".comp.GenericFileProvider"
        android:authorities="in.namespace.appname.fileprovider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/provider_paths"/>
    </provider>
</code>```

答:
```<code> Uri updatedApkUri =  GenericFileProvider.getUriForFile(
 AppUpdateActivity.this,
 "in.namespace.appname.fileprovider",
 updatedApk);
</code>```

Please change your code to this

```<code> Uri updatedApkUri =  GenericFileProvider.getUriForFile(
 AppUpdateActivity.this,
 BuildConfig.APPLICATION_ID + ".provider",
 updatedApk);
</code>```

and manage permissions like this

```<code>if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
                } else if (Build.VERSION.SDK_INT >=
Build.VERSION_CODES.JELLY_BEAN) {
                    val clip = ClipData.newUri(contentResolver, "A photo",
mImageCaptureUri)
                    intent.clipData = clip
                    intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
                } else {
                    val resInfoList =
 packageManager.queryIntentActivities(intent,
 PackageManager.MATCH_DEFAULT_ONLY)
                    for (resolveInfo in resInfoList) {
                        val packageName =
 resolveInfo.activityInfo.packageName
                        grantUriPermission(packageName, mImageCaptureUri,
 Intent.FLAG_GRANT_WRITE_URI_PERMISSION or
 Intent.FLAG_GRANT_READ_URI_PERMISSION)
                    }
                }
            }
            intent.putExtra("return-data", true)
</code>```

Body:
I have an app which is not on Play Store. I was earlier able to start the app installer by the following code:

In Activity:

Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/app_path/app_name.apk")), "application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.startActivity(intent);

Now, I've changed the targetSdkVersion to 25, and made some changes in my code but I'm getting the following error:

FATAL EXCEPTION: AsyncTask #1
      Process: com.android.packageinstaller, PID: 6499
      java.lang.RuntimeException: An error occurred while executing doInBackground()
      at android.os.AsyncTask$3.done(AsyncTask.java:326)
      at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
      at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
      at java.util.concurrent.FutureTask.run(FutureTask.java:242)
      at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:244)
      at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
      at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
      at java.lang.Thread.run(Thread.java:761)
       Caused by: java.lang.SecurityException: Permission Denial: opening provider in.namespace.appname.comp.GenericFileProvider from ProcessRecord{ba35e80 6499:com.android.packageinstaller/u0a17} (pid=6499, uid=10017) that is not exported from uid 10076
      at android.os.Parcel.readException(Parcel.java:1684)
      at android.os.Parcel.readException(Parcel.java:1637)
      at android.app.ActivityManagerProxy.getContentProvider(ActivityManagerNative.java:4213)
      at android.app.ActivityThread.acquireProvider(ActivityThread.java:5535)
      at android.app.ContextImpl$ApplicationContentResolver.acquireUnstableProvider(ContextImpl.java:2239)
      at android.content.ContentResolver.acquireUnstableProvider(ContentResolver.java:1517)
      at android.content.ContentResolver.openTypedAssetFileDescriptor(ContentResolver.java:1131)
      at android.content.ContentResolver.openAssetFileDescriptor(ContentResolver.java:984)
      at android.content.ContentResolver.openInputStream(ContentResolver.java:704)
      at com.android.packageinstaller.PackageInstallerActivity$StagingAsyncTask.doInBackground(PackageInstallerActivity.java:804)
      at com.android.packageinstaller.PackageInstallerActivity$StagingAsyncTask.doInBackground(PackageInstallerActivity.java:795)
      at android.os.AsyncTask$2.call(AsyncTask.java:306)
      at java.util.concurrent.FutureTask.run(FutureTask.java:237)
      at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:244)
      at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
      at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
      at java.lang.Thread.run(Thread.java:761)

These are the changes I've made in my code:

in Manifest:

<permission
    android:name="in.namespace.appname.fp.READ"
    android:description="@string/file_provider_permission_description"
    android:label="in.namespace.appname.READ_FILE"/>

<uses-permission android:name="in.namespace.appname.fp.READ"/>

<application
    ...
    ...
    <provider
        android:name=".comp.GenericFileProvider"
        android:authorities="in.namespace.appname.fileprovider"
        android:exported="false"
        android:grantUriPermissions="true"
        android:readPermission="in.namespace.appname.fp.READ">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/provider_paths"/>
    </provider>
    .
    .
</application>

Create an empty class GenericFileProvider in directory comp:

public class GenericFileProvider extends FileProvider { }

Changed the Activity code to:

File updatedApk = new File(Environment.getExternalStorageDirectory() + "/file_path/appname.apk");
Uri updatedApkUri =  GenericFileProvider.getUriForFile(
     AppUpdateActivity.this,
     "in.namespace.appname.fileprovider",
     updatedApk);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(updatedApkUri, "application/vnd.android.package-archive");

intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.startActivity(intent);

What's causing this error and how can I fix this ?

EDIT #1

Changed my manifest:

<provider
        android:name=".comp.GenericFileProvider"
        android:authorities="in.namespace.appname.fileprovider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/provider_paths"/>
    </provider>

Body:
 Uri updatedApkUri =  GenericFileProvider.getUriForFile(
 AppUpdateActivity.this,
 "in.namespace.appname.fileprovider",
 updatedApk);

Please change your code to this

 Uri updatedApkUri =  GenericFileProvider.getUriForFile(
 AppUpdateActivity.this,
 BuildConfig.APPLICATION_ID + ".provider",
 updatedApk);

and manage permissions like this

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
                } else if (Build.VERSION.SDK_INT >=
Build.VERSION_CODES.JELLY_BEAN) {
                    val clip = ClipData.newUri(contentResolver, "A photo",
mImageCaptureUri)
                    intent.clipData = clip
                    intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
                } else {
                    val resInfoList =
 packageManager.queryIntentActivities(intent,
 PackageManager.MATCH_DEFAULT_ONLY)
                    for (resolveInfo in resInfoList) {
                        val packageName =
 resolveInfo.activityInfo.packageName
                        grantUriPermission(packageName, mImageCaptureUri,
 Intent.FLAG_GRANT_WRITE_URI_PERMISSION or
 Intent.FLAG_GRANT_READ_URI_PERMISSION)
                    }
                }
            }
            intent.putExtra("return-data", true)


来源: stackexchange

问:
xmldocument and nested schemas
Using c# and .net 3.5 I'm trying to validate an xml document against a schema that has includes.

The schemas and there includes are as below

Schema1.xsd  -> include another.xsd

another.xsd -> include base.xsd

When i try to add the Schema1.xsd to the XmlDocument i get the following error.

Type 'YesNoType' is not declared or is not a simple type.

I believe i'm getting this error because the base.xsd file is not being included when i load the Schema1.xsd schema.

I'm trying to use the XmlSchemaSet class and I'm setting the XmlResolver uri to the location of the schemas.

NOTE : All schemas live under the same directory E:\Dev\Main\XmlSchemas

Here is the code

```<code>string schemaPath = "E:\\Dev\\Main\\XmlSchemas";

XmlDocument xmlDocSchema = new XmlDocument();

XmlSchemaSet s = new XmlSchemaSet();

XmlUrlResolver resolver = new XmlUrlResolver();

Uri baseUri = new Uri(schemaPath);

resolver.ResolveUri(null, schemaPath);

s.XmlResolver = resolver;

s.Add(null, XmlReader.Create(new System.IO.StreamReader(schemaPath + "\\Schema1.xsd"), new XmlReaderSettings { ValidationType = ValidationType.Schema, XmlResolver = resolver }, new Uri(schemaPath).ToString()));

xmlDocSchema.Schemas.Add(s);

ValidationEventHandler valEventHandler = new ValidationEventHandler
(ValidateNinoDobEvent);

try
{
xmlDocSchema.LoadXml(xml);
xmlDocSchema.Validate(valEventHandler);
}
catch (XmlSchemaValidationException xmlValidationError)
{
// need to interogate the Validation Exception, for possible further
// processing.
string message = xmlValidationError.Message;
return false;
}
</code>```

Can anyone point me in the right direction regarding validating an xmldocument against a schema with nested includes.

答:
I also have a nested schema case and I don't find any error in validating.My code looks like follwoing.</p>

```<code>private string strLogger = null;
    public bool ValidateXml(string path2XMLFile, string path2XSDFile)
    {
        bool isValidFile = false;
        try
        {
            XmlReaderSettings settings = new XmlReaderSettings();
            settings.ValidationType = ValidationType.Schema;
            settings.Schemas.Add(null, path2XSDFile);
            settings.ValidationEventHandler += new ValidationEventHandler(settings_ValidationEventHandler);
            XmlReader reader = XmlReader.Create(path2XMLFile, settings);
            while (reader.Read()) ;
            if (String.IsNullOrEmpty(strLogger))
            {
                isValidFile = true;
            }
        }
        catch (Exception ex)
        {
            LoggingHandler.Log(ex);
        }
        return isValidFile;
    }
    private void settings_ValidationEventHandler(object sender, ValidationEventArgs e)
    {
        strLogger += System.Environment.NewLine + "Validation Error Message  = [" + e.Message + "], " + "Validation Error Severity = [" + e.Severity + "], " + System.Environment.NewLine;
    }
</code>```

ContentLicense: CC BY-SA 2.5

Title: xmldocument and nested schemas

Body:
Using c# and .net 3.5 I'm trying to validate an xml document against a schema that has includes.

The schemas and there includes are as below

Schema1.xsd  -> include another.xsd

another.xsd -> include base.xsd

When i try to add the Schema1.xsd to the XmlDocument i get the following error.

Type 'YesNoType' is not declared or is not a simple type.

I believe i'm getting this error because the base.xsd file is not being included when i load the Schema1.xsd schema.

I'm trying to use the XmlSchemaSet class and I'm setting the XmlResolver uri to the location of the schemas.

NOTE : All schemas live under the same directory E:\Dev\Main\XmlSchemas

Here is the code

string schemaPath = "E:\\Dev\\Main\\XmlSchemas";

XmlDocument xmlDocSchema = new XmlDocument();

XmlSchemaSet s = new XmlSchemaSet();

XmlUrlResolver resolver = new XmlUrlResolver();

Uri baseUri = new Uri(schemaPath);

resolver.ResolveUri(null, schemaPath);

s.XmlResolver = resolver;

s.Add(null, XmlReader.Create(new System.IO.StreamReader(schemaPath + "\\Schema1.xsd"), new XmlReaderSettings { ValidationType = ValidationType.Schema, XmlResolver = resolver }, new Uri(schemaPath).ToString()));

xmlDocSchema.Schemas.Add(s);

ValidationEventHandler valEventHandler = new ValidationEventHandler
(ValidateNinoDobEvent);

try
{
xmlDocSchema.LoadXml(xml);
xmlDocSchema.Validate(valEventHandler);
}
catch (XmlSchemaValidationException xmlValidationError)
{
// need to interogate the Validation Exception, for possible further
// processing.
string message = xmlValidationError.Message;
return false;
}

Can anyone point me in the right direction regarding validating an xmldocument against a schema with nested includes.

Body:
I also have a nested schema case and I don't find any error in validating.My code looks like follwoing.

private string strLogger = null;
    public bool ValidateXml(string path2XMLFile, string path2XSDFile)
    {
        bool isValidFile = false;
        try
        {
            XmlReaderSettings settings = new XmlReaderSettings();
            settings.ValidationType = ValidationType.Schema;
            settings.Schemas.Add(null, path2XSDFile);
            settings.ValidationEventHandler += new ValidationEventHandler(settings_ValidationEventHandler);
            XmlReader reader = XmlReader.Create(path2XMLFile, settings);
            while (reader.Read()) ;
            if (String.IsNullOrEmpty(strLogger))
            {
                isValidFile = true;
            }
        }
        catch (Exception ex)
        {
            LoggingHandler.Log(ex);
        }
        return isValidFile;
    }
    private void settings_ValidationEventHandler(object sender, ValidationEventArgs e)
    {
        strLogger += System.Environment.NewLine + "Validation Error Message  = [" + e.Message + "], " + "Validation Error Severity = [" + e.Severity + "], " + System.Environment.NewLine;
    }


问:
How to send textbox value and item ID from view to controller razorview
How do I send the current item ID and textbox value to the controller after clicking submit button.

```<code>@model propertyMgmt.Models.Property
  <div class="container" id="tourpackages-carousel">
    <div class="panel panel-default" style="width:inherit">
      <div class="panel-heading">
        <h4 style="font-family:Tahoma, Geneva, sans-serif;margin-left:-5px;">
        <strong>@Model.PropertyDescription</strong></h4>
      </div>
      <div class="panel-body">
        <div class="row">
          <div class="col-md-6">
            <div>
              <img src="~/Image/@Model.PropertyImage" alt="" style="width:100%;height:300px">
            </div>
          </div>
          <div class="col-md-6" style="margin-left:-8px;margin-top:-20px;">
            <div style="background-color:#d9dadd">
              <h3 style="margin-left:16px;">
              <u>Property Details</u></h3>
            <dl class="dl-horizontal">
              <dt>Total Investment:</dt>
              <dd>@Model.InvestmentAmount</dd>
              <dt>Remaining Investment:</dt>
              <dd>@Model.RemainingInvestmentAmount</dd>
              <dt>Property Discription:</dt>
              <dd>@Model.PropertyDescription</dd>
              <dt>Property Cost:</dt>
              <dd>@Model.PropertyCost</dd>
              <dt>Country:</dt>
              <dd>@Model.Country</dd>
              <dt>City:</dt>
              <dd>@Model.City</dd>
            </dl>

            @using (Html.BeginForm("AddInvestment","Home",FormMethod.Post))
            {
            <input type="number" id="investmentAmount" name="investmentAmount" /><br />
            <input type="submit" value="Submit" />
            }
          </ div >
        </ div >
      </ div >
    </ div >
</ div >
</ div >
</code>```

The following is the controller with the parameters needed.

```<code>[HttpPost]
[Route("AddInvestment/{id}/{amount}")]
public ActionResult AddInvestment(int propertyId, double investmentAmount)
{
    Investment investment = new Investment();
    investment.PropertyId = propertyId;
    investment.InvestorId = Convert.ToInt32(Session["UserId"]);
    investment.InvestmentAmount = investmentAmount;
    _investmentQueryProcessor.AddInvestment(investment);
    RemainingInvestment(propertyId, investmentAmount);
    RemainingInvestorBalance(investment.InvestorId, investmentAmount);
    return View();
}
</code>```

I want to understand how I can pass the item Id and textbox value for above parameters using helper tags. I am also not sure about the @using Html.BeginForm() in the middle. Any help would be appreciated.

答:
When you submit the form (as your code shows), the data gets submitted as key-value pairs (name:value). This is done using the name attribute of the input controls. If you need to track the id, then you will need to put the id in its own "key-value pair" (in this case, a separate input control). Something like this:

```<code>        @using (Html.BeginForm("AddInvestment","Home",FormMethod.Post))
        {
            <input type="number" id="investmentAmount" name="investmentAmount" /><br />
            <input type="hidden" id="propertyId" name="propertyId" value="@Model.PropertyId" /><br />
            <input type="submit" value="Submit" />
        }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
How do I send the current item ID and textbox value to the controller after clicking submit button.

@model propertyMgmt.Models.Property

        @Model.PropertyDescription

              Property Details

Total Investment:

@Model.InvestmentAmount

Remaining Investment:

@Model.RemainingInvestmentAmount

Property Discription:

@Model.PropertyDescription

Property Cost:

@Model.PropertyCost

Country:

@Model.Country

City:

@Model.City

            @using (Html.BeginForm("AddInvestment","Home",FormMethod.Post))
            {
            <input type="number" id="investmentAmount" name="investmentAmount" />

            <input type="submit" value="Submit" />
            }

The following is the controller with the parameters needed.

[HttpPost]
[Route("AddInvestment/{id}/{amount}")]
public ActionResult AddInvestment(int propertyId, double investmentAmount)
{
    Investment investment = new Investment();
    investment.PropertyId = propertyId;
    investment.InvestorId = Convert.ToInt32(Session["UserId"]);
    investment.InvestmentAmount = investmentAmount;
    _investmentQueryProcessor.AddInvestment(investment);
    RemainingInvestment(propertyId, investmentAmount);
    RemainingInvestorBalance(investment.InvestorId, investmentAmount);
    return View();
}

I want to understand how I can pass the item Id and textbox value for above parameters using helper tags. I am also not sure about the @using Html.BeginForm() in the middle. Any help would be appreciated.

Body:
When you submit the form (as your code shows), the data gets submitted as key-value pairs (name:value). This is done using the name attribute of the input controls. If you need to track the id, then you will need to put the id in its own "key-value pair" (in this case, a separate input control). Something like this:

        @using (Html.BeginForm("AddInvestment","Home",FormMethod.Post))
        {
            <input type="number" id="investmentAmount" name="investmentAmount" /><br />
            <input type="hidden" id="propertyId" name="propertyId" value="@Model.PropertyId" /><br />
            <input type="submit" value="Submit" />
        }

ContentLicense: CC BY-SA 3.0


问:
Eclipse ctrl+right does nothing
I'm editing a Java source in Eclipse (Version: Kepler Release). I'm used no navigate text on other editors using Ctrl+Right to move to the next word and Ctrl+Shift+Right to select the next word. But on eclipse nothing happens, the cursor stays in the same place.

On Window->Preferences->General->keys the binding seems to be correct, it says:
Command: Next Word; Binding: Ctrl+Right; When: Editing Text; Category: Text Editing.

But it's not working.

答:
I've got the same problem with Eclipse-Oxygen and disabling the welcome screen fixed the issue. I gave this answer just to confirm the solutions explained above also work for the following eclipse version;

1:  Eclipse-Oxygen Version: Oxygen.1a Release (4.7.1a) (released on October 2017)

2: Version: Oxygen.3a Release (4.7.3a) Build id: 20180405-1200

Title: Eclipse ctrl+right does nothing


问:
Change Brightness using WMI
I have tried this Windows example Getting WMI Data from a Remote Computer and this other Calling a Provider Method, and both work correctly in my computer. However I have tried to use WMI to change the brightness and I am getting an error on step 6, in this part:

```<code>    //Get the Next Object from the collection
    hres = pEnum->Next(WBEM_INFINITE, //Timeout
    1, //No of objects requested
    &pObj, //Returned Object
    &ulReturned /*No of object returned*/);
</code>```

pEnum is a negative value.

IMPORTANT: While I was writing this question, I tried with different computers and I get errors in all of them, except when I use a laptop. Therefore, how can I change the brightness of a monitor?

I also realize that if I go to wbemtest.exe, in all my computers the class WmiMonitorBrightnessMethods and the method WmiSetBrightness exist, but only in the laptop there is an instance of it. In fact, in the computers when I click on view objects of the class I get this message (see image)

This is my code:

```<code>#define _WIN32_DCOM

#include <iostream>
using namespace std;
#include <comdef.h>
#include <Wbemidl.h>

#pragma comment(lib, "wbemuuid.lib")

int main(int iArgCnt, char ** argv)
{
    HRESULT hres;

    // Step 1: --------------------------------------------------
    // Initialize COM. ------------------------------------------

    hres =  CoInitializeEx(0, COINIT_MULTITHREADED);
    if (FAILED(hres))
    {
        cout << "Failed to initialize COM library. Error code = 0x"
             << hex << hres << endl;
        return 1;                  // Program has failed.
    }

    // Step 2: --------------------------------------------------
    // Set general COM security levels --------------------------

    hres =  CoInitializeSecurity(
        NULL,
        -1,                          // COM negotiates service
        NULL,                        // Authentication services
        NULL,                        // Reserved
        RPC_C_AUTHN_LEVEL_DEFAULT,   // Default authentication
        RPC_C_IMP_LEVEL_IMPERSONATE, // Default Impersonation
        NULL,                        // Authentication info
        EOAC_NONE,                   // Additional capabilities
        NULL                         // Reserved
        );

    if (FAILED(hres))
    {
        cout << "Failed to initialize security. Error code = 0x"
             << hex << hres << endl;
        CoUninitialize();
        return 1;                      // Program has failed.
    }

    // Step 3: ---------------------------------------------------
    // Obtain the initial locator to WMI -------------------------

    IWbemLocator *pLoc = NULL;

    hres = CoCreateInstance(
        CLSID_WbemLocator,
        0,
        CLSCTX_INPROC_SERVER,
        IID_IWbemLocator, (LPVOID *) &pLoc);

    if (FAILED(hres))
    {
        cout << "Failed to create IWbemLocator object. "
             << "Err code = 0x"
             << hex << hres << endl;
        CoUninitialize();
        return 1;                 // Program has failed.
    }

    // Step 4: ---------------------------------------------------
    // Connect to WMI through the IWbemLocator::ConnectServer method

    IWbemServices *pSvc = NULL;

    // Connect to the local root\wminamespace
    // and obtain pointer pSvc to make IWbemServices calls.
    hres = pLoc->ConnectServer(
        _bstr_t(L"ROOT\\WMI"),
        NULL,
        NULL,
        0,
        NULL,
        0,
        0,
        &pSvc
    );

    if (FAILED(hres))
    {
        cout << "Could not connect. Error code = 0x"
             << hex << hres << endl;
        pLoc->Release();
        CoUninitialize();
        return 1;                // Program has failed.
    }

    cout << "Connected to ROOT\\WMI namespace" << endl;

    // Step 5: --------------------------------------------------
    // Set security levels for the proxy ------------------------

    hres = CoSetProxyBlanket(
        pSvc,                        // Indicates the proxy to set
        RPC_C_AUTHN_WINNT,           // RPC_C_AUTHN_xxx
        RPC_C_AUTHZ_NONE,            // RPC_C_AUTHZ_xxx
        NULL,                        // Server principal name
        RPC_C_AUTHN_LEVEL_CALL,      // RPC_C_AUTHN_LEVEL_xxx
        RPC_C_IMP_LEVEL_IMPERSONATE, // RPC_C_IMP_LEVEL_xxx
        NULL,                        // client identity
        EOAC_NONE                    // proxy capabilities
    );

    if (FAILED(hres))
    {
        cout << "Could not set proxy blanket. Error code = 0x"
             << hex << hres << endl;
        pSvc->Release();
        pLoc->Release();
        CoUninitialize();
        return 1;               // Program has failed.
    }

    // Step 6: --------------------------------------------------
    // Call WmiSetBrightness method -----------------------------

    // set up to call the Win32_Process::Create method
    BSTR ClassName = SysAllocString(L"WmiMonitorBrightnessMethods");
    BSTR MethodName = SysAllocString(L"WmiSetBrightness");
    BSTR bstrQuery = SysAllocString(L"Select * from WmiMonitorBrightnessMethods");
    IEnumWbemClassObject *pEnum = NULL;

    hres = pSvc->ExecQuery(_bstr_t(L"WQL"), //Query Language
    bstrQuery, //Query to Execute
    WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY, //Make a semi-synchronous call
    NULL, //Context
    &pEnum /*Enumeration Interface*/);

    hres = WBEM_S_NO_ERROR;

    ULONG ulReturned;
    IWbemClassObject *pObj;
    DWORD retVal = 0;

    //Get the Next Object from the collection
    hres = pEnum->Next(WBEM_INFINITE, //Timeout
    1, //No of objects requested
    &pObj, //Returned Object
    &ulReturned /*No of object returned*/);

    IWbemClassObject* pClass = NULL;
    hres = pSvc->GetObject(ClassName, 0, NULL, &pClass, NULL);

    IWbemClassObject* pInParamsDefinition = NULL;
    hres = pClass->GetMethod(MethodName, 0, &pInParamsDefinition, NULL);

    IWbemClassObject* pClassInstance = NULL;
    hres = pInParamsDefinition->SpawnInstance(0, &pClassInstance);

    VARIANT var1;
    VariantInit(&var1);
    BSTR ArgName0 = SysAllocString(L"Timeout");

    V_VT(&var1) = VT_BSTR;
    V_BSTR(&var1) = SysAllocString(L"0");
    hres = pClassInstance->Put(ArgName0,
        0,
        &var1,
        CIM_UINT32); //CIM_UINT64
    VariantClear(&var1);

    VARIANT var;
    VariantInit(&var);
    BSTR ArgName1 = SysAllocString(L"Brightness");

    V_VT(&var2) = VT_BSTR;
    V_BSTR(&var2) = SysAllocString(L"80"); //Brightness value
    hres = pClassInstance->Put(ArgName1,
        0,
        &var2,
        CIM_UINT8);
    VariantClear(&var2);

    // Call the method
    VARIANT pathVariable;
    VariantInit(&pathVariable);

    hres = pSvc->ExecMethod(pathVariable.bstrVal,
        MethodName,
        0,
        NULL,
        pClassInstance,
        NULL,
        NULL);
    VariantClear(&pathVariable);

    return 0;
}
</code>```

答:
It is mostly because your PC does not support brightness controls via a software. For example in laptops there are hotkeys that can be used to control the brightness, if that exists that you will get an instance and make use of it via WMI.

To be sure, you can run below mentioned command in powershell. If it returns Not supported then you can not use WMI for these controls.

```<code>Get-CimInstance -Namespace root/WMI -ClassName WmiMonitorBrightnessMethods
</code>```

Note : Hotkeys work via another softwares like Mobility Center etc.

Title: Change Brightness using WMI

Body:
I have tried this Windows example Getting WMI Data from a Remote Computer and this other Calling a Provider Method, and both work correctly in my computer. However I have tried to use WMI to change the brightness and I am getting an error on step 6, in this part:

    //Get the Next Object from the collection
    hres = pEnum->Next(WBEM_INFINITE, //Timeout
    1, //No of objects requested
    &pObj, //Returned Object
    &ulReturned /*No of object returned*/);

pEnum is a negative value.

IMPORTANT: While I was writing this question, I tried with different computers and I get errors in all of them, except when I use a laptop. Therefore, how can I change the brightness of a monitor?

I also realize that if I go to wbemtest.exe, in all my computers the class WmiMonitorBrightnessMethods and the method WmiSetBrightness exist, but only in the laptop there is an instance of it. In fact, in the computers when I click on view objects of the class I get this message (see image)

This is my code:

#define _WIN32_DCOM

#include <iostream>
using namespace std;
#include <comdef.h>
#include <Wbemidl.h>

#pragma comment(lib, "wbemuuid.lib")

int main(int iArgCnt, char ** argv)
{
    HRESULT hres;

    // Step 1: --------------------------------------------------
    // Initialize COM. ------------------------------------------

    hres =  CoInitializeEx(0, COINIT_MULTITHREADED);
    if (FAILED(hres))
    {
        cout << "Failed to initialize COM library. Error code = 0x"
             << hex << hres << endl;
        return 1;                  // Program has failed.
    }

    // Step 2: --------------------------------------------------
    // Set general COM security levels --------------------------

    hres =  CoInitializeSecurity(
        NULL,
        -1,                          // COM negotiates service
        NULL,                        // Authentication services
        NULL,                        // Reserved
        RPC_C_AUTHN_LEVEL_DEFAULT,   // Default authentication
        RPC_C_IMP_LEVEL_IMPERSONATE, // Default Impersonation
        NULL,                        // Authentication info
        EOAC_NONE,                   // Additional capabilities
        NULL                         // Reserved
        );

    if (FAILED(hres))
    {
        cout << "Failed to initialize security. Error code = 0x"
             << hex << hres << endl;
        CoUninitialize();
        return 1;                      // Program has failed.
    }

    // Step 3: ---------------------------------------------------
    // Obtain the initial locator to WMI -------------------------

    IWbemLocator *pLoc = NULL;

    hres = CoCreateInstance(
        CLSID_WbemLocator,
        0,
        CLSCTX_INPROC_SERVER,
        IID_IWbemLocator, (LPVOID *) &pLoc);

    if (FAILED(hres))
    {
        cout << "Failed to create IWbemLocator object. "
             << "Err code = 0x"
             << hex << hres << endl;
        CoUninitialize();
        return 1;                 // Program has failed.
    }

    // Step 4: ---------------------------------------------------
    // Connect to WMI through the IWbemLocator::ConnectServer method

    IWbemServices *pSvc = NULL;

    // Connect to the local root\wminamespace
    // and obtain pointer pSvc to make IWbemServices calls.
    hres = pLoc->ConnectServer(
        _bstr_t(L"ROOT\\WMI"),
        NULL,
        NULL,
        0,
        NULL,
        0,
        0,
        &pSvc
    );

    if (FAILED(hres))
    {
        cout << "Could not connect. Error code = 0x"
             << hex << hres << endl;
        pLoc->Release();
        CoUninitialize();
        return 1;                // Program has failed.
    }

    cout << "Connected to ROOT\\WMI namespace" << endl;

    // Step 5: --------------------------------------------------
    // Set security levels for the proxy ------------------------

    hres = CoSetProxyBlanket(
        pSvc,                        // Indicates the proxy to set
        RPC_C_AUTHN_WINNT,           // RPC_C_AUTHN_xxx
        RPC_C_AUTHZ_NONE,            // RPC_C_AUTHZ_xxx
        NULL,                        // Server principal name
        RPC_C_AUTHN_LEVEL_CALL,      // RPC_C_AUTHN_LEVEL_xxx
        RPC_C_IMP_LEVEL_IMPERSONATE, // RPC_C_IMP_LEVEL_xxx
        NULL,                        // client identity
        EOAC_NONE                    // proxy capabilities
    );

    if (FAILED(hres))
    {
        cout << "Could not set proxy blanket. Error code = 0x"
             << hex << hres << endl;
        pSvc->Release();
        pLoc->Release();
        CoUninitialize();
        return 1;               // Program has failed.
    }

    // Step 6: --------------------------------------------------
    // Call WmiSetBrightness method -----------------------------

    // set up to call the Win32_Process::Create method
    BSTR ClassName = SysAllocString(L"WmiMonitorBrightnessMethods");
    BSTR MethodName = SysAllocString(L"WmiSetBrightness");
    BSTR bstrQuery = SysAllocString(L"Select * from WmiMonitorBrightnessMethods");
    IEnumWbemClassObject *pEnum = NULL;

    hres = pSvc->ExecQuery(_bstr_t(L"WQL"), //Query Language
    bstrQuery, //Query to Execute
    WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY, //Make a semi-synchronous call
    NULL, //Context
    &pEnum /*Enumeration Interface*/);

    hres = WBEM_S_NO_ERROR;

    ULONG ulReturned;
    IWbemClassObject *pObj;
    DWORD retVal = 0;

    //Get the Next Object from the collection
    hres = pEnum->Next(WBEM_INFINITE, //Timeout
    1, //No of objects requested
    &pObj, //Returned Object
    &ulReturned /*No of object returned*/);

    IWbemClassObject* pClass = NULL;
    hres = pSvc->GetObject(ClassName, 0, NULL, &pClass, NULL);

    IWbemClassObject* pInParamsDefinition = NULL;
    hres = pClass->GetMethod(MethodName, 0, &pInParamsDefinition, NULL);

    IWbemClassObject* pClassInstance = NULL;
    hres = pInParamsDefinition->SpawnInstance(0, &pClassInstance);

    VARIANT var1;
    VariantInit(&var1);
    BSTR ArgName0 = SysAllocString(L"Timeout");

    V_VT(&var1) = VT_BSTR;
    V_BSTR(&var1) = SysAllocString(L"0");
    hres = pClassInstance->Put(ArgName0,
        0,
        &var1,
        CIM_UINT32); //CIM_UINT64
    VariantClear(&var1);

    VARIANT var;
    VariantInit(&var);
    BSTR ArgName1 = SysAllocString(L"Brightness");

    V_VT(&var2) = VT_BSTR;
    V_BSTR(&var2) = SysAllocString(L"80"); //Brightness value
    hres = pClassInstance->Put(ArgName1,
        0,
        &var2,
        CIM_UINT8);
    VariantClear(&var2);

    // Call the method
    VARIANT pathVariable;
    VariantInit(&pathVariable);

    hres = pSvc->ExecMethod(pathVariable.bstrVal,
        MethodName,
        0,
        NULL,
        pClassInstance,
        NULL,
        NULL);
    VariantClear(&pathVariable);

    return 0;
}

Body:
It is mostly because your PC does not support brightness controls via a software. For example in laptops there are hotkeys that can be used to control the brightness, if that exists that you will get an instance and make use of it via WMI.

To be sure, you can run below mentioned command in powershell. If it returns Not supported then you can not use WMI for these controls.

Get-CimInstance -Namespace root/WMI -ClassName WmiMonitorBrightnessMethods

Note : Hotkeys work via another softwares like Mobility Center etc.


问:
How to connect Angular JS with spring mvc using $http service to get data from controller to jsp
```<code>    My Controller:
</code>```

How to get values from spring MVC to Angular js  to display in jsp page.
    Below i posted my spring MVC and Angular js config code.Please some one help
    how to grt values from Spring controller.how to get url path of our
    controller.

```<code>    package com.dineshonjava.controller;

    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;

    import org.hibernate.SessionFactory;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.validation.BindingResult;
    import org.springframework.web.bind.annotation.ModelAttribute;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.servlet.ModelAndView;

    import com.dineshonjava.bean.EmployeeBean;
    import com.dineshonjava.model.Employee;
    import com.dineshonjava.service.EmployeeService;

    @Controller
    public class EmployeeController {

        @Autowired
        private EmployeeService employeeService;

        @RequestMapping(value = "/search", method = RequestMethod.GET)
        public Map<String, Object> search(@ModelAttribute("command")  EmployeeBean employeeBean,
                BindingResult result) {

            Map<String, Object> model = new HashMap<String, Object>();
            model.put("employees",  prepareListofBean(employeeService.listEmployeess()));

            return (model);
        }

        private List<EmployeeBean> prepareListofBean(List<Employee> employees){
            List<EmployeeBean> beans = null;
            if(employees != null && !employees.isEmpty()){
                beans = new ArrayList<EmployeeBean>();
                EmployeeBean bean = null;
                for(Employee employee : employees){
                    bean = new EmployeeBean();
                    bean.setName(employee.getEmpName());
                    bean.setId(employee.getEmpId());
                    bean.setAddress(employee.getEmpAddress());
                    bean.setSalary(employee.getSalary());
                    bean.setAge(employee.getEmpAge());
                    bean.setBloodgrp(employee.getBloodgrp());
                    bean.setAids(employee.getAids());
                    bean.setWeight(employee.getWeight());
                    bean.setPass(employee.getPass());
                    beans.add(bean);
                }
            }
            return beans;
        }

    }

    Angular js page:
</code>```

This is my angular js page here i try to get data's from Spring mvc controller but it fails . please explain how to get data from spring MVC .im new to angular js and spring mvc this is my task im fresher .

```<code><html>
<head>
<script>
    var app = angular.module('angularjsTable', ['angularUtils.directives.dirPagination']);
     app.controller('listitemdata',function($scope, $http){
         $scope.employees = [];
         $http.get("http://localhost:8080/sdnext/search").success(function(response){
             $scope.employees = response;
});
});
</script>
</head>
<tbody>
<tr dir-paginate="employee in employees">

<td>{{employee.id}}</td>
<td>{{employee.name}}</td>
<td>{{employee.age}}</td>
<td>{{employee.salary}}</td>
<td>{{employee.address}}</td>
<td>{{employee.bloodgrp}}</td>
<td>{{employee.aids}}</td>
<td>{{employee.weight}}</td>
</tr>
</tbody>

</html>
</code>```

答:
Dont use any model just send data In response and convert List Of DTO Object in json

```<code> @RequestMapping(value = "/search", method = RequestMethod.GET)
      public void  search(HttpServletResponse res,HttpServletRequest req) {

      List<EmployeeBean> data =  employeeService.listEmployeess();
        JSONArray array = new JSONArray();
            for (EmployeeBean e : data) {
                JSONObject jsonObject = new JSONObject(e);
                array.put(jsonObject);
            }
         response.getWriter().append(array.toString());
        }
</code>```

in pom.xml for jsonObject

```<code> <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20160810</version>
        </dependency>
</code>```

Body:
    My Controller:

How to get values from spring MVC to Angular js  to display in jsp page.
    Below i posted my spring MVC and Angular js config code.Please some one help
    how to grt values from Spring controller.how to get url path of our
    controller.

    package com.dineshonjava.controller;

    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;

    import org.hibernate.SessionFactory;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.validation.BindingResult;
    import org.springframework.web.bind.annotation.ModelAttribute;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.servlet.ModelAndView;

    import com.dineshonjava.bean.EmployeeBean;
    import com.dineshonjava.model.Employee;
    import com.dineshonjava.service.EmployeeService;

    @Controller
    public class EmployeeController {

        @Autowired
        private EmployeeService employeeService;

        @RequestMapping(value = "/search", method = RequestMethod.GET)
        public Map<String, Object> search(@ModelAttribute("command")  EmployeeBean employeeBean,
                BindingResult result) {

            Map<String, Object> model = new HashMap<String, Object>();
            model.put("employees",  prepareListofBean(employeeService.listEmployeess()));

            return (model);
        }

        private List<EmployeeBean> prepareListofBean(List<Employee> employees){
            List<EmployeeBean> beans = null;
            if(employees != null && !employees.isEmpty()){
                beans = new ArrayList<EmployeeBean>();
                EmployeeBean bean = null;
                for(Employee employee : employees){
                    bean = new EmployeeBean();
                    bean.setName(employee.getEmpName());
                    bean.setId(employee.getEmpId());
                    bean.setAddress(employee.getEmpAddress());
                    bean.setSalary(employee.getSalary());
                    bean.setAge(employee.getEmpAge());
                    bean.setBloodgrp(employee.getBloodgrp());
                    bean.setAids(employee.getAids());
                    bean.setWeight(employee.getWeight());
                    bean.setPass(employee.getPass());
                    beans.add(bean);
                }
            }
            return beans;
        }

    }

    Angular js page:

This is my angular js page here i try to get data's from Spring mvc controller but it fails . please explain how to get data from spring MVC .im new to angular js and spring mvc this is my task im fresher .

{{employee.id}}
{{employee.name}}
{{employee.age}}
{{employee.salary}}
{{employee.address}}
{{employee.bloodgrp}}
{{employee.aids}}
{{employee.weight}}

Body:
Dont use any model just send data In response and convert List Of DTO Object in json

 @RequestMapping(value = "/search", method = RequestMethod.GET)
      public void  search(HttpServletResponse res,HttpServletRequest req) {

      List<EmployeeBean> data =  employeeService.listEmployeess();
        JSONArray array = new JSONArray();
            for (EmployeeBean e : data) {
                JSONObject jsonObject = new JSONObject(e);
                array.put(jsonObject);
            }
         response.getWriter().append(array.toString());
        }

in pom.xml for jsonObject

 <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20160810</version>
        </dependency>


问:
Placing UiView as a subview programmatically
I have ViewController that looks like this. There is parent ScrollView that holds UIView (wrapperView) and this wrapper view has TextView and ImageView inside.
This simple structure is created form interface builder with all constraints needed so it works fine.

In some cases I need to programmatically add one more UIView inside my wrapperView right under ImageView (green arrow points there).

So I created xib file for my new UIView and separate class for it

```<code>class MyView : UIView {
    class func instanceFromNib() -> UIView {
        return UINib(nibName: "MyView", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! UIView
    }
}
</code>```

And I code of my ViewController I added

```<code>let myView = MyView.instanceFromNib()
myView = CGRect(x: 0, y: 0, width: 300, height: 80)
wrapperView.addSubview(myView)
</code>```

now i see myView on the screen in top of wrapperView but when i try to apply constraints like

```<code>NSLayoutConstraint(item: myView, attribute: .top, relatedBy: .equal, toItem: myImageView, attribute: .bottom, multiplier: 1.0, constant: 8).isActive = true
</code>```

I got

Unable to simultaneously satisfy constraints

What am I doing wrong?

答: You may use the Debug View Hierarchy to debug your UI issues including the constraints which are failing to be satisfied. Most probably your .top constraint which is added at runtime is conflicting with .top constraint which you have set in your storyboard.

Body:
I have ViewController that looks like this. There is parent ScrollView that holds UIView (wrapperView) and this wrapper view has TextView and ImageView inside.
This simple structure is created form interface builder with all constraints needed so it works fine.

In some cases I need to programmatically add one more UIView inside my wrapperView right under ImageView (green arrow points there).

So I created xib file for my new UIView and separate class for it

class MyView : UIView {
    class func instanceFromNib() -> UIView {
        return UINib(nibName: "MyView", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! UIView
    }
}

And I code of my ViewController I added

let myView = MyView.instanceFromNib()
myView = CGRect(x: 0, y: 0, width: 300, height: 80)
wrapperView.addSubview(myView)

now i see myView on the screen in top of wrapperView but when i try to apply constraints like

NSLayoutConstraint(item: myView, attribute: .top, relatedBy: .equal, toItem: myImageView, attribute: .bottom, multiplier: 1.0, constant: 8).isActive = true

I got

Unable to simultaneously satisfy constraints

What am I doing wrong?


问:
C++11-style [[unused]] attribute in gcc?
Under gcc/g++ 4.9 I can write:

```<code>int x __attribute__((unused)) = f();
</code>```

to indicate that x is intentionally unused.

Is it possible to do this with the C++11 [[]] attribute notation somehow?

I tried:

```<code>int x [[unused]] = f();
</code>```

but it doesn't work.

(Yes, I know it is an implementation-defined attribute.)

答:
There is [[maybe_unused]] attribute in C++17. It's implemented in GCC 7, see C++ Standards Support in GCC .

Example from P0212R1 proposal:

```<code>[[maybe_unused]] void f([[maybe_unused]] bool thing1,
                        [[maybe_unused]] bool thing2) {
    [[maybe_unused]] bool b = thing1 && thing2;
    assert(b);
}
</code>```

Body:
Under gcc/g++ 4.9 I can write:

int x __attribute__((unused)) = f();

to indicate that x is intentionally unused.

Is it possible to do this with the C++11 [[]] attribute notation somehow?

I tried:

int x [[unused]] = f();

but it doesn't work.

(Yes, I know it is an implementation-defined attribute.)

Body:
There is [[maybe_unused]] attribute in C++17. It's implemented in GCC 7, see C++ Standards Support in GCC .

Example from P0212R1 proposal:

[[maybe_unused]] void f([[maybe_unused]] bool thing1,
                        [[maybe_unused]] bool thing2) {
    [[maybe_unused]] bool b = thing1 && thing2;
    assert(b);
}


问:
How to manage access rights for rocket.chat, so that all users are not visible to everyone?
I am using Rocket.chat as part of a website, where users from different organizations can log in and chat with their colleagues.

How to configure rocket.chat so that users from different organizations cannot see each other?

For example, can I define a user hierarchy and also a custom permission (like: can-see-other-organization) in Rocket.chat?

答:
Also interested in this question.
One of solutions found: to proxy and filter requests.
Its not the best solution, but no one else found for now.</p>


问:
defining default values
Im a new SAS User and I have a small problem

I have one large empty table A with lets say 100 columns that I have created with a simple proc sql; create table

I have another table B with lets say 40 columns and table C with 55 columns.
I want to add these two tables into table A, basically I want a table with 100 columns containing the data from table B & C and I'm doing this with a Union command.

Since I dont have values for all 100 variables I have to set default values.
Lets say I have a column named nourishment in table A, food in table B and has no equivalent in table C. I have rules like "If the data comes from table B then value =xxx if its from table C then Value="DefaultValue"

I'd do this easily with R or python but Im struggling with sas.

I'm using SAS sql commands (a Union command)

How do you set default values ? (for all data types : character, numeric or dateI'm using SAS sql commands )

答:
```<code>. as MyColumnName
</code>```

SAS can deal with missing values.

Using a specially coded value, such as 'NA', to represent a missing value condition can work but may lead to headaches and extra coding.  Recommended read in SAS help: "Working with Missing Values"

The default SAS missing value for numerics (which also includes dates) is period.

```<code>. as MyColumnName
</code>```

SAS also has 27 special missing values for numerics that are expressed as . < character >

```<code>.A as MyColumnName
...
.Z as MyColumnName
._ as MyColumnName
</code>```

The missing value for character variables is a single space

```<code>' '
'' empty quote string also works
'    ' as does a longer empty string
</code>```

Rule of thumb: be consistent when coding your missing values.

You can use OPTIONS MISSING to specify what character is shown when a missing value is printed.

```<code>OPTIONS MISSING = '*'; * My special representation of missing for this report;
Proc PRINT data=myData;
run;
OPTIONS MISSING = '.'; * Restore to the default;
</code>```

SAS custom formats can also be used to customize what is printed for missing values.

```<code>Proc FORMAT;
  value MissingN
    . = 'N/A'
    .N = 'Special N/A different than regular N/A'  /* for .N */
  ;
  value $MissingC
    ' ' = 'N/A'
  ;
  value SillyChristmasStocking
    .C = 'Bad'
    .O = 'children'
    .A = 'get'
    .L = 'No toys'
  ;
</code>```

The token after the value keyword can be any new valid SAS name that you want to used for your format name.

```<code>Proc PRINT data=myData;
  format myColumnName MissingN.;
  format name $MissingC.;
  format behaviour SillyChristmasStocking.;
run;
</code>```

As for your character missing value conditions, I would continue to use " " or ' '

You mention UNION which is a SQL feature.  In SQL, JOIN also occur, perhaps more often then UNION.  When JOINing and values from two source columns collide, you will want to use either COALESCE() function or CASE
statements to select the non-missing value.

Title: defining default values

Body:
. as MyColumnName

SAS can deal with missing values.

Using a specially coded value, such as 'NA', to represent a missing value condition can work but may lead to headaches and extra coding.  Recommended read in SAS help: "Working with Missing Values"

The default SAS missing value for numerics (which also includes dates) is period.

. as MyColumnName

SAS also has 27 special missing values for numerics that are expressed as . < character >

.A as MyColumnName
...
.Z as MyColumnName
._ as MyColumnName

The missing value for character variables is a single space

' '
'' empty quote string also works
'    ' as does a longer empty string

Rule of thumb: be consistent when coding your missing values.

You can use OPTIONS MISSING to specify what character is shown when a missing value is printed.

OPTIONS MISSING = '*'; * My special representation of missing for this report;
Proc PRINT data=myData;
run;
OPTIONS MISSING = '.'; * Restore to the default;

SAS custom formats can also be used to customize what is printed for missing values.

Proc FORMAT;
  value MissingN
    . = 'N/A'
    .N = 'Special N/A different than regular N/A'  /* for .N */
  ;
  value $MissingC
    ' ' = 'N/A'
  ;
  value SillyChristmasStocking
    .C = 'Bad'
    .O = 'children'
    .A = 'get'
    .L = 'No toys'
  ;

The token after the value keyword can be any new valid SAS name that you want to used for your format name.

Proc PRINT data=myData;
  format myColumnName MissingN.;
  format name $MissingC.;
  format behaviour SillyChristmasStocking.;
run;

As for your character missing value conditions, I would continue to use " " or ' '

You mention UNION which is a SQL feature.  In SQL, JOIN also occur, perhaps more often then UNION.  When JOINing and values from two source columns collide, you will want to use either COALESCE() function or CASE
statements to select the non-missing value.


问:
Delete substrings started with 'vi-' within string
How can I go from 'mystr' to 'result'. I believe it can be done with regular expressions but I don't know how to do it.

mystr

```<code>var mystr = 'football vi-cnn-sel vi-sky test vi-axn red';
</code>```

result

```<code>var result = 'football test red';
</code>```

Regards,
Elio Fernandes

答:
You can use the regex \b(vi\-\[a-zA-Z\-\]*).

And trim your result string of multiple spaces with +(?= )

var mystr = 'football vi-cnn-sel vi-sky test vi-axn red vitest';
var result = mystr.replace(/\bvi\-[a-zA-Z\-]*/g,'').replace(/ +(?= )/g,'');
console.log(result);```

Body:
How can I go from 'mystr' to 'result'. I believe it can be done with regular expressions but I don't know how to do it.

mystr

var mystr = 'football vi-cnn-sel vi-sky test vi-axn red';

result

var result = 'football test red';

Regards,
Elio Fernandes


问:
application doesn't debug on iphone
When I run my application on iphone then I can't debug it, on simulator I can. It doesn't give any error or any message, xcode keep saying that my app is running but my app gets stuck while showing splash screen.

To run application, I need to stop debugger in xcode then restart my application on iphone. I am using xcode v3.2.5.

I reinstalled my xcode but nothing happened.

My console output is

unable to load symbol file: unable to load symbol file: unable to load symbol file: warning: Unable to read symbols for /Developer/Platforms/iPhoneOS.platform/DeviceSupport/4.2.1 (8C148)/Symbols/usr/lib/info/dns.so (file not found).
warning: UUID mismatch detected with the loaded library - on disk is:
    /Developer/Platforms/iPhoneOS.platform/DeviceSupport/4.2.1 (8C148)/Symbols/System/Library/Frameworks/CoreVideo.framework/CoreVideo
warning: UUID mismatch detected with the loaded library - on disk is:
    /Developer/Platforms/iPhoneOS.platform/DeviceSupport/4.2.1 (8C148)/Symbols/usr/lib/libicucore.A.dylib
warning: UUID mismatch detected with the loaded library - on disk is:
    /Developer/Platforms/iPhoneOS.platform/DeviceSupport/4.2.1 (8C148)/Symbols/System/Library/PrivateFrameworks/MobileBluetooth.framework/MobileBluetooth
warning: UUID mismatch detected with the loaded library - on disk is:
    /Developer/Platforms/iPhoneOS.platform/DeviceSupport/4.2.1 (8C148)/Symbols/System/Library/PrivateFrameworks/GameKitServices.framework/GameKitServices
warning: UUID mismatch detected with the loaded library - on disk is:
    /Developer/Platforms/iPhoneOS.platform/DeviceSupport/4.2.1 (8C148)/Symbols/System/Library/Frameworks/MessageUI.framework/MessageUI
warning: UUID mismatch detected with the loaded library - on disk is:
    /Developer/Platforms/iPhoneOS.platform/DeviceSupport/4.2.1 (8C148)/Symbols/System/Library/Frameworks/EventKit.framework/EventKit
warning: UUID mismatch detected with the loaded library - on disk is:
    /Developer/Platforms/iPhoneOS.platform/DeviceSupport/4.2.1 (8C148)/Symbols/System/Library/PrivateFrameworks/WebBookmarks.framework/WebBookmarks
warning: UUID mismatch detected with the loaded library - on disk is:
    /Developer/Platforms/iPhoneOS.platform/DeviceSupport/4.2.1 (8C148)/Symbols/System/Library/PrivateFrameworks/Notes.framework/Notes

答:
Delete /Developer/Platforms/iPhoneOS.platform/DeviceSupport/4.2.1

Restart XCode

Go to organizer and agree to let it download what it wants

works perfectly fine for me :)

Title: application doesn't debug on iphone


问:
How to set initial value in Django UsercreationForm
I am beginner in Django and developing a user registration page using the UserCreationForm from django.contrib.auth.forms. But, unable to set the initial values for password1 and password2 fields.

My requirement is when opening the usercreation form the password and re-enter password fields should get filled with an default password.

I have tried this way but unable to achieve this requirement.

views/user.py

```<code>if request.method == "POST":
    form = UserCreationForm(request.POST)
    if form.is_valid():
        user = form.save()

else:
    form = UserCreationForm(initial={'password1':'testing123','password2':'testing123'})
</code>```

Any help would be appreciated.

答:
It's very bad idea to pre populate with default password. But however this is general idea about how to achive that. And also I recommend to extend the UserCreationForm and do the rest./</p>

```<code># Create form variable...
form = UserCreationForm(initial={
    'password2': 'password',
    'password1': 'password',
    'username': 'rajasimon'})

# Assign render_value to True
form.fields['password1'].widget.render_value = True
form.fields['password2'].widget.render_value = True

# Return template with form...
return render(request, 'base.html', {'form': form})
</code>```

Body:
I am beginner in Django and developing a user registration page using the UserCreationForm from django.contrib.auth.forms. But, unable to set the initial values for password1 and password2 fields.

My requirement is when opening the usercreation form the password and re-enter password fields should get filled with an default password.

I have tried this way but unable to achieve this requirement.

views/user.py

if request.method == "POST":
    form = UserCreationForm(request.POST)
    if form.is_valid():
        user = form.save()

else:
    form = UserCreationForm(initial={'password1':'testing123','password2':'testing123'})

Any help would be appreciated.

Body:
It's very bad idea to pre populate with default password. But however this is general idea about how to achive that. And also I recommend to extend the UserCreationForm and do the rest./

# Create form variable...
form = UserCreationForm(initial={
    'password2': 'password',
    'password1': 'password',
    'username': 'rajasimon'})

# Assign render_value to True
form.fields['password1'].widget.render_value = True
form.fields['password2'].widget.render_value = True

# Return template with form...
return render(request, 'base.html', {'form': form})


问:
How to pull data from URL into form with Ruby on Rails 5
I have a form where users can fill to share design work. However fields are pretty similar to dribbble.com .

I see some websites allow user to paste a link that auto fills the form. Example can be seen at https://www.uplabs.com/submit

I dont need the exact codes on how to do this. Can you please advise a direction? some plugins, some examples, ...?

Example; filling form (image, title, designer id, description, etc.) from link a link like https://dribbble.com/shots/1902343-Subscribe-to-our-newsletters

Thank you!

答:
You can do that using using Ajax call to a Rails controller.
Create a rails controller which will scrap from the webpage title and meta description. You can use mechanize like in the example below.

Then using Ajax call send pasted url to that rails controller action and there perform scrapping

```<code>$("#url_input").on("paste", function(e) {
  $.ajax({
    url: "/url_data_grabber/grab",
    data: $("#url_input").val(),
    success: function(result) {
      $("#title").val(result["title"]);
      $("#title").val(result["description"]);
    }
  });
});

require 'mechanize'
class UrlGrabberController < ApplicationController
  def grab
    pasted_url = params.fetch("pasted_url")
    page = agent.get(pasted_url)
    title = page.title

    node = page.at("head meta[name='description']")
    description = node["content"]

    render json: {title: title, description: description}
  end
end
</code>```

Body:
You can do that using using Ajax call to a Rails controller.
Create a rails controller which will scrap from the webpage title and meta description. You can use mechanize like in the example below.

Then using Ajax call send pasted url to that rails controller action and there perform scrapping

$("#url_input").on("paste", function(e) {
  $.ajax({
    url: "/url_data_grabber/grab",
    data: $("#url_input").val(),
    success: function(result) {
      $("#title").val(result["title"]);
      $("#title").val(result["description"]);
    }
  });
});

require 'mechanize'
class UrlGrabberController < ApplicationController
  def grab
    pasted_url = params.fetch("pasted_url")
    page = agent.get(pasted_url)
    title = page.title

    node = page.at("head meta[name='description']")
    description = node["content"]

    render json: {title: title, description: description}
  end
end


问:
SAMLException: InResponseToField of the Response doesn't correspond to sent message
We are working on an application, which is protected with spring security saml.

Authentication works fine, but there is one problem with the following workflow in production environment.

user requests the unprotected address www.server.com

response is a html page with an inline script that changes window.location.href to the saml protected page (service provider) www.server.com/app/action?param1=value1&param2=value2

spring saml detects that authentication is needed and redirects the user to the login form (identity provider) on www.login-server.com

at this point the login form is the first page that is displayed to the user

user adds this login page as bookmark (including saml related url params for this http session) www.login-server.com/adfs/ls/?SAMLRequest=xxx&SigAlg=xxx&Signature=arGdsZwJtHzTDjQP1oYqbjNO

user works with the application...

at the next day the user opens this bookmark and login

IdP redirects to the SP but the belonging http session has already expired

Now we get the following exception in our application:

org.opensaml.common.SAMLException: InResponseToField of the Response doesn't correspond to sent message arGdsZwJtHzTDjQP1oYqbjNO

Any ideas how to handle this workflow so the user can use the application after successful login?
Thanks for your answers!

答:
We have solved our issue with following changes to the spring saml configuration:

In bean with id successRedirectHandler (org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler) we set the defaultTargetUrl to the init-Action of our application (including all request parameters). This url will be automatically used in case of IdP initiated SSO.

In Bean with id contextProvider (org.springframework.security.saml.context.SAMLContextProviderLB) we set storageFactory to org.springframework.security.saml.storage.EmptyStorageFactory. This disables the check of the InResponseToField.


问:
How do you set the JRViewer export options?
Recently I updated my project with the newest jasper-reports lib.
There is a new JRViewer class (net.sf.jasperreports.swing) which replaced the old one (net.sf.jasperreports.view). Now I can't figure out how to set the export options. The old code was like:</p>

```<code>JRPdfSaveContributor pdf = new JRPdfSaveContributor(locale, resBundle);
JRRtfSaveContributor rtf = new JRRtfSaveContributor(locale, resBundle);
JRSingleSheetXlsSaveContributor xls = new JRSingleSheetXlsSaveContributor(locale, resBundle);
JRDocxSaveContributor docx = new JRDocxSaveContributor(locale, resBundle);
viewer.setSaveContributors(new JRSaveContributor[] { pdf, rtf, xls, docx });
</code>```

答:
You'll have to extend net.sf.jasperreports.swing.JRViewer and set the export contributors to JRViewerToolbar.  Something like this:</p>

```<code>public class MyJRViewer extends JRViewer {
    //define the constructor that you use
    public MyJRViewer(JasperPrint jasperPrint) {
        super(jasperPrint);
    }

    @Override
    protected JRViewerToolbar createToolbar() {
        JRViewerToolbar toolbar = super.createToolbar();

        Locale locale = viewerContext.getLocale();
        ResourceBundle resBundle = viewerContext.getResourceBundle();
        JRPdfSaveContributor pdf = new JRPdfSaveContributor(locale, resBundle);
        JRRtfSaveContributor rtf = new JRRtfSaveContributor(locale, resBundle);
        JRSingleSheetXlsSaveContributor xls = new JRSingleSheetXlsSaveContributor(locale, resBundle);
        JRDocxSaveContributor docx = new JRDocxSaveContributor(locale, resBundle);
        toolbar.setSaveContributors(new JRSaveContributor[] {pdf, rtf, xls, docx});

        return toolbar;
    }
}
</code>```

Body:
Recently I updated my project with the newest jasper-reports lib.
There is a new JRViewer class (net.sf.jasperreports.swing) which replaced the old one (net.sf.jasperreports.view). Now I can't figure out how to set the export options. The old code was like:

JRPdfSaveContributor pdf = new JRPdfSaveContributor(locale, resBundle);
JRRtfSaveContributor rtf = new JRRtfSaveContributor(locale, resBundle);
JRSingleSheetXlsSaveContributor xls = new JRSingleSheetXlsSaveContributor(locale, resBundle);
JRDocxSaveContributor docx = new JRDocxSaveContributor(locale, resBundle);
viewer.setSaveContributors(new JRSaveContributor[] { pdf, rtf, xls, docx });

Body:
You'll have to extend net.sf.jasperreports.swing.JRViewer and set the export contributors to JRViewerToolbar.  Something like this:

public class MyJRViewer extends JRViewer {
    //define the constructor that you use
    public MyJRViewer(JasperPrint jasperPrint) {
        super(jasperPrint);
    }

    @Override
    protected JRViewerToolbar createToolbar() {
        JRViewerToolbar toolbar = super.createToolbar();

        Locale locale = viewerContext.getLocale();
        ResourceBundle resBundle = viewerContext.getResourceBundle();
        JRPdfSaveContributor pdf = new JRPdfSaveContributor(locale, resBundle);
        JRRtfSaveContributor rtf = new JRRtfSaveContributor(locale, resBundle);
        JRSingleSheetXlsSaveContributor xls = new JRSingleSheetXlsSaveContributor(locale, resBundle);
        JRDocxSaveContributor docx = new JRDocxSaveContributor(locale, resBundle);
        toolbar.setSaveContributors(new JRSaveContributor[] {pdf, rtf, xls, docx});

        return toolbar;
    }
}


问:
How to access Node JS route Url in Angular JS site
I am working on a site which is in Angular JS language. Now for website, I have to generate dynamic sitemaps and for this I used Node JS and created a xml.js route in node and wrote hello world.

Now the problem is, I am not able to use access this xml.js in angular site. Here is xml.js code :

```<code>var express = require("express");
var router = express.Router();

router.get("/test", function() {
    console.log("hello world");
});

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

Here is server.js code :

```<code>var express=require('express');
var xml = require("./xml");
var app=express();
app.use('/xml',xml);
app.use('/',express.static('app'));
app.listen(9000) ;
</code>```

Now whenever I try to access http://192.168.0.19:9000/xml/test I am being redirected to home page always.

Can someone help me out ?

答:
You can try this code.This code work for me

You need to pass req and res parameter.

```<code>router.get('/', function (req, res) {
    res.send('home page')
})
router.get("/test", function (req, res) {
    console.log("hello world");
    res.send('test page')
})
</code>```

Body:
I am working on a site which is in Angular JS language. Now for website, I have to generate dynamic sitemaps and for this I used Node JS and created a xml.js route in node and wrote hello world.

Now the problem is, I am not able to use access this xml.js in angular site. Here is xml.js code :

var express = require("express");
var router = express.Router();

router.get("/test", function() {
    console.log("hello world");
});

module.exports = router;

Here is server.js code :

var express=require('express');
var xml = require("./xml");
var app=express();
app.use('/xml',xml);
app.use('/',express.static('app'));
app.listen(9000) ;

Now whenever I try to access http://192.168.0.19:9000/xml/test I am being redirected to home page always.

Can someone help me out ?

Body:
You can try this code.This code work for me

You need to pass req and res parameter.

router.get('/', function (req, res) {
    res.send('home page')
})
router.get("/test", function (req, res) {
    console.log("hello world");
    res.send('test page')
})


问:
Python: requests.post not posting
I'm trying to post a json string to Google Firebase.

The same command works without hickups using curl, but if I do that using Python, there's no data in the DB.

Here's the code:

```<code>postdata = {"pm10": pm10, "pm2.5": pm25, "lat": gps_data.get('latitude'), "lon": gps_data.get('longitude'), "alt": gps_data.get('speed'), "spd": gps_data.get('altitude2'), "satt": gps_data.get('satellites')}

logging.info(args.url)
logging.info(postdata)

r = requests.post(args.url, data=postdata, headers={'content-type': 'application/json'})

logging.debug(r)
</code>```

I call the script using:

python l.py -u http://blabla.firebaseio.com/test1.json

The output is:

```<code>INFO:Serial device initialized
INFO:Posting to http://blabla.firebaseio.com/test1.json
INFO:http://blabla.firebaseio.com/test1.json
INFO:{'satt': 10, 'pm10': 30, 'lon': XX.XXXXX, 'pm2.5': 27, 'lat': YY.YYYYY, 'alt': 0.037, 'spd': 336.8}
INFO:PM 10: 30
INFO:PM 2.5: 27
INFO:Latitude: XX.XXXX
INFO:longitude: YY.YYYYY
</code>```

But when I open the DB, no data.

Using curl with the same parameters works.

Update:

Logging debug provides this as info:

```<code>DEBUG:requests.packages.urllib3.connectionpool:Starting new HTTP connection (1): blabla.firebaseio.com
DEBUG:requests.packages.urllib3.connectionpool:http://blabla.firebaseio.com:80 "POST /test1.json HTTP/1.1" 404 1571
DEBUG:root:<Response [404]>
</code>```

答:
So, turns out the issue was with one of the variables being passed as json contained an invalid char.

The value was pm2.5, so I just renamed it to pm25.

The key is not to have any chars such as . - or something of the sort.

After that it started working.

Title: Python: requests.post not posting

Body:
I'm trying to post a json string to Google Firebase.

The same command works without hickups using curl, but if I do that using Python, there's no data in the DB.

Here's the code:

postdata = {"pm10": pm10, "pm2.5": pm25, "lat": gps_data.get('latitude'), "lon": gps_data.get('longitude'), "alt": gps_data.get('speed'), "spd": gps_data.get('altitude2'), "satt": gps_data.get('satellites')}

logging.info(args.url)
logging.info(postdata)

r = requests.post(args.url, data=postdata, headers={'content-type': 'application/json'})

logging.debug(r)

I call the script using:

python l.py -u http://blabla.firebaseio.com/test1.json

The output is:

INFO:Serial device initialized
INFO:Posting to http://blabla.firebaseio.com/test1.json
INFO:http://blabla.firebaseio.com/test1.json
INFO:{'satt': 10, 'pm10': 30, 'lon': XX.XXXXX, 'pm2.5': 27, 'lat': YY.YYYYY, 'alt': 0.037, 'spd': 336.8}
INFO:PM 10: 30
INFO:PM 2.5: 27
INFO:Latitude: XX.XXXX
INFO:longitude: YY.YYYYY

But when I open the DB, no data.

Using curl with the same parameters works.

Update:

Logging debug provides this as info:

DEBUG:requests.packages.urllib3.connectionpool:Starting new HTTP connection (1): blabla.firebaseio.com
DEBUG:requests.packages.urllib3.connectionpool:http://blabla.firebaseio.com:80 "POST /test1.json HTTP/1.1" 404 1571
DEBUG:root:<Response [404]>


问:
PowerMockito: Unable to mock a constructor if code is in another class
I am facing a very weird issue here.

Following is my Test class:

SearchViewModel.java

```<code>@RunWith(PowerMockRunner.class)
@PrepareForTest({JSONReader.class, ConstantsPath.class, DatabaseManager.class})
public class SearchViewModelTest {

    @Rule
    public TestRule rule = new InstantTaskExecutorRule();
    private String indexSearchContent;
    private String fullTextSearchContentGL1, fullTextSearchContentGL2, fullTextSearchContentGL3, fullTextSearchContentGL4;
    private String searchQuery = "a";
    private List<FullTextSearchItem> fullTextSearchResult;
    private String behaviorString;
    private SearchViewModel searchViewModel;
    private DatabaseManager databaseManager;

    private void initInputs() throws IOException {
        indexSearchContent = JSONReader.convertStreamToString(getClass().getClassLoader().getResourceAsStream(ConstantsPath.getInstance().getIndexSearchFilePath()));
        behaviorString = JSONReader.convertStreamToString(getClass().getClassLoader().getResourceAsStream(ConstantsPath.getInstance().getBehavioralFilePath()));

        fullTextSearchContentGL1 = JSONReader.convertStreamToString(getClass().getClassLoader().getResourceAsStream(ConstantsPath.getInstance().getFullTextSearchFilePath("1")));
        fullTextSearchContentGL2 = JSONReader.convertStreamToString(getClass().getClassLoader().getResourceAsStream(ConstantsPath.getInstance().getFullTextSearchFilePath("2")));
        fullTextSearchContentGL3 = JSONReader.convertStreamToString(getClass().getClassLoader().getResourceAsStream(ConstantsPath.getInstance().getFullTextSearchFilePath("3")));

    }

    private void mockDaggerDependency() {
        AppInfo appInfo = Mockito.mock(AppInfo.class);
        Mockito.when(appInfo.getAppName()).thenReturn("testApp");
        Mockito.when(appInfo.getAppLanguage()).thenReturn("EN");

        TestApplicationModule module = new TestApplicationModule(appInfo);
        DatabaseModule databaseModule = Mockito.mock(DatabaseModule.class);
        Component component = DaggerComponent.builder().applicationModule(module).databaseModule(databaseModule).build();
        MyApplication.setComponent(component);
    }

    private void mockGuidelineList() throws Exception {
        databaseManager = PowerMockito.mock(DatabaseManager.class);
        List<Guideline> mockedGls = new ArrayList<>();
        Guideline gl = new Guideline();
        gl.setGuidelineId("1");
        mockedGls.add(gl);
        gl = new Guideline();
        gl.setGuidelineId("2");
        mockedGls.add(gl);
        gl = new Guideline();
        gl.setGuidelineId("3");
        mockedGls.add(gl);
        Mockito.when(databaseManager.getGuidelinesListByPositionOnHome()).thenReturn(mockedGls);

        PowerMockito.whenNew(DatabaseManager.class).withNoArguments().thenReturn(databaseManager);
        // prepare expected output for fulltext search
        Observable.fromIterable(new DatabaseManager().getGuidelinesListByPositionOnHome())
                .map(Guideline::getGuidelineId)
                .flatMap(glId -> BehavioralFile.<List<FullTextSearchItem>>loadJsonFile(ConstantsPath.getInstance().getFullTextSearchFilePath(glId),
                        new TypeToken<List<FullTextSearchItem>>() {
                        }.getType()).toObservable()
                        .flatMapIterable(fullTextSearchitems -> fullTextSearchitems)
                        .filter(item -> item.getText().toLowerCase().contains(searchQuery.toLowerCase()))).<List<FullTextSearchItem>>toList()
                .subscribe(list -> {
                    fullTextSearchResult = list;
                });
    }

    @Before
    public void setUp() throws Exception {
        MainActivityTest.overrideRxJavaPlugins();
        mockDaggerDependency();
        initInputs();

        PowerMockito.mockStatic(JSONReader.class);
        BDDMockito.given(JSONReader.readJsonFile(ConstantsPath.getInstance().getIndexSearchFilePath())).willReturn(indexSearchContent);

        BDDMockito.given(JSONReader.readJsonFile(ConstantsPath.getInstance().getFullTextSearchFilePath("1"))).willReturn(fullTextSearchContentGL1);
        BDDMockito.given(JSONReader.readJsonFile(ConstantsPath.getInstance().getFullTextSearchFilePath("2"))).willReturn(fullTextSearchContentGL2);
        BDDMockito.given(JSONReader.readJsonFile(ConstantsPath.getInstance().getFullTextSearchFilePath("3"))).willReturn(fullTextSearchContentGL3);

        BDDMockito.given(JSONReader.readJsonFile(ConstantsPath.getInstance().getBehavioralFilePath())).willReturn(behaviorString);

        mockGuidelineList();

        searchViewModel = new SearchViewModel();
    }

    @After
    public void tearDown() throws Exception {
    }

    @Test
    public void loadFullTextSearch() throws Exception {

        //searchViewModel.loadFullTextSearch_(searchQuery);
        loadFullTextSearch(searchQuery);

        assertEquals(searchViewModel.fullTextSearchListLiveData.getValue().size(), fullTextSearchResult.size());
    }

    private void loadFullTextSearch(String query) {
       // following line is throwing exception if put in another class.
        Observable.fromIterable(new DatabaseManager().getGuidelinesListByPositionOnHome())
                .map(Guideline::getGuidelineId)
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(Schedulers.io())
                .flatMap(glId -> BehavioralFile.<List<FullTextSearchItem>>loadJsonFile(ConstantsPath.getInstance().getFullTextSearchFilePath(glId),
                        new TypeToken<List<FullTextSearchItem>>() {
                        }.getType()).toObservable()
                        .flatMapIterable(fullTextSearchitems -> fullTextSearchitems)
                        .filter(item -> item.getText().toLowerCase().contains(query.toLowerCase()))).<List<FullTextSearchItem>>toList().toObservable()
                .subscribe(list -> searchViewModel.fullTextSearchListLiveData.setValue(list));
    }

}
</code>```

here loadFullTextSearch() test cases works perfectly fine until i remove comment of line searchViewModel.loadFullTextSearch_(searchQuery);,

check modified test case:

```<code>@Test
public void loadFullTextSearch() throws Exception {

        searchViewModel.loadFullTextSearch_(searchQuery);
        //loadFullTextSearch(searchQuery);

        assertEquals(searchViewModel.fullTextSearchListLiveData.getValue().size(), fullTextSearchResult.size());
    }
</code>```

Here comes the weird part: both the functions(earchViewModel.loadFullTextSearch_(), loadFullTextSearch()) has same code but loadFullTestSearch_() is in SearchViewModel class and loadFullTextSearch() in is test cases it self, that i did to figure out why constructor of DatabaseManager class is not getting mocked(Observable.fromIterable(new DatabaseManager().getGuidelinesListByPositionOnHome())) when code is in SearchViewModel class.

Note: I am mocking constructor of DatabaseManager class. check mockGuidelineList() method. Mocked method is working if constructor is getting invoked in same test class.

Exception i get is :

```<code>java.lang.NullPointerException: Cannot return null from a non-@Nullable @Provides method
</code>```

Because i am using dagger and the constructor i am mocking initialises database object dependency.

```<code>public DatabaseManager() {
    MyApplication.getComponent().inject(this);
}
</code>```

Any help would be appreciated, Thanks.

答:
I was doing everything fine but missed to add class where constructor is being invoked in @PrepareForTest annotation.

So in my case this has to be:

```<code>@PrepareForTest({JSONReader.class, ConstantsPath.class, DatabaseManager.class, SearchViewModel.class})
</code>```

this stackoverflow answer helped me out.

Body:
I am facing a very weird issue here.

Following is my Test class:

SearchViewModel.java

@RunWith(PowerMockRunner.class)
@PrepareForTest({JSONReader.class, ConstantsPath.class, DatabaseManager.class})
public class SearchViewModelTest {

    @Rule
    public TestRule rule = new InstantTaskExecutorRule();
    private String indexSearchContent;
    private String fullTextSearchContentGL1, fullTextSearchContentGL2, fullTextSearchContentGL3, fullTextSearchContentGL4;
    private String searchQuery = "a";
    private List<FullTextSearchItem> fullTextSearchResult;
    private String behaviorString;
    private SearchViewModel searchViewModel;
    private DatabaseManager databaseManager;

    private void initInputs() throws IOException {
        indexSearchContent = JSONReader.convertStreamToString(getClass().getClassLoader().getResourceAsStream(ConstantsPath.getInstance().getIndexSearchFilePath()));
        behaviorString = JSONReader.convertStreamToString(getClass().getClassLoader().getResourceAsStream(ConstantsPath.getInstance().getBehavioralFilePath()));

        fullTextSearchContentGL1 = JSONReader.convertStreamToString(getClass().getClassLoader().getResourceAsStream(ConstantsPath.getInstance().getFullTextSearchFilePath("1")));
        fullTextSearchContentGL2 = JSONReader.convertStreamToString(getClass().getClassLoader().getResourceAsStream(ConstantsPath.getInstance().getFullTextSearchFilePath("2")));
        fullTextSearchContentGL3 = JSONReader.convertStreamToString(getClass().getClassLoader().getResourceAsStream(ConstantsPath.getInstance().getFullTextSearchFilePath("3")));

    }

    private void mockDaggerDependency() {
        AppInfo appInfo = Mockito.mock(AppInfo.class);
        Mockito.when(appInfo.getAppName()).thenReturn("testApp");
        Mockito.when(appInfo.getAppLanguage()).thenReturn("EN");

        TestApplicationModule module = new TestApplicationModule(appInfo);
        DatabaseModule databaseModule = Mockito.mock(DatabaseModule.class);
        Component component = DaggerComponent.builder().applicationModule(module).databaseModule(databaseModule).build();
        MyApplication.setComponent(component);
    }

    private void mockGuidelineList() throws Exception {
        databaseManager = PowerMockito.mock(DatabaseManager.class);
        List<Guideline> mockedGls = new ArrayList<>();
        Guideline gl = new Guideline();
        gl.setGuidelineId("1");
        mockedGls.add(gl);
        gl = new Guideline();
        gl.setGuidelineId("2");
        mockedGls.add(gl);
        gl = new Guideline();
        gl.setGuidelineId("3");
        mockedGls.add(gl);
        Mockito.when(databaseManager.getGuidelinesListByPositionOnHome()).thenReturn(mockedGls);

        PowerMockito.whenNew(DatabaseManager.class).withNoArguments().thenReturn(databaseManager);
        // prepare expected output for fulltext search
        Observable.fromIterable(new DatabaseManager().getGuidelinesListByPositionOnHome())
                .map(Guideline::getGuidelineId)
                .flatMap(glId -> BehavioralFile.<List<FullTextSearchItem>>loadJsonFile(ConstantsPath.getInstance().getFullTextSearchFilePath(glId),
                        new TypeToken<List<FullTextSearchItem>>() {
                        }.getType()).toObservable()
                        .flatMapIterable(fullTextSearchitems -> fullTextSearchitems)
                        .filter(item -> item.getText().toLowerCase().contains(searchQuery.toLowerCase()))).<List<FullTextSearchItem>>toList()
                .subscribe(list -> {
                    fullTextSearchResult = list;
                });
    }

    @Before
    public void setUp() throws Exception {
        MainActivityTest.overrideRxJavaPlugins();
        mockDaggerDependency();
        initInputs();

        PowerMockito.mockStatic(JSONReader.class);
        BDDMockito.given(JSONReader.readJsonFile(ConstantsPath.getInstance().getIndexSearchFilePath())).willReturn(indexSearchContent);

        BDDMockito.given(JSONReader.readJsonFile(ConstantsPath.getInstance().getFullTextSearchFilePath("1"))).willReturn(fullTextSearchContentGL1);
        BDDMockito.given(JSONReader.readJsonFile(ConstantsPath.getInstance().getFullTextSearchFilePath("2"))).willReturn(fullTextSearchContentGL2);
        BDDMockito.given(JSONReader.readJsonFile(ConstantsPath.getInstance().getFullTextSearchFilePath("3"))).willReturn(fullTextSearchContentGL3);

        BDDMockito.given(JSONReader.readJsonFile(ConstantsPath.getInstance().getBehavioralFilePath())).willReturn(behaviorString);

        mockGuidelineList();

        searchViewModel = new SearchViewModel();
    }

    @After
    public void tearDown() throws Exception {
    }

    @Test
    public void loadFullTextSearch() throws Exception {

        //searchViewModel.loadFullTextSearch_(searchQuery);
        loadFullTextSearch(searchQuery);

        assertEquals(searchViewModel.fullTextSearchListLiveData.getValue().size(), fullTextSearchResult.size());
    }

    private void loadFullTextSearch(String query) {
       // following line is throwing exception if put in another class.
        Observable.fromIterable(new DatabaseManager().getGuidelinesListByPositionOnHome())
                .map(Guideline::getGuidelineId)
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(Schedulers.io())
                .flatMap(glId -> BehavioralFile.<List<FullTextSearchItem>>loadJsonFile(ConstantsPath.getInstance().getFullTextSearchFilePath(glId),
                        new TypeToken<List<FullTextSearchItem>>() {
                        }.getType()).toObservable()
                        .flatMapIterable(fullTextSearchitems -> fullTextSearchitems)
                        .filter(item -> item.getText().toLowerCase().contains(query.toLowerCase()))).<List<FullTextSearchItem>>toList().toObservable()
                .subscribe(list -> searchViewModel.fullTextSearchListLiveData.setValue(list));
    }

}

here loadFullTextSearch() test cases works perfectly fine until i remove comment of line searchViewModel.loadFullTextSearch_(searchQuery);,

check modified test case:

@Test
public void loadFullTextSearch() throws Exception {

        searchViewModel.loadFullTextSearch_(searchQuery);
        //loadFullTextSearch(searchQuery);

        assertEquals(searchViewModel.fullTextSearchListLiveData.getValue().size(), fullTextSearchResult.size());
    }

Here comes the weird part: both the functions(earchViewModel.loadFullTextSearch_(), loadFullTextSearch()) has same code but loadFullTestSearch_() is in SearchViewModel class and loadFullTextSearch() in is test cases it self, that i did to figure out why constructor of DatabaseManager class is not getting mocked(Observable.fromIterable(new DatabaseManager().getGuidelinesListByPositionOnHome())) when code is in SearchViewModel class.

Note: I am mocking constructor of DatabaseManager class. check mockGuidelineList() method. Mocked method is working if constructor is getting invoked in same test class.

Exception i get is :

java.lang.NullPointerException: Cannot return null from a non-@Nullable @Provides method

Because i am using dagger and the constructor i am mocking initialises database object dependency.

public DatabaseManager() {
    MyApplication.getComponent().inject(this);
}

Any help would be appreciated, Thanks.

Body:
I was doing everything fine but missed to add class where constructor is being invoked in @PrepareForTest annotation.

So in my case this has to be:

@PrepareForTest({JSONReader.class, ConstantsPath.class, DatabaseManager.class, SearchViewModel.class})

this stackoverflow answer helped me out.


问:
A amazing result with CUDA GPU when block number is large
Recently I work with CUDA programming, I met an incredible problem when the blockNum Exceeding 500. In order to simplify the mode,I wrote the following test code:

```<code>#include <assert.h>
#include <cuda.h>
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <cuda_runtime.h>
#include <device_launch_parameters.h>
/* Example from "Introduction to CUDA C" from NVIDIA website:
https://developer.nvidia.com/cuda-education

Compile with:
$ nvcc example_intro.cu */

#define num 1000
const int N = num*32*12;

__global__ void add_blocks (int *a,  int *c) {
   int threadId = blockIdx.x * blockDim.x * blockDim.y
                + threadIdx.y * blockDim.x + threadIdx.x;
    int block_id = threadIdx.y;
    if(threadId % 2 == 0){
        c[threadId] =  1;
    }
}

int main(void) {

    int *a, *c;
    int *d_a,  *d_c; /* Device (GPU) copies of a, b, c */
    size_t size = N * sizeof(int);

    /* Allocate memory in device */
    cudaMalloc((void **) &d_a, size);
    cudaMalloc((void **) &d_c, size);

    /* Allocate memory in host */
    a = (int *) malloc(size);
    c = (int *) malloc(size);

    /* Allocate random data in vectors a and b (inside host) */
    for (int i = 0; i < N; ++i) {
        a[i] = 0;
        c[i] = 0;
    }

    /* Copy data to device */
    cudaMemcpy(d_a, a, size, cudaMemcpyHostToDevice);

    dim3 threads_per_block(32, 12);
    add_blocks<<<num, threads_per_block>>>(d_a,d_c);
    cudaMemcpy(c, d_c, size, cudaMemcpyDeviceToHost);

    cudaError_t errSync  = cudaGetLastError();
    if (errSync != cudaSuccess)
    printf("Sync kernel error: %s\n", cudaGetErrorString(errSync));

    int counter = 0;
    for (int i = 0; i < N; ++i) {
        if(c[i] == 1){
            counter ++;
        }
    }
    printf("%d\n",counter);

    /* Clean-up */
    free(a);
    free(c);
    cudaFree(d_a);
    cudaFree(d_c);

    return 0;
  }
</code>```

when the thread num is multiples of 2, I set the c array with 1, and in the end I count the num of 1, which I think is  N/2. It works well when block num is below 500, for example is num*32*12/2 = 500 * 32 * 12 / 2 = 96 000. But when num is 1000 the result is 312846 which should be 192000. Anyone can help me? thanks all.

答:
The problem is in this code:

```<code>int counter = 0;
for (int i = 0; i < N; ++i) {
    if(c[i] == 1){
        counter ++;
    }
}
printf("%d\n",counter);
</code>```

You are implicitly assuming that every value of 1 in c must have been set by the prior GPU kernel. However, you never set the value of half of the elements in d_c (and thus c at this point in the program) at all, so there is no guarantee that some of those also won't have a value of 1. Reading and using the values of unitialized memory isn't amazing, it is just bad programming practice.

Body:
Recently I work with CUDA programming, I met an incredible problem when the blockNum Exceeding 500. In order to simplify the mode,I wrote the following test code:

#include <assert.h>
#include <cuda.h>
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <cuda_runtime.h>
#include <device_launch_parameters.h>
/* Example from "Introduction to CUDA C" from NVIDIA website:
https://developer.nvidia.com/cuda-education

Compile with:
$ nvcc example_intro.cu */

#define num 1000
const int N = num*32*12;

__global__ void add_blocks (int *a,  int *c) {
   int threadId = blockIdx.x * blockDim.x * blockDim.y
                + threadIdx.y * blockDim.x + threadIdx.x;
    int block_id = threadIdx.y;
    if(threadId % 2 == 0){
        c[threadId] =  1;
    }
}

int main(void) {

    int *a, *c;
    int *d_a,  *d_c; /* Device (GPU) copies of a, b, c */
    size_t size = N * sizeof(int);

    /* Allocate memory in device */
    cudaMalloc((void **) &d_a, size);
    cudaMalloc((void **) &d_c, size);

    /* Allocate memory in host */
    a = (int *) malloc(size);
    c = (int *) malloc(size);

    /* Allocate random data in vectors a and b (inside host) */
    for (int i = 0; i < N; ++i) {
        a[i] = 0;
        c[i] = 0;
    }

    /* Copy data to device */
    cudaMemcpy(d_a, a, size, cudaMemcpyHostToDevice);

    dim3 threads_per_block(32, 12);
    add_blocks<<<num, threads_per_block>>>(d_a,d_c);
    cudaMemcpy(c, d_c, size, cudaMemcpyDeviceToHost);

    cudaError_t errSync  = cudaGetLastError();
    if (errSync != cudaSuccess)
    printf("Sync kernel error: %s\n", cudaGetErrorString(errSync));

    int counter = 0;
    for (int i = 0; i < N; ++i) {
        if(c[i] == 1){
            counter ++;
        }
    }
    printf("%d\n",counter);

    /* Clean-up */
    free(a);
    free(c);
    cudaFree(d_a);
    cudaFree(d_c);

    return 0;
  }

when the thread num is multiples of 2, I set the c array with 1, and in the end I count the num of 1, which I think is  N/2. It works well when block num is below 500, for example is num*32*12/2 = 500 * 32 * 12 / 2 = 96 000. But when num is 1000 the result is 312846 which should be 192000. Anyone can help me? thanks all.

Body:
The problem is in this code:

int counter = 0;
for (int i = 0; i < N; ++i) {
    if(c[i] == 1){
        counter ++;
    }
}
printf("%d\n",counter);

You are implicitly assuming that every value of 1 in c must have been set by the prior GPU kernel. However, you never set the value of half of the elements in d_c (and thus c at this point in the program) at all, so there is no guarantee that some of those also won't have a value of 1. Reading and using the values of unitialized memory isn't amazing, it is just bad programming practice.