问:
Throwing exception from CompletableFuture
I have the following code:

```<code>// How to throw the ServerException?
public void myFunc() throws ServerException{
    // Some code
    CompletableFuture<A> a = CompletableFuture.supplyAsync(() -> {
        try {
            return someObj.someFunc();
        } catch(ServerException ex) {
            // throw ex; gives an error here.
        }
    }));
    // Some code
}
</code>```

someFunc() throws a ServerException. I don't want to handle this here but throw the exception from someFunc() to caller of myFunc().

答:
Your code suggests that you are using the result of the asynchronous operation later in the same method, so you’ll have to deal with CompletionException anyway, so one way to deal with it, is

```<code>public void myFunc() throws ServerException {
    // Some code
    CompletableFuture<A> a = CompletableFuture.supplyAsync(() -> {
        try { return someObj.someFunc(); }
        catch(ServerException ex) { throw new CompletionException(ex); }
    });
    // Some code running in parallel to someFunc()

    A resultOfA;
    try {
        resultOfA = a.join();
    }
    catch(CompletionException ex) {
        try {
            throw ex.getCause();
        }
        catch(Error|RuntimeException|ServerException possible) {
            throw possible;
        }
        catch(Throwable impossible) {
            throw new AssertionError(impossible);
        }
    }
    // some code using resultOfA
}
</code>```

All exceptions thrown inside the asynchronous processing of the Supplier will get wrapped into a CompletionException when calling join, except the ServerException we have already wrapped in a CompletionException.

When we re-throw the cause of the CompletionException, we may face unchecked exceptions, i.e. subclasses of Error or RuntimeException, or our custom checked exception ServerException. The code above handles all of them with a multi-catch which will re-throw them. Since the declared return type of getCause() is Throwable, the compiler requires us to handle that type despite we already handled all possible types. The straight-forward solution is to throw this actually impossible throwable wrapped in an AssertionError.

Alternatively, we could use an alternative result future for our custom exception:

```<code>public void myFunc() throws ServerException {
    // Some code
    CompletableFuture<ServerException> exception = new CompletableFuture<>();
    CompletableFuture<A> a = CompletableFuture.supplyAsync(() -> {
        try { return someObj.someFunc(); }
        catch(ServerException ex) {
            exception.complete(ex);
            throw new CompletionException(ex);
        }
    });
    // Some code running in parallel to someFunc()

    A resultOfA;
    try {
        resultOfA = a.join();
    }
    catch(CompletionException ex) {
        if(exception.isDone()) throw exception.join();
        throw ex;
    }

    // some code using resultOfA
}
</code>```

This solution will re-throw all “unexpected” throwables in their wrapped form, but only throw the custom ServerException in its original form passed via the exception future. Note that we have to ensure that a has been completed (like calling join() first), before we query the exception future, to avoid race conditions.

Body:
I have the following code:

// How to throw the ServerException?
public void myFunc() throws ServerException{
    // Some code
    CompletableFuture a = CompletableFuture.supplyAsync(() -> {
        try {
            return someObj.someFunc();
        } catch(ServerException ex) {
            // throw ex; gives an error here.
        }
    }));
    // Some code
}

someFunc() throws a ServerException. I don't want to handle this here but throw the exception from someFunc() to caller of myFunc().

Body:
Your code suggests that you are using the result of the asynchronous operation later in the same method, so you’ll have to deal with CompletionException anyway, so one way to deal with it, is

public void myFunc() throws ServerException {
    // Some code
    CompletableFuture<A> a = CompletableFuture.supplyAsync(() -> {
        try { return someObj.someFunc(); }
        catch(ServerException ex) { throw new CompletionException(ex); }
    });
    // Some code running in parallel to someFunc()

    A resultOfA;
    try {
        resultOfA = a.join();
    }
    catch(CompletionException ex) {
        try {
            throw ex.getCause();
        }
        catch(Error|RuntimeException|ServerException possible) {
            throw possible;
        }
        catch(Throwable impossible) {
            throw new AssertionError(impossible);
        }
    }
    // some code using resultOfA
}

All exceptions thrown inside the asynchronous processing of the Supplier will get wrapped into a CompletionException when calling join, except the ServerException we have already wrapped in a CompletionException.

When we re-throw the cause of the CompletionException, we may face unchecked exceptions, i.e. subclasses of Error or RuntimeException, or our custom checked exception ServerException. The code above handles all of them with a multi-catch which will re-throw them. Since the declared return type of getCause() is Throwable, the compiler requires us to handle that type despite we already handled all possible types. The straight-forward solution is to throw this actually impossible throwable wrapped in an AssertionError.

Alternatively, we could use an alternative result future for our custom exception:

public void myFunc() throws ServerException {
    // Some code
    CompletableFuture<ServerException> exception = new CompletableFuture<>();
    CompletableFuture<A> a = CompletableFuture.supplyAsync(() -> {
        try { return someObj.someFunc(); }
        catch(ServerException ex) {
            exception.complete(ex);
            throw new CompletionException(ex);
        }
    });
    // Some code running in parallel to someFunc()

    A resultOfA;
    try {
        resultOfA = a.join();
    }
    catch(CompletionException ex) {
        if(exception.isDone()) throw exception.join();
        throw ex;
    }

    // some code using resultOfA
}

This solution will re-throw all “unexpected” throwables in their wrapped form, but only throw the custom ServerException in its original form passed via the exception future. Note that we have to ensure that a has been completed (like calling join() first), before we query the exception future, to avoid race conditions.


来源: stackexchange

问:
Not able to install node-sass
I have been trying to install node-sass using npm but it shows a postinstall error. I have already got the latest version of node and npm.

答:
A colleague of mine had exactly the same problem this morning, after upgrading from an old Node.js version (with npm 3.x) to Node.js 8 with npm 5.

What helped here was quite simple:

Delete the node_modules directory

Run npm install to re-install everything again

Maybe it works for you, too.

ContentLicense: CC BY-SA 3.0

Title: Not able to install node-sass


问:
Azure Data Factory: Parameterized the Folder and file path
Environments

Azure Data Factory

Scenario

I have ADF pipeline which reads the data from On premise server and writes the data to azure data lake.

For the same - I have provided Folder structure in ADF*(dataset)*as follows

Folder Path : - DBName/RawTables/Transactional

File Path : -  TableName.csv

Problem

Is it possible to parameterized the Folder name or file path ?  Basically - if tomorrow - I want to change the folder path*(without deployment)* then we should be updating the metadata or table structure.

答:
Mangesh, why don't you try the .Net custom activity in ADF. This custom activity will be your first activity that will potentially check for the processed folder and if the processed folder is present it will move that to History(say) folder. As, ADF is a platform for data movement and data transformation, it doesn't deal with the IO activity. You can learn more about the .Net custom activity at:

https://learn.microsoft.com/en-us/azure/data-factory/data-factory-use-custom-activities


问:
some classes from maven dependency cannot be referenced
I added org.joda.time dependency through maven, and I can reference for example Seconds class from org.joda.time package but I can't DateTime or others. What can cause this behavior? I can browse joda-time-2.9.9.jar in Maven Dependencies and all classes are there.

As you see Seconds class is imported as expected but DateTimeField is not recognized.

答:
First try ALT+F5

If the error persists, try to build the project from the command line (mvn clean package, or through Eclipse as "Run As -> Maven build...").

If the compilation shows errors, fix them (maybe you need another version of your jar or some other jar shadows the classes you need).


问:
how to upload excel file using Java Restful web services and AngularJS
I want to take Excel file from html input type="file" and pass that Excel file to my rest method java by http post method. I have a angular controller for that. I want to know how the controller should look like and what should be there in my rest method. I am using Apache POI to process the excel file. </p>

答:
You can have a angular method like this:

$scope.exelMethod = function (){

var excelObj = {};

excelObj.name = 'test';

excelObj.age = '20';

//you can write '/excel' as a rest web-service

$http.post('/excel,excelObj).success(function(response) {

```<code> console.log(response);// This will be a download path

 //after this call the download function
</code>```

});
}

In the middle layer you can write /excel service and map the excelObj from front end to a class view like this

public class ExcelView{

private String name;

private String age;
}

Now you can use this ExcelView class to map your data using POI. You will have to process the data and pass a download location of the file in the server to FE. In FE you will have to write a download function to download the file from the path you just got from the response.

Body:
You can have a angular method like this:

$scope.exelMethod = function (){

var excelObj = {};

excelObj.name = 'test';

excelObj.age = '20';

//you can write '/excel' as a rest web-service

$http.post('/excel,excelObj).success(function(response) {

 console.log(response);// This will be a download path

 //after this call the download function

});
}

In the middle layer you can write /excel service and map the excelObj from front end to a class view like this

public class ExcelView{

private String name;

private String age;
}

Now you can use this ExcelView class to map your data using POI. You will have to process the data and pass a download location of the file in the server to FE. In FE you will have to write a download function to download the file from the path you just got from the response.


问:
Hide/Remove and Show/Restore options in a Select2 dropdown box
I have an issue where I need to hide or remove options from a select2 dropdown when selected.  These selections fill a list.  I would rather not remove the option because if the user removes it from the freshly populated list then it should return to the dropdown with its place in the order restored.  I've tried the following:

```<code>.select2-results .select2-disabled,  .select2-results__option[aria-disabled=true] {
    display: none;
}

$('#optionId').prop('disabled', true);
</code>```

With the prop being set in the jQuery change block.  I just can't get this piece.

答:
I have figured it out.  If the disable is wrapped like so:

```<code>$(#selectId).select2('destroy');
$(#optionId).prop('disabled', true);
$(#selectId).select2();
</code>```

then the disabled setting will be honored by select2 and the the display none will make the item disappear.  To make it reappear, just follow the same steps with the disabled property set to 'false'.

Body:
I have an issue where I need to hide or remove options from a select2 dropdown when selected.  These selections fill a list.  I would rather not remove the option because if the user removes it from the freshly populated list then it should return to the dropdown with its place in the order restored.  I've tried the following:

.select2-results .select2-disabled,  .select2-results__option[aria-disabled=true] {
    display: none;
}

$('#optionId').prop('disabled', true);

With the prop being set in the jQuery change block.  I just can't get this piece.

Body:
I have figured it out.  If the disable is wrapped like so:

$(#selectId).select2('destroy');
$(#optionId).prop('disabled', true);
$(#selectId).select2();

then the disabled setting will be honored by select2 and the the display none will make the item disappear.  To make it reappear, just follow the same steps with the disabled property set to 'false'.


问:
CSS/HTML5: How to adjust div tag height equal to browser window's current height?
I want the height of my div tag exactly equal to the height of the browser's window. So if you resize the browser the  should adjust automatically.
So what should I set my height equal to in CSS.

I have tried

```<code>.class {
  height: 100%;
}
</code>```

Doesn't work.

em, rem, vh, wh apparently only work with the font.

If I however, hard-code the body tag to some amount of pixels, then the percentage works for the children tags but this is not dynamic.

What I want: Just as I am viewing this stack page in my browser. I wish when I resize the browser I still get the same amount of page viewership, only resized for the new size (responsive).

Thanks.

答:
Your divs parent is the body. height:100% will go as high as the parent. So you need to do this.

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

Body:
I want the height of my div tag exactly equal to the height of the browser's window. So if you resize the browser the  should adjust automatically.
So what should I set my height equal to in CSS.

I have tried

.class {
  height: 100%;
}

Doesn't work.

em, rem, vh, wh apparently only work with the font.

If I however, hard-code the body tag to some amount of pixels, then the percentage works for the children tags but this is not dynamic.

What I want: Just as I am viewing this stack page in my browser. I wish when I resize the browser I still get the same amount of page viewership, only resized for the new size (responsive).

Thanks.

Body:
Your divs parent is the body. height:100% will go as high as the parent. So you need to do this.

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


问:
How to call simulink model(.slx) from script
I'm a super beginner in Simulink models and control systems.
I have .slx Simulink model for drone dynamics system.
It takes in two inputs (roll cmd, pitch cmd) and outputs velocity x, velocity y, position x, and position y.

From here, it seems like I can open the system by calling

```<code>open_system('myModel.slx', 'loadable');
</code>```

But how do I put inputs and get output values?
Is there a way I can do this in a gui?

EDIT:
Here is the full layout of my model:

When I did

```<code>roll_CMD=10;
pitch_CMD=20;
</code>```

I got a warning saying:

```<code>Input port 1 of 'SimpleDroneDynamics/...' is not connected.
</code>```

How do I feed inputs using port numbers?

How do I get outputs with port numbers? I tried

[vx, vy, px, py] = sim('SimpleDroneDynamics.slx');

and got an error saying

```<code>Number of left-hand side argument doesn't match block diagram...
</code>```

Is there a way to continuously feed inputs at every time step? This being controller module, I think I'm supposed to feed in different values based on output position and velocity.

EDIT2:
I'm using Matlab2017a

答:
First of all Simulink model use main Matlab workspace. So you can change your variables values at command window (or just at your script) and run Simulink model.

There are several ways to initialize this constants for Simulink. One more useful way is to create script containing all your variables and load it at Simulink model starts. You can do it by adding script name in Simulink/Model Explorer/Callbacks. (There are different callbacks - on Loading, on Starting and etc.). Read more about this: here.

Now you can run your simulation using sim function:

```<code>sim('name_of_model')
</code>```

name_of_model must contain path if model is not in the active MATLAB folder (active folder you can see in your matlab window just under the main menu).

There are different properties of sim function, read about them in help this can be useful for you. By the way: you can change some parameters of your model using sim. You even can find any block in your model and change it's properties. Read more about sim and about finding current blocks. Interesting that the last solution give you ability to change parameters during the simulation!

About getting output. After you run simulation you get tout variable in main workspace. It is an array of timesteps. But if you add outport block (like at my image) you also get another variable in workspace yout. yout is an Datasets. It contain all your outports values. For 2 outports for example:

```<code>yout

yout =

  Simulink.SimulationData.Dataset
  Package: Simulink.SimulationData

  Characteristics:
          Name: 'yout'
    Total Elements: 2

  Elements:
    1 : ''
    2 : ''
</code>```

Get the values of any of outports:

```<code>yout.get(1).Values
</code>```

it is a timeseries data type, so:

yout.get(1).Values.Time - give you times

yout.get(2).Values.Data - give you values of this outport at each time

We have one more method to take output values:

```<code>[t,x,y] = sim('model_name')
</code>```

it returns double arrays. t- time array, y - matrix of all outports values (it already double and contain only values without times, but for each simulation time!)

So now you can create common Matlab GUI and work at this variables! There is no any difficulties. You can read more about GUI for Simulink here.

Body:
I'm a super beginner in Simulink models and control systems.
I have .slx Simulink model for drone dynamics system.
It takes in two inputs (roll cmd, pitch cmd) and outputs velocity x, velocity y, position x, and position y.

From here, it seems like I can open the system by calling

open_system('myModel.slx', 'loadable');

But how do I put inputs and get output values?
Is there a way I can do this in a gui?

EDIT:
Here is the full layout of my model:

When I did

roll_CMD=10;
pitch_CMD=20;

I got a warning saying:

Input port 1 of 'SimpleDroneDynamics/...' is not connected.

How do I feed inputs using port numbers?

How do I get outputs with port numbers? I tried

[vx, vy, px, py] = sim('SimpleDroneDynamics.slx');

and got an error saying

Number of left-hand side argument doesn't match block diagram...

Is there a way to continuously feed inputs at every time step? This being controller module, I think I'm supposed to feed in different values based on output position and velocity.

EDIT2:
I'm using Matlab2017a

Body:
First of all Simulink model use main Matlab workspace. So you can change your variables values at command window (or just at your script) and run Simulink model.

There are several ways to initialize this constants for Simulink. One more useful way is to create script containing all your variables and load it at Simulink model starts. You can do it by adding script name in Simulink/Model Explorer/Callbacks. (There are different callbacks - on Loading, on Starting and etc.). Read more about this: here.

Now you can run your simulation using sim function:

sim('name_of_model')

name_of_model must contain path if model is not in the active MATLAB folder (active folder you can see in your matlab window just under the main menu).

There are different properties of sim function, read about them in help this can be useful for you. By the way: you can change some parameters of your model using sim. You even can find any block in your model and change it's properties. Read more about sim and about finding current blocks. Interesting that the last solution give you ability to change parameters during the simulation!

About getting output. After you run simulation you get tout variable in main workspace. It is an array of timesteps. But if you add outport block (like at my image) you also get another variable in workspace yout. yout is an Datasets. It contain all your outports values. For 2 outports for example:

yout

yout =

  Simulink.SimulationData.Dataset
  Package: Simulink.SimulationData

  Characteristics:
          Name: 'yout'
    Total Elements: 2

  Elements:
    1 : ''
    2 : ''

Get the values of any of outports:

yout.get(1).Values

it is a timeseries data type, so:

yout.get(1).Values.Time - give you times

yout.get(2).Values.Data - give you values of this outport at each time

We have one more method to take output values:

[t,x,y] = sim('model_name')

it returns double arrays. t- time array, y - matrix of all outports values (it already double and contain only values without times, but for each simulation time!)

So now you can create common Matlab GUI and work at this variables! There is no any difficulties. You can read more about GUI for Simulink here.


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

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

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

答:
Iterate through it and count the elements which aren't null:

```<code>int counter = 0;
for (int i = 0; i < theArray.length; i ++)
    if (theArray[i] != null)
        counter ++;
</code>```

This can be neatened up by using for:each loops and suchlike, but this is the jist.

Either that, or keep a counter and whenever you add an element, increment it.

Body:
Say i have the array

int theArray = new int[20];

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

Body:
Iterate through it and count the elements which aren't null:

int counter = 0;
for (int i = 0; i < theArray.length; i ++)
    if (theArray[i] != null)
        counter ++;

This can be neatened up by using for:each loops and suchlike, but this is the jist.

Either that, or keep a counter and whenever you add an element, increment it.

ContentLicense: CC BY-SA 2.5


问:
Fossil JSON API: How to create a wiki page?
I've been trying to create a wiki page, ufollowing the documentation of the Fossil JSON API. When I put the URL http://myrepo.top/json/wiki/create?name=test I get and answer similar to:

{"fossil":"81d7d3f43ebd4e77095cfbacee7ebc9ae043a014760cde56d437dbd8b6a37c92","timestamp":1496771043,"resultCode":"FOSSIL-3002","resultText":"'name' parameter is missing.","command":"wiki/create","procTimeUs":4000,"procTimeMs":4}

I don't know how the page name is supposed to be given in the URL. I was imagining that was similar to the way you query wiki pages, but seems that the API is expecting something different. Could someone show me the proper way of adding the page name to the Fossil JSON API URL?

Thanks,

答:
Looking at the source code, it would seem you need to send the new wiki page name in the body of the POST request:

```<code>{ name: "test"
, content: "# Test\n\nThis is a test page."
, mimetype: "text/x-markdown"
}
</code>```

If I read the code correctly, both name and content need to be specified in the JSON body, but the mimetype can be specified either as a GET parameter, or in the JSON body.

Disclaimer: I haven't tested this code, since I have no JSON-enabled instance of Fossil at hand.

Body:
Looking at the source code, it would seem you need to send the new wiki page name in the body of the POST request:

{ name: "test"
, content: "# Test\n\nThis is a test page."
, mimetype: "text/x-markdown"
}

If I read the code correctly, both name and content need to be specified in the JSON body, but the mimetype can be specified either as a GET parameter, or in the JSON body.

Disclaimer: I haven't tested this code, since I have no JSON-enabled instance of Fossil at hand.


问:
Failed to find configured root error in android 7.0
I get this error: failed to find configured root that contains /storage/emulated/0/android/data/
There are some similar questions but they are using other location for storing files.
I am using:
   Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)  method and this is the code I'm using to open camera:

```<code> private void TakePicture() {
    photoFile = FileManager.generateFileStampedPhotoFile();
    PicturesHelper.TryTakePictureWithAnIntent(this, photoFile, REQUEST_IMAGE_CAPTURE);
}

public static File generateFileStampedPhotoFile()
{
    Uri photoFileUri=null;
    File photoFile=null;
    File outputDir=getPhotoDirectory();
    if(outputDir!=null)
    {
        String timeStamp=new SimpleDateFormat("yyyyMMDD_HHmmss").format(new Date());
        String photoFileName="IMG_"+timeStamp+".jpg";
         photoFile=new File(outputDir,photoFileName);
       // photoFileUri=Uri.fromFile(photoFile);

    }
    return  photoFile;
}

 public static void TryTakePictureWithAnIntent(Activity context,File
   photoFile,int requestCode)
  {
    Intent takePictureIntent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    if(takePictureIntent.resolveActivity(context.getPackageManager())!=null) //if user has camera?
    {

        if (photoFile != null) {
            Uri photoURI = FileProvider.getUriForFile(context,
                    "com.myapp.fileprovider",
                    photoFile);
            takePictureIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            takePictureIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);

            context.startActivityForResult(takePictureIntent, requestCode);
        }

    }
}

public static File getPhotoDirectory()
{
    File outputDir=null;
    String externalStorageState=Environment.getExternalStorageState();
    if(externalStorageState.equals(Environment.MEDIA_MOUNTED)) {
        File pictureDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        outputDir=new File(new File(pictureDir,"Adriagate"),"Online");
        if(!outputDir.exists())//V.P. if directory/ies not exist/s it will be created. mksdrs method follows file structure and creates directory by direcory if needed
        {
            if(!outputDir.mkdirs())
            {
                return null;
            }
        }
    }
    return outputDir;
}
</code>```

I have put provider inside AndroidManifest:

```<code>  <provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="com.myapp.fileprovider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/file_paths"></meta-data>
    </provider>
</code>```

And this is file_paths.xml file:

```<code><?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-files name="Whatever_Nothing_Works"/>
</code>```

答:
You are storing your images in Environment.getExternalStoragePublicDirectory(). That is not one of the supported roots for FileProvider. Plus, your XML has <external-files>, and that is not a supported element for FileProvider (valid ones all end in -path).

Options include:

Changing the location of where you are storing the images to one of the locations supported by FileProvider and adjusting your XML to match

Switching to my StreamProvider and using <external-public-path dir="Pictures">

Changing your XML to <external-path name="whatever" path="Pictures"> and hope for the best

Body:
I get this error: failed to find configured root that contains /storage/emulated/0/android/data/
There are some similar questions but they are using other location for storing files.
I am using:
   Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)  method and this is the code I'm using to open camera:

 private void TakePicture() {
    photoFile = FileManager.generateFileStampedPhotoFile();
    PicturesHelper.TryTakePictureWithAnIntent(this, photoFile, REQUEST_IMAGE_CAPTURE);
}

public static File generateFileStampedPhotoFile()
{
    Uri photoFileUri=null;
    File photoFile=null;
    File outputDir=getPhotoDirectory();
    if(outputDir!=null)
    {
        String timeStamp=new SimpleDateFormat("yyyyMMDD_HHmmss").format(new Date());
        String photoFileName="IMG_"+timeStamp+".jpg";
         photoFile=new File(outputDir,photoFileName);
       // photoFileUri=Uri.fromFile(photoFile);

    }
    return  photoFile;
}

 public static void TryTakePictureWithAnIntent(Activity context,File
   photoFile,int requestCode)
  {
    Intent takePictureIntent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    if(takePictureIntent.resolveActivity(context.getPackageManager())!=null) //if user has camera?
    {

        if (photoFile != null) {
            Uri photoURI = FileProvider.getUriForFile(context,
                    "com.myapp.fileprovider",
                    photoFile);
            takePictureIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            takePictureIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);

            context.startActivityForResult(takePictureIntent, requestCode);
        }

    }
}

public static File getPhotoDirectory()
{
    File outputDir=null;
    String externalStorageState=Environment.getExternalStorageState();
    if(externalStorageState.equals(Environment.MEDIA_MOUNTED)) {
        File pictureDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        outputDir=new File(new File(pictureDir,"Adriagate"),"Online");
        if(!outputDir.exists())//V.P. if directory/ies not exist/s it will be created. mksdrs method follows file structure and creates directory by direcory if needed
        {
            if(!outputDir.mkdirs())
            {
                return null;
            }
        }
    }
    return outputDir;
}

I have put provider inside AndroidManifest:

  <provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="com.myapp.fileprovider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/file_paths"></meta-data>
    </provider>

And this is file_paths.xml file:

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-files name="Whatever_Nothing_Works"/>


问:
UIView Rotation using swift issue
I would like to rotate UIView which defined on the storyboard I used

```<code>CGAffineTransform(rotationAngle: self.degreesToRadians(5))
</code>```

which degreesToradians a function to convert to Radians, the rotation is working perfectly but the only problem is the UIView not vectorial (the edge of the view is not rendered properly and it looks like a saw) like in the screenshot below :

答:
I have had the same problems as you and to solve it I just add a border to the view which is transparent, do it like this:

```<code>customView.layer.borderWidth = 1
customView.layer.borderColor = UIColor.clear.cgColor // important that it is clear
customView.layer.shouldRasterize = true
customView.layer.rasterizationScale = UIScreen.main.scale
</code>```

Add that code after your rotation code.

With the code:

Without the code:

Title: UIView Rotation using swift issue

Body:
I would like to rotate UIView which defined on the storyboard I used

CGAffineTransform(rotationAngle: self.degreesToRadians(5))

which degreesToradians a function to convert to Radians, the rotation is working perfectly but the only problem is the UIView not vectorial (the edge of the view is not rendered properly and it looks like a saw) like in the screenshot below :

Body:
I have had the same problems as you and to solve it I just add a border to the view which is transparent, do it like this:

customView.layer.borderWidth = 1
customView.layer.borderColor = UIColor.clear.cgColor // important that it is clear
customView.layer.shouldRasterize = true
customView.layer.rasterizationScale = UIScreen.main.scale

Add that code after your rotation code.

With the code:

Without the code:


问:
Fetch by mulitple record ordering with custom fields
I have some problem in fetching records with multiple ordering. For this i have write query but problem is that, in one ordering i have custom fields. I want to order by custom values and normal ordering both.

// Query

```<code>select id, name, f_name, catg, form_no, address, mobile, grp, prt_no, reg_amt, adm_chg,
       flat_detail
from mst_app
where mobile = ?
order by block,level,flat_no
</code>```

I want to add custom value on level column.

Any one can help me to solve this problem.

Thanks

答:
I think you want conditional order by for level column.. Then you can use case function...</p>

```<code>ORDER BY
CASE
   WHEN level <> 0 THEN level
END desc
</code>```

Body:
I have some problem in fetching records with multiple ordering. For this i have write query but problem is that, in one ordering i have custom fields. I want to order by custom values and normal ordering both.

// Query

select id, name, f_name, catg, form_no, address, mobile, grp, prt_no, reg_amt, adm_chg,
       flat_detail
from mst_app
where mobile = ?
order by block,level,flat_no

I want to add custom value on level column.

Any one can help me to solve this problem.

Thanks

Body:
I think you want conditional order by for level column.. Then you can use case function...

ORDER BY
CASE
   WHEN level <> 0 THEN level
END desc


问:
Upload image and text field to server multipart data in iOS objective c
I'm trying to upload the image file and three four text fields and I am receiving all the text fields in the server and I am not getting image name or image on the server. Below is my code:

```<code>- (IBAction)continueb:(id)sender {

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://test.kre8tives.com/barebon/customer_registerapi.php"]];

NSData *imageData = UIImageJPEGRepresentation(self.profilei.image, 1.0);

[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:60];
[request setHTTPMethod:@"POST"];

NSString *boundary = @"unique-consistent-string";

// set Content-Type in HTTP header
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
[request setValue:contentType forHTTPHeaderField: @"Content-Type"];

// post body
NSMutableData *body = [NSMutableData data];

NSString *test = [NSString stringWithFormat:@"+91%@cache",self.mobilestrp]; //Image name if you want a custom name

// add image data

if (imageData){
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"%@%@%@", @"Content-Disposition: form-data; name=\"image\"; filename=\"%@",test,@".png\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[@"Content-Type: image/png\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:imageData];
    [body appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
}

//  parameter username
[body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"customer_name\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"%@",_nametf.text dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

//  parameter phone
[body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"phone\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"%@",self.mobilestrp dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];

//  parameter email
[body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"email\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"%@",_emailtf.text dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

//  parameter dob
[body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"dob\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"%@",_dobtf.text dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];

// setting the body of the post to the reqeust
[request setHTTPBody:body];

// set the content-length
NSString *postLength = [NSString stringWithFormat:@"%d", [body length]];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];

[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
       NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]; // this is json string
    if(data.length > 0)
    {
        NSLog(@ "success:%@",requestReply);
        NSLog(@"data:%@",data);
    }
}];
[self performSegueWithIdentifier:@"b3" sender:self];
}
</code>```

above is my action button in this I am getting four text fields from the user and using image picker I am setting profile picture and that profile picture is stored in UIImage profile and I am not able to figure out what is the problem

below is my log:-

2017-06-07 11:08:34.737734+0530 MenuBar[1485:80176]
  [MobileAssetError:29] Unable to copy asset information from
  https://mesu.apple.com/assets/ for asset type
  com.apple.MobileAsset.TextInput.SpellChecker
      2017-06-07 11:08:56.007 MenuBar[1485:80118] success:/tmp/phpTMFhjM9047038606akshay1318a@gmail,com18-01-1995
      2017-06-07 11:08:59.622 MenuBar[1485:80118] data:<2f746d70 2f706870 544d4668 6a4d3930 34373033 38363036 616b7368 61793133
  31386140 676d6169 6c2c636f 6d31382d 30312d31 393935>

I have changed my PHP code to return whatever I get from the request to check the working of the request and I got the above reply from the request

答:
if you want to send multipart data to server you can use below code

```<code>NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"YOUR URL"]];

NSData *imageData = UIImageJPEGRepresentation(self.profilei.image, 1.0);

[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:60];
[request setHTTPMethod:@"POST"];

NSString *boundary = @"unique-consistent-string";

// set Content-Type in HTTP header
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
[request setValue:contentType forHTTPHeaderField: @"Content-Type"];

// post body
NSMutableData *body = [NSMutableData data];

//Image name if you want a custom name
NSString *test = [NSString stringWithFormat:@"your custom name"];

// add image data

if (imageData){
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"%@%@%@", @"Content-  Disposition: form-data; name=\"image\"; filename=\"%@",test,@".png\"\r\n"]   dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Type: image/png\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:imageData];
[body appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
}

//  parameter username
[body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"customer_name\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"%@",_nametf.text dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

//  parameter phone
[body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"phone\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"%@",self.mobilestrp dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];

//  parameter email
[body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"email\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"%@",_emailtf.text dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

//  parameter dob
[body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"dob\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"%@",_dobtf.text dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];

// setting the body of the post to the reqeust
[request setHTTPBody:body];

// set the content-length
NSString *postLength = [NSString stringWithFormat:@"%d", [body length]];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];

[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
   NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]; // this is json string
 if(data.length > 0)
{
    NSLog(@ "success:%@",requestReply);
    NSLog(@"data:%@",data);
}
}];
[self performSegueWithIdentifier:@"b3" sender:self];
}
</code>```

I have explained above how the method works!!

Body:
I'm trying to upload the image file and three four text fields and I am receiving all the text fields in the server and I am not getting image name or image on the server. Below is my code:

- (IBAction)continueb:(id)sender {

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://test.kre8tives.com/barebon/customer_registerapi.php"]];

NSData *imageData = UIImageJPEGRepresentation(self.profilei.image, 1.0);

[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:60];
[request setHTTPMethod:@"POST"];

NSString *boundary = @"unique-consistent-string";

// set Content-Type in HTTP header
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
[request setValue:contentType forHTTPHeaderField: @"Content-Type"];

// post body
NSMutableData *body = [NSMutableData data];

NSString *test = [NSString stringWithFormat:@"+91%@cache",self.mobilestrp]; //Image name if you want a custom name

// add image data

if (imageData){
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"%@%@%@", @"Content-Disposition: form-data; name=\"image\"; filename=\"%@",test,@".png\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[@"Content-Type: image/png\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:imageData];
    [body appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
}

//  parameter username
[body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"customer_name\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"%@",_nametf.text dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

//  parameter phone
[body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"phone\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"%@",self.mobilestrp dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];

//  parameter email
[body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"email\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"%@",_emailtf.text dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

//  parameter dob
[body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"dob\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"%@",_dobtf.text dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];

// setting the body of the post to the reqeust
[request setHTTPBody:body];

// set the content-length
NSString *postLength = [NSString stringWithFormat:@"%d", [body length]];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];

[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
       NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]; // this is json string
    if(data.length > 0)
    {
        NSLog(@ "success:%@",requestReply);
        NSLog(@"data:%@",data);
    }
}];
[self performSegueWithIdentifier:@"b3" sender:self];
}

above is my action button in this I am getting four text fields from the user and using image picker I am setting profile picture and that profile picture is stored in UIImage profile and I am not able to figure out what is the problem

below is my log:-

2017-06-07 11:08:34.737734+0530 MenuBar[1485:80176]
  [MobileAssetError:29] Unable to copy asset information from
  https://mesu.apple.com/assets/ for asset type
  com.apple.MobileAsset.TextInput.SpellChecker
      2017-06-07 11:08:56.007 MenuBar[1485:80118] success:/tmp/phpTMFhjM9047038606akshay1318a@gmail,com18-01-1995
      2017-06-07 11:08:59.622 MenuBar[1485:80118] data:<2f746d70 2f706870 544d4668 6a4d3930 34373033 38363036 616b7368 61793133
  31386140 676d6169 6c2c636f 6d31382d 30312d31 393935>

I have changed my PHP code to return whatever I get from the request to check the working of the request and I got the above reply from the request

Body:
if you want to send multipart data to server you can use below code

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"YOUR URL"]];

NSData *imageData = UIImageJPEGRepresentation(self.profilei.image, 1.0);

[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:60];
[request setHTTPMethod:@"POST"];

NSString *boundary = @"unique-consistent-string";

// set Content-Type in HTTP header
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
[request setValue:contentType forHTTPHeaderField: @"Content-Type"];

// post body
NSMutableData *body = [NSMutableData data];

//Image name if you want a custom name
NSString *test = [NSString stringWithFormat:@"your custom name"];

// add image data

if (imageData){
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"%@%@%@", @"Content-  Disposition: form-data; name=\"image\"; filename=\"%@",test,@".png\"\r\n"]   dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Type: image/png\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:imageData];
[body appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
}

//  parameter username
[body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"customer_name\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"%@",_nametf.text dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

//  parameter phone
[body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"phone\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"%@",self.mobilestrp dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];

//  parameter email
[body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"email\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"%@",_emailtf.text dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

//  parameter dob
[body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"dob\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"%@",_dobtf.text dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];

// setting the body of the post to the reqeust
[request setHTTPBody:body];

// set the content-length
NSString *postLength = [NSString stringWithFormat:@"%d", [body length]];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];

[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
   NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]; // this is json string
 if(data.length > 0)
{
    NSLog(@ "success:%@",requestReply);
    NSLog(@"data:%@",data);
}
}];
[self performSegueWithIdentifier:@"b3" sender:self];
}

I have explained above how the method works!!


问:
how to find row from numeric cell that contain target vector in Matlab?
I have cell array that is as follow:

```<code>S{1} = [10,20,30,40,50];
S{2} = [10,20,40,50];
S{3} = [10,50,510];
S{4} = [10,20,70,40,60];
S{5} = [20,40];
</code>```

and,i have a target vector:

```<code>T=[10,70]
</code>```

i need to find rows of cell that T is subitem of those.
for above example result is : 4

because T is  subitems of row 4.

答:
Get the count of matches for each cell against T and see which cells have a match count being equal to the number of elements in T, indicating that those cells have all elements from T. The assumption here is that we have unique elements in each of those cells.

Here's the implementation -

```<code>find(cellfun(@(x) nnz(ismember(x, T)), S) == numel(T))
</code>```

Or as suggested by @Leander Moesinger we can get the matches for each element off T across all elements in each cell and then simply use all(), like so -

```<code>find(cellfun(@(x) all(ismember(T,x)),S))
</code>```

Body:
I have cell array that is as follow:

S{1} = [10,20,30,40,50];
S{2} = [10,20,40,50];
S{3} = [10,50,510];
S{4} = [10,20,70,40,60];
S{5} = [20,40];

and,i have a target vector:

T=[10,70]

i need to find rows of cell that T is subitem of those.
for above example result is : 4

because T is  subitems of row 4.

Body:
Get the count of matches for each cell against T and see which cells have a match count being equal to the number of elements in T, indicating that those cells have all elements from T. The assumption here is that we have unique elements in each of those cells.

Here's the implementation -

find(cellfun(@(x) nnz(ismember(x, T)), S) == numel(T))

Or as suggested by @Leander Moesinger we can get the matches for each element off T across all elements in each cell and then simply use all(), like so -

find(cellfun(@(x) all(ismember(T,x)),S))


问:
Stateful testing gives hypothesis.errors.Flaky: Run failed initially but succeeded on a second try
I am trying to solve a puzzle using Hypothesis similar to what has been done here:

http://nchammas.com/writing/how-not-to-die-hard-with-hypothesis

Unfortunately it fails intermittently with the Flaky error and I am not able to track down the problem using pdb.

My program source is at:

https://gist.github.com/sureshvv/0fb78ef221fb8c1ed85dd034c83abefa

It can be run using py.test.

Any assistance to diagnose and solve the problem appreciated.

答: Problem was caused because of calling random.sample inside my rule. Need to use the strategies.choices() instead.</p>


问:
R- programming - Error in seq.default(a, length = max(0, b - a - 1)) : length must be non-negative number
I tried running the code below.

```<code>library(sfsmisc)
set.seed(307)
y  <- rnorm(200)
h2 <- 0.3773427

t   <- seq(-3.317670,  2.963407, length.out=500)
fit <- density(y, bw=h2, n=1024, kernel="epanechnikov")

integrate.xy(fit$x, fit$y, min(fit$x), t[407])
</code>```

However, i received the following message:

"Error in seq.default(a, length = max(0, b - a - 1)) :
    length must be non-negative number".

I am not sure what's wrong.

I do not encounter any problem when i use t[406] or t[408] as follow:

```<code>integrate.xy(fit$x, fit$y, min(fit$x), t[406])
integrate.xy(fit$x, fit$y, min(fit$x), t[408])
</code>```

Does anyone know what's the problem and how to fix it? Appreciate your help, thanks!

答:
thanks for your suggestion. I tried the method and no longer see the error for the above simulation with set.seed(307). However, the error still occur when I tried to run the following code:

```<code>for (i in 1:2000) {
print(i)
set.seed(i)
y  <- rnorm(200)
h2 <- 0.3773427

t   <- seq(-3.317670,  2.963407, length.out=500)
fit <- density(y, bw=h2, n=1024, kernel="epanechnikov")

integrate.xy(fit$x, fit$y, min(fit$x), t[407],xtol=3.16228e-7)
}
</code>```

The same occur when i use xtol=4.16228e-6.

Is there a way to resolve the issue so that I won't run into this problem?

OwnerDisplayName: Rainey

Body:
I tried running the code below.

library(sfsmisc)
set.seed(307)
y  <- rnorm(200)
h2 <- 0.3773427

t   <- seq(-3.317670,  2.963407, length.out=500)
fit <- density(y, bw=h2, n=1024, kernel="epanechnikov")

integrate.xy(fit$x, fit$y, min(fit$x), t[407])

However, i received the following message:

"Error in seq.default(a, length = max(0, b - a - 1)) :
    length must be non-negative number".

I am not sure what's wrong.

I do not encounter any problem when i use t[406] or t[408] as follow:

integrate.xy(fit$x, fit$y, min(fit$x), t[406])
integrate.xy(fit$x, fit$y, min(fit$x), t[408])

Does anyone know what's the problem and how to fix it? Appreciate your help, thanks!

Body:
thanks for your suggestion. I tried the method and no longer see the error for the above simulation with set.seed(307). However, the error still occur when I tried to run the following code:

for (i in 1:2000) {
print(i)
set.seed(i)
y  <- rnorm(200)
h2 <- 0.3773427

t   <- seq(-3.317670,  2.963407, length.out=500)
fit <- density(y, bw=h2, n=1024, kernel="epanechnikov")

integrate.xy(fit$x, fit$y, min(fit$x), t[407],xtol=3.16228e-7)
}

The same occur when i use xtol=4.16228e-6.

Is there a way to resolve the issue so that I won't run into this problem?


问:
How to get the current products in cart in Magento?

I need to get the currently products in cart to estimate how many
  products are in ? I used the below code but it gave me this error
  message
  > Fatal error: Call to undefined method
  Mage_Sales_Model_Resource_Quote_Item_Collection::getAllItems()

Code:

```<code>    <?php

      require 'app/Mage.php';
      Mage::app();

     if (!Mage::isInstalled()) {
        echo "Application is not installed yet, please complete install wizard first.";

}

     $cart =Mage::getSingleton('checkout/cart')->getQuote()->getItemsCollection();
           foreach ($cart->getAllItems() as $item) {
                   $productName = $item->getProduct()->getName();
                   $productPrice = $item->getProduct()->getPrice();

          print($item);

}
</code>```

答:
There is a problem in your code :

```<code>$cart =Mage::getSingleton('checkout/cart')->getQuote()->getItemsCollection();
</code>```

It should be :

```<code>$cart = Mage::getSingleton('checkout/cart');
$quote = $cart->getQuote();
foreach ($quote->getAllItems() as $item) {
      $productName = $item->getProduct()->getName();
      $productPrice = $item->getProduct()->getPrice();

      print($item);
}
</code>```

Body:
I need to get the currently products in cart to estimate how many
  products are in ? I used the below code but it gave me this error
  message
  > Fatal error: Call to undefined method
  Mage_Sales_Model_Resource_Quote_Item_Collection::getAllItems()

Code:

    <?php

      require 'app/Mage.php';
      Mage::app();

     if (!Mage::isInstalled()) {
        echo "Application is not installed yet, please complete install wizard first.";

}

     $cart =Mage::getSingleton('checkout/cart')->getQuote()->getItemsCollection();
           foreach ($cart->getAllItems() as $item) {
                   $productName = $item->getProduct()->getName();
                   $productPrice = $item->getProduct()->getPrice();

          print($item);

}

Body:
There is a problem in your code :

$cart =Mage::getSingleton('checkout/cart')->getQuote()->getItemsCollection();

It should be :

$cart = Mage::getSingleton('checkout/cart');
$quote = $cart->getQuote();
foreach ($quote->getAllItems() as $item) {
      $productName = $item->getProduct()->getName();
      $productPrice = $item->getProduct()->getPrice();

      print($item);
}


问:
I need help debugging pls
```<code># make a list

shopping_list = []

# print instructions how to use app

print("what should we pick up at store")
print("Enter 'DONE' to stop adding items")

while True:
    # ask for new items
    new_item = input("> ")

    # quit app
    if new_item == "DONE":
        break

    # add new items to list
    shopping_list.append(new_item)

# print out app
print("Here's your list:")

for item in shopping_list:
    print(item)
</code>```

答:
Based on the exception I am getting,
If you are using python 2 use raw_input('> ')
and if you are using python3 use str(input('> '))

Title: I need help debugging pls


问:
Match within string, but ignore matches between brackets - Regex and JavaScript
I have the following string examples:

```<code> "1. go [south], but look out for the trout pouting [lout]"
 "2. go [south], but be wary of the pouting [lout]"
 "3. go [south], but be wary of the sullen-looking [lout]"
</code>```

I'd like the query word out to match if it appears in each string, but is ignored if it's between brackets. So I'm looking to match:

True for out, trout, and pouting

True for pouting

False

I've managed to get as far as this expression:

```<code>/[^\(\)\[\]]out\s(?![\]])/ig
</code>```

However, it's only matching the first string for out and trout .

I've figured out that the whitespace character is the influencing factor here for not matching pouting, but getting rid of it matches everything between the brackets, too.

What would be the correct regular expression for this?

答:
Assuming [...] are balanced and unescaped, you can use a negative lookahead based search:

```<code>/out(?![^\[\]]*\])/
</code>```

(?![^\[\]]*\]) is a negative lookahead that asserts that we don't have a ] following non-[ and non-] characters ahead thus making sure we're not matching out inside a [...].

Javascript code to build your regex:

```<code>search = "out";
var regex = new RexExp(search + "(?![^\\[\\]]*\\])", "g");
</code>```

RegEx Demo

Body:
I have the following string examples:

 "1. go [south], but look out for the trout pouting [lout]"
 "2. go [south], but be wary of the pouting [lout]"
 "3. go [south], but be wary of the sullen-looking [lout]"

I'd like the query word out to match if it appears in each string, but is ignored if it's between brackets. So I'm looking to match:

True for out, trout, and pouting

True for pouting

False

I've managed to get as far as this expression:

/[^\(\)\[\]]out\s(?![\]])/ig

However, it's only matching the first string for out and trout .

I've figured out that the whitespace character is the influencing factor here for not matching pouting, but getting rid of it matches everything between the brackets, too.

What would be the correct regular expression for this?

Body:
Assuming [...] are balanced and unescaped, you can use a negative lookahead based search:

/out(?![^\[\]]*\])/

(?![^\[\]]*\]) is a negative lookahead that asserts that we don't have a ] following non-[ and non-] characters ahead thus making sure we're not matching out inside a [...].

Javascript code to build your regex:

search = "out";
var regex = new RexExp(search + "(?![^\\[\\]]*\\])", "g");

RegEx Demo


问:
check if function is a generator
I played with generators in Nodejs v0.11.2 and I'm wondering
how I can check that argument to my function is generator function.

I found this way typeof f === 'function' && Object.getPrototypeOf(f) !== Object.getPrototypeOf(Function) but I'm not sure if this is good (and working in future) way.

What is your opinion about this issue?

答:
I checked how koa does it and they use this library: https://github.com/ljharb/is-generator-function.

You can use it like this

```<code>const isGeneratorFunction = require('is-generator-function');
if(isGeneratorFunction(f)) {
    ...
}
</code>```

Title: check if function is a generator

Body:
I checked how koa does it and they use this library: https://github.com/ljharb/is-generator-function.

You can use it like this

const isGeneratorFunction = require('is-generator-function');
if(isGeneratorFunction(f)) {
    ...
}


问:
Reverting animation done with AnimatorSet
I am creating an animation with AnimatorSet and when it ends I would like to leave the View where it was.

The code is something like this:

```<code>mLastAnimation = new AnimatorSet();
mLastAnimation.playTogether(
  ObjectAnimator.ofFloat(mImageView, "scaleX", 1.5f, 1f),
  ObjectAnimator.ofFloat(mImageView, "translationY", 40f, 0f));
mLastAnimation.setDuration(3000);
mLastAnimation.addListener(this);
mLastAnimation.start();

// The Activity implements the AnimatorListener interface
  @Override
  public void onAnimationEnd(Animator animator) {
    // Undo the animation changes to the view.
  }
</code>```

EDIT:

I am using the new animation API so setFillAfter() will not work here.

答:
While using ObjectAnimator you can simply set

```<code>android:repeatMode="reverse"
</code>```

Body:
I am creating an animation with AnimatorSet and when it ends I would like to leave the View where it was.

The code is something like this:

mLastAnimation = new AnimatorSet();
mLastAnimation.playTogether(
  ObjectAnimator.ofFloat(mImageView, "scaleX", 1.5f, 1f),
  ObjectAnimator.ofFloat(mImageView, "translationY", 40f, 0f));
mLastAnimation.setDuration(3000);
mLastAnimation.addListener(this);
mLastAnimation.start();

// The Activity implements the AnimatorListener interface
  @Override
  public void onAnimationEnd(Animator animator) {
    // Undo the animation changes to the view.
  }

EDIT:

I am using the new animation API so setFillAfter() will not work here.

Body:
While using ObjectAnimator you can simply set

android:repeatMode="reverse"


问:
Problems Building Application as Release in Visual Studio 2008 - C++
I'm having a little trouble building my application as Release in Visual Studio 2008.  It builds fine without any errors or warning as Debug.  The application is primarily Win32 with a little MFC and ATL mixed in here and there.  Most of the projects in the solution generate a LIB and DLL.

This is one of the errors I am getting:

fatal error C1189: #error :  Building MFC application with /MD[d] (CRT dll version) requires MFC shared dll version. Please #define _AFXDLL or do not use /MD[d]

My application is a multithreaded DLL, so the /MD needs to stay.  The only Windows includes are these:

```<code>#include "stdafx.h"
#include "afx.h"
#include "WMIQuery.h"
#include "SerialPort.h"
</code>```

The other error is this:

fatal error C1083: Cannot open include file: 'WMIQuery.h': No such file or directory

This one really doesn't make sense to me because, the environment has no problem finding this file building for Debug.

Does anyone know how to fix this?  If any additional information is needed, just say so, and I'll post.  Thanks.

答:
The first error is most likely a mismatch in your project settings. Since you require /MD, check your project configuration properties for release, under the 'General' heading. There should be an item "Use of MFC". This should be set to "Use MFC in a Shared DLL".

The second error is probably due to a mismatch in include paths between the two configurations.

Body:
I'm having a little trouble building my application as Release in Visual Studio 2008.  It builds fine without any errors or warning as Debug.  The application is primarily Win32 with a little MFC and ATL mixed in here and there.  Most of the projects in the solution generate a LIB and DLL.

This is one of the errors I am getting:

fatal error C1189: #error :  Building MFC application with /MD[d] (CRT dll version) requires MFC shared dll version. Please #define _AFXDLL or do not use /MD[d]

My application is a multithreaded DLL, so the /MD needs to stay.  The only Windows includes are these:

#include "stdafx.h"
#include "afx.h"
#include "WMIQuery.h"
#include "SerialPort.h"

The other error is this:

fatal error C1083: Cannot open include file: 'WMIQuery.h': No such file or directory

This one really doesn't make sense to me because, the environment has no problem finding this file building for Debug.

Does anyone know how to fix this?  If any additional information is needed, just say so, and I'll post.  Thanks.


问:
Color in link tag doesn't work but color in div in link tag works?
Why doesn't this work (in terms of text color):

```<code>.navbarDivText {
    color: #DAA520;
}
.navbarDiv {
    width: 150px;
    background-color: inherit;
    margin-left: 10px;
}

<li class="navbarDiv" >
   <a href="index.php" class = "navbarDivText">Main Page</a>
</li>
</code>```

But this does:

```<code><li class="navbarDiv" >
   <a href="index.php">
     <div class = "navbarDivText">Main Page</div>
   </a>
 </li>
</code>```

答:
In this there are two cases if you give the color for list it will change the color of list and the anchor remained blue by default with underline.

If you also want to to change the color of anchor in a list you should have also give the styling for anchor means text-decoration and color whatever style you want.

See example here hope this will help you. Link

More demo: Here

Body:
Why doesn't this work (in terms of text color):

.navbarDivText {
    color: #DAA520;
}
.navbarDiv {
    width: 150px;
    background-color: inherit;
    margin-left: 10px;
}

   Main Page

But this does:

Main Page


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

Any settings to speed up fetching table data in DBeaver?

答:
Changing following settings in your oracle db connection will be faster fetching table data than it's not set.

Right click on your db connection --> Edit Connection --> Oracle properties --> tick on 'Use RULE hint for system catalog queries'
(by default this is not set)

UPDATE

In the newer version (21.0.0) of DBeaver, many more performance options appear here. Turning on them significantly improves the performance for me

ContentLicense: CC BY-SA 4.0


问:
CSS/HTML5: How to adjust div tag height equal to browser window's current height?
I want the height of my div tag exactly equal to the height of the browser's window. So if you resize the browser the  should adjust automatically.
So what should I set my height equal to in CSS.

I have tried

```<code>.class {
  height: 100%;
}
</code>```

Doesn't work.

em, rem, vh, wh apparently only work with the font.

If I however, hard-code the body tag to some amount of pixels, then the percentage works for the children tags but this is not dynamic.

What I want: Just as I am viewing this stack page in my browser. I wish when I resize the browser I still get the same amount of page viewership, only resized for the new size (responsive).

Thanks.

答:
You want to add vh so something like this.

```<code>*{
  margin:0;
  padding:0;
}
.container{
  background:grey;
  height:100vh;
}
</code>```

and HTML

```<code><div class="container">
  <h1>Hello from the other side</h1>
</div>
</code>```

and here is an example.

Body:
I want the height of my div tag exactly equal to the height of the browser's window. So if you resize the browser the  should adjust automatically.
So what should I set my height equal to in CSS.

I have tried

.class {
  height: 100%;
}

Doesn't work.

em, rem, vh, wh apparently only work with the font.

If I however, hard-code the body tag to some amount of pixels, then the percentage works for the children tags but this is not dynamic.

What I want: Just as I am viewing this stack page in my browser. I wish when I resize the browser I still get the same amount of page viewership, only resized for the new size (responsive).

Thanks.

Body:
You want to add vh so something like this.

*{
  margin:0;
  padding:0;
}
.container{
  background:grey;
  height:100vh;
}

and HTML

<div class="container">
  <h1>Hello from the other side</h1>
</div>

and here is an example.


问:
Setting Color through Javascript based on condition
I am generating a html table through C# code in an MVC Application .

I want to color the value in table cell as red and condition for this is (if column-x value is greater than value of column-y than set color of column-x as red).

column-x and column-y have their on id,s

Below is generated HTML and javascript code which I am using

$('#body table').each(function () {
    $('#' + this.id + ' ' + 'tr').each(function () {
        var v1 = $('#TodayPDue').html();
        var v2 = $('#TodayIntDue').html();

        if (v1 > v2){
            $('#TodayPDue').css('color','red');
        }
     })
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id='CollectionRPT' class='table table-bordered table-hover'>
     <tbody>
         <tr>
            <td>1</td>
            <td>BIHAR</td>
            <td id='TodayPDue'>2220515</td>
            <td id='TodayIntDue'>457565</td>
            <td id='TodayPCollected'>0</td>
            <td id='TodayIntCollected'>0</td>
            <td id='MonthPDue'>10232468</td>
            <td id='MonthIntDue'>2058526</td>
            <td id='MonthPCollected'>5912869</td>
            <td id='MonthIntCollected'>1167760</td>
            <td id='YearPDue'>6432342</td>
            <td id='YearIntDue'>1303773</td>
            <td id='YearPCollected'>2111473</td>
            <td id='YearIntCollected'>413023</td>
         </tr>
     </tbody>
</table></code>```

Any idea why it is showing no effect ?

答:
Your body selector was wrong remove # from

```<code>$('#body table').each(function () {
</code>```

it should be

```<code>$('body table').each(function () {
</code>```

function color_table() {
    $('body table').each(function () {
        $('#' + this.id + ' ' + 'tr').each(function () {
            var v1 = $(this).find('#TodayPDue').html();
            var v2 = $(this).find('#TodayIntDue').html();

            if (v1 > v2)
            {
                $('#TodayPDue').css('color','red');
            }
            else
            {
               $('#TodayPDue').css('color','green');
            }
        });
    });
}

color_table();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>table
{
  border:1
}</code>```

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

        1	BIHAR	2220515	457565
        0	0	10232468
        2058526	5912869	1167760
        6432342	1303773	2111473
        413023

```

Body:
I am generating a html table through C# code in an MVC Application .

I want to color the value in table cell as red and condition for this is (if column-x value is greater than value of column-y than set color of column-x as red).

column-x and column-y have their on id,s

Below is generated HTML and javascript code which I am using

$('#body table').each(function () {
    $('#' + this.id + ' ' + 'tr').each(function () {
        var v1 = $('#TodayPDue').html();
        var v2 = $('#TodayIntDue').html();

        if (v1 > v2){
            $('#TodayPDue').css('color','red');
        }
     })
});

            1
            BIHAR
            2220515
            457565
            0
            0
            10232468
            2058526
            5912869
            1167760
            6432342
            1303773
            2111473
            413023

Any idea why it is showing no effect ?

Body:
Your body selector was wrong remove # from

$('#body table').each(function () {

it should be

$('body table').each(function () {

function color_table() {
    $('body table').each(function () {
        $('#' + this.id + ' ' + 'tr').each(function () {
            var v1 = $(this).find('#TodayPDue').html();
            var v2 = $(this).find('#TodayIntDue').html();

            if (v1 > v2)
            {
                $('#TodayPDue').css('color','red');
            }
            else
            {
               $('#TodayPDue').css('color','green');
            }
        });
    });
}

color_table();

table
{
  border:1
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id='CollectionRPT' class='table table-bordered table-hover'>
    <tbody>
        <tr>
        <td>1</td><td>BIHAR</td><td id='TodayPDue'>2220515</td><td id='TodayIntDue'>457565</td>
        <td id='TodayPCollected'>0</td><td id='TodayIntCollected'>0</td><td id='MonthPDue'>10232468</td>
        <td id='MonthIntDue'>2058526</td><td id='MonthPCollected'>5912869</td><td id='MonthIntCollected'>1167760</td>
        <td id='YearPDue'>6432342</td><td id='YearIntDue'>1303773</td><td id='YearPCollected'>2111473</td>
        <td id='YearIntCollected'>413023</td>
        </tr>
        </tbody>
    </table>


问:
How to split the string before the 3rd occurrence of a "/" in Java
I have:

```<code>/xxx/yyy/aaa/bbb/abc.xml (or)
/xxx/yyy/aaa/abc.xml (or)
/xxx/yyy/aaa/bbb/ccc/abc.xml
</code>```

But I need only:

```<code>/xxx/yyyy
</code>```

How do I implement this in Java?
Thanks in advance.

答:
You can use StringUtils class for this.

Sample code snippet for your question,

```<code>    String str = "/xxx/yyy/aaa/bbb/abc.xml";

    int index = StringUtils.ordinalIndexOf(str , "/" , 3);

    String result = str.substring(0,index);
</code>```

Or you can use indexOf method iteratively,

```<code>    String str = "/xxx/yyy/aaa/bbb/abc.xml";

    int index = 0 , count = 1;

    while(count != 3)
    {
         index = str.indexOf("/" , index+1);
         count++;
    }

    String result = str.substring(0,index);
</code>```

Body:
I have:

/xxx/yyy/aaa/bbb/abc.xml (or)
/xxx/yyy/aaa/abc.xml (or)
/xxx/yyy/aaa/bbb/ccc/abc.xml

But I need only:

/xxx/yyyy

How do I implement this in Java?
Thanks in advance.

Body:
You can use StringUtils class for this.

Sample code snippet for your question,

    String str = "/xxx/yyy/aaa/bbb/abc.xml";

    int index = StringUtils.ordinalIndexOf(str , "/" , 3);

    String result = str.substring(0,index);

Or you can use indexOf method iteratively,

    String str = "/xxx/yyy/aaa/bbb/abc.xml";

    int index = 0 , count = 1;

    while(count != 3)
    {
         index = str.indexOf("/" , index+1);
         count++;
    }

    String result = str.substring(0,index);


问:
How to configure Python read/write module?
I have an assignment where my task is to measure the time it takes for Python to read an infile, and consequently write a number of 'a':s in an outfile, for every character in the in-file. My code looks like this:

```<code>import time

#opening input file for reading and output file for writing
#assume in.txt file created e.g. from cmd.exe using command:
# fsutil file createnew in.txt 20000000
#which creates a text file of ~20MB filled with dots.
#double backslash is required as escape character on Windows
inputFile = open('C:\\Users\\Benson\\in.txt', 'r')
outputFile = open('C:\\Users\\Benson\\out.txt', 'w')

start_time = time.time()

for i in range(1, 100):
    while True:
    #reading file by 1 character
    ch=inputFile.read(1)
    #end loop if no more characters left
    if not ch: break
    #for every character read - write an 'a' to output
    outputFile.write('a')

print("%s" % (time.time() - start_time))
</code>```

However, when I run the program I find that the number of characters in the out-file does not correspond to the number of characters in the in-file. For the in-file I have used an excerpt from Harry Potter and the Chamber of Secrets, about 1300 words. However the output file consists of only 99 'a':s whereas they should be about, or exactly, 1300 in total. What am I doing wrong?

答:
Your for loop is 1,100 which would give you 99 reads. Try instead using,

```<code>`For i in inflile:'
</code>```

The change your code to use i. i will be a line of the file, by default will be all chars apart of a new line.

Body:
I have an assignment where my task is to measure the time it takes for Python to read an infile, and consequently write a number of 'a':s in an outfile, for every character in the in-file. My code looks like this:

import time

#opening input file for reading and output file for writing
#assume in.txt file created e.g. from cmd.exe using command:
# fsutil file createnew in.txt 20000000
#which creates a text file of ~20MB filled with dots.
#double backslash is required as escape character on Windows
inputFile = open('C:\\Users\\Benson\\in.txt', 'r')
outputFile = open('C:\\Users\\Benson\\out.txt', 'w')

start_time = time.time()

for i in range(1, 100):
    while True:
    #reading file by 1 character
    ch=inputFile.read(1)
    #end loop if no more characters left
    if not ch: break
    #for every character read - write an 'a' to output
    outputFile.write('a')

print("%s" % (time.time() - start_time))

However, when I run the program I find that the number of characters in the out-file does not correspond to the number of characters in the in-file. For the in-file I have used an excerpt from Harry Potter and the Chamber of Secrets, about 1300 words. However the output file consists of only 99 'a':s whereas they should be about, or exactly, 1300 in total. What am I doing wrong?

Body:
Your for loop is 1,100 which would give you 99 reads. Try instead using,

`For i in inflile:'

The change your code to use i. i will be a line of the file, by default will be all chars apart of a new line.


问:
JPA AttributeConverter comparison?
I'm looking for an easy way to query a database column of type string in format YYYYMMDD. This could be done with a native query like:

```<code>select * from TPRODUCT where to_date(ENDOFPRODUCTION, 'YYYYMMDD') > CURRENT_DATE;
</code>```

But is there a way to achieve this comparison with an AttributeConverter

```<code>@NamedQuery(name = "product.filterByEOP", query =
    "select p from Product p where p.eop > :currentDate")
</code>```

答:
Why you don't convert your String to a date and use this last like it is :

```<code>String myDate = "20170607";
DateFormat format = new SimpleDateFormat("YYYYMMDD");
Date newDate = format.parse(myDate);
</code>```

Now you can use :

```<code>query.setParameter("currentDate", newDate);
</code>```

Title: JPA AttributeConverter comparison?

Body:
I'm looking for an easy way to query a database column of type string in format YYYYMMDD. This could be done with a native query like:

select * from TPRODUCT where to_date(ENDOFPRODUCTION, 'YYYYMMDD') > CURRENT_DATE;

But is there a way to achieve this comparison with an AttributeConverter

@NamedQuery(name = "product.filterByEOP", query =
    "select p from Product p where p.eop > :currentDate")

Body:
Why you don't convert your String to a date and use this last like it is :

String myDate = "20170607";
DateFormat format = new SimpleDateFormat("YYYYMMDD");
Date newDate = format.parse(myDate);

Now you can use :

query.setParameter("currentDate", newDate);


问:
What database tests should I write so that refactoring database is easy
Are there any guidelines on writing database tests so that you can refactor database "without fear" while doing evolutionary database design?

What aspects of database should be put to test while developing it? Any example would be great..

答:
When writing stored procedures, I liberally add Debug / Print statements.  With @Debug as a input parameter of type bit :</p>

```<code>IF @Debug = 1 PRINT @MyDynamicVariable
</code>```

OwnerDisplayName: StackUnderflow

LastEditorDisplayName: StackUnderflow

Body:
When writing stored procedures, I liberally add Debug / Print statements.  With @Debug as a input parameter of type bit :

IF @Debug = 1 PRINT @MyDynamicVariable

OwnerDisplayName: Ash Machine


问:
Java - Open a PDF file from within the JAR in a Java window (JPanel, JFrame)
I have a Java desktop application (a jar that will be used in a Mac OS .app and a Windows .exe). This Jar will contain a PDF file and I need to show this file in a Java Swing window.
How is this possible? Can be done without any additional library, like ICEPdf?</p>

答:
With this function, you will use the default PDF viewer that your OS have installed       </p>

```<code>Desktop.getDesktop().open(new File(*path to PDF*));
</code>```

Body:
With this function, you will use the default PDF viewer that your OS have installed

Desktop.getDesktop().open(new File(*path to PDF*));


问:
How to set default mode headset in android
I am working on a VoIP app, I get an issue when user unplugs headphone then device automatically switches to loud speaker but I want device to switch to normal speaker. Is there any way I can change it to normal speaker?</p>

答:
Tricky stuff, esp multiple devices, different scenarios.

I have worked on a VoIP app that is how i know this. What you are facing is probably because the audio manager mode and-or stream is being handled manually after requesting focus. What you need to do is to transfer the control to the call stream so while your call is on,

connection and disconnection of headset, transfer to the phone earpiece etc is handled automatically by the o.s.

You could probably be doing all of this or a combination...

Use AudioManager {.setMode(int mode)} - use MODE_IN_COMMUNICATION, recommended for VoIP or MODE_IN_CALL

Also, check STREAM_VOICE_CALL

Are you usinng
- isSpeakerphoneOn() and setSpeakerphoneOn(boolean)
- isBluetoothScoOn(), setBluetoothScoOn(boolean) ?

Will need to play around with all of those for device or headset model specific issues.

Useful stuff:

Even if a SCO connection is established, the following restrictions
  apply on audio output streams so that they can be routed to SCO
  headset:

the stream type must be STREAM_VOICE_CALL

the format must be mono

the sampling must be 16kHz or 8kHz


问:
Possible bug in fullcalendar's eventClick?
Here is the code snippet in question:

```<code>eventClick: function(calEvent) {
                if(user != calEvent.modified_by && calEvent.modified_by != 0){
                     $('.antoconfirm').css("display", "inline-block");
                }
                $('#fc_edit').click();
                $('#title2').val(calEvent.title);

                //-----------Submit button click-------------------
                $(".antosubmit2").on("click", function(e) {
                  e.preventDefault();
                  e.stopImmediatePropagation();
                  calEvent.title = $("#title2").val();
                  calEvent.confirm = 0;
                  calEvent.backgroundColor = '#ddbd39';
                  dbTitle = calEvent.title;

                  //ajax goes here, works fine

                  calendar.fullCalendar('updateEvent', calEvent);
                  $(".antosubmit2").off("click");
                  $('.antoclose2').click();
                });
                //---------------------------------------------------

               //-----------Close button click-------------------
               $(".antoclose2").on("click", function() {
                  console.log(calEvent.title);
                  $(".antoclose2").off("click");
              });
              //---------------------------------------------------
              return false;
           },
</code>```

$('#fc_edit').click(); calls the modal in which the editing is done. There are two buttons with the classes "antosubmit2" and "antoclose2". You click on an event, the modal comes up, you change the title, click submit, the modal goes away and voila, the title is changed(from "new1" to "new3" in this example):Test events, title change

When ONLY the submit button is used, everything works fine, you can change one event after the other without incident. On the other hand, when you use the close button on one event and try to change the title on another, the first event will be changed:Test events, title change after close

Now at the "ajax goes here, works fine" part is an ajax POST, that sends the correct data despite what the calendar shows and after a page reload everything is edited the way it should be.

Is this a bug with fullcalendar's event rendering or does my code fail somewhere?

答:
I think you need to run .off against all your button click handlers whenever any of your buttons is used. At the moment you only remove the handler for the button that was actually clicked. If you don't remove them, those handlers will remain and get used again if the other button is clicked in future. This is exactly the scenario you have run into.

In the case you described, I suspect because when you closed the first event, you didn't remove the "click" handler related to the "submit" button that went with that event. Then, when you changed the title of the second event, it ran the "click" handler for both events, because you never removed the first handler. Hence why the title for the first event gets changed when it shouldn't.

Body:
Here is the code snippet in question:

eventClick: function(calEvent) {
                if(user != calEvent.modified_by && calEvent.modified_by != 0){
                     $('.antoconfirm').css("display", "inline-block");
                }
                $('#fc_edit').click();
                $('#title2').val(calEvent.title);

                //-----------Submit button click-------------------
                $(".antosubmit2").on("click", function(e) {
                  e.preventDefault();
                  e.stopImmediatePropagation();
                  calEvent.title = $("#title2").val();
                  calEvent.confirm = 0;
                  calEvent.backgroundColor = '#ddbd39';
                  dbTitle = calEvent.title;

                  //ajax goes here, works fine

                  calendar.fullCalendar('updateEvent', calEvent);
                  $(".antosubmit2").off("click");
                  $('.antoclose2').click();
                });
                //---------------------------------------------------

               //-----------Close button click-------------------
               $(".antoclose2").on("click", function() {
                  console.log(calEvent.title);
                  $(".antoclose2").off("click");
              });
              //---------------------------------------------------
              return false;
           },

$('#fc_edit').click(); calls the modal in which the editing is done. There are two buttons with the classes "antosubmit2" and "antoclose2". You click on an event, the modal comes up, you change the title, click submit, the modal goes away and voila, the title is changed(from "new1" to "new3" in this example):Test events, title change

When ONLY the submit button is used, everything works fine, you can change one event after the other without incident. On the other hand, when you use the close button on one event and try to change the title on another, the first event will be changed:Test events, title change after close

Now at the "ajax goes here, works fine" part is an ajax POST, that sends the correct data despite what the calendar shows and after a page reload everything is edited the way it should be.

Is this a bug with fullcalendar's event rendering or does my code fail somewhere?


问:
Using multiple test directorys Java / Maven
i got a Java project which has multiple test directorys at resources.

```<code>\target\test-classes
                   |___conf
                   |      |_ items...
                   |___otherdata
                          |_ items...
</code>```

I need to access \target\test-classes at it's root, so I can switch between directories since a testcase uses files from BOTH directories at once.

Tried:

```<code>File targetClassesDir = new File(getClass().getProtectionDomain().getCodeSource().getLocation().getPath());
File targetDir = targetClassesDir.getParentFile();
</code>```

and

```<code>getClass().getResource("test-classes").getPath()
</code>```

but counldn't access the root of test-classes yet.

I've constructed a pretty shitty workaround...:

```<code>tuple4TestsuiteContainer.add(new HeaderBodyPayloadTestcase(
                                    "conf\\" + xqueries[0],
                                    getClass().getResource("/").getPath(),
                                    "xquery-testdata\\" + file.substring(file.lastIndexOf(File.separatorChar) + 1),
                                    "xquery-testdata\\" +expectedFiles[0].substring(expectedFiles[0].lastIndexOf(File.separatorChar) + 1)
                            ));
</code>```

and in the actual tester:

```<code>String xqueryFileContent = readFile(testDataBasePath + xQueryUnderTestPath, encoding);
</code>```

答:
I am not sure if I understand your problem correctly. I assume you need to get access to some data (resource).
If the resource is copied to your target directory during the maven step, then you can get the path to this resource in your code (e.g. test) via something like</p>

```<code>String resrouce = "data/bla/blub.txt";
String pathToResource = URLDecoder.decode(this.getClass().getResource(resource).getFile(), "UTF-8");
</code>```

Body:
i got a Java project which has multiple test directorys at resources.

\target\test-classes
                   |___conf
                   |      |_ items...
                   |___otherdata
                          |_ items...

I need to access \target\test-classes at it's root, so I can switch between directories since a testcase uses files from BOTH directories at once.

Tried:

File targetClassesDir = new File(getClass().getProtectionDomain().getCodeSource().getLocation().getPath());
File targetDir = targetClassesDir.getParentFile();

and

getClass().getResource("test-classes").getPath()

but counldn't access the root of test-classes yet.

I've constructed a pretty shitty workaround...:

tuple4TestsuiteContainer.add(new HeaderBodyPayloadTestcase(
                                    "conf\\" + xqueries[0],
                                    getClass().getResource("/").getPath(),
                                    "xquery-testdata\\" + file.substring(file.lastIndexOf(File.separatorChar) + 1),
                                    "xquery-testdata\\" +expectedFiles[0].substring(expectedFiles[0].lastIndexOf(File.separatorChar) + 1)
                            ));

and in the actual tester:

String xqueryFileContent = readFile(testDataBasePath + xQueryUnderTestPath, encoding);

Body:
I am not sure if I understand your problem correctly. I assume you need to get access to some data (resource).
If the resource is copied to your target directory during the maven step, then you can get the path to this resource in your code (e.g. test) via something like

String resrouce = "data/bla/blub.txt";
String pathToResource = URLDecoder.decode(this.getClass().getResource(resource).getFile(), "UTF-8");


问:
How to use a UIButton as a toggle switch
I am using a UIButton of custom type and what I want is use it like a toggle switch with the change of image. Like when it is clicked if previously it was not in selected mode it should go in selected mode or otherwise vice-a-versa. Also it will have a different image and when it is selected it will have a different image when it is not.

I am not able to do it programatically, is there any good easy way to do this.

答:
For Swift 3

```<code>@IBAction func playPause(sender : UIButton){

   if sender.isSelected {
      player.pause()
   }else{
      player.play()
  }
  sender.isSelected = !sender.isSelected
}
</code>```

Body:
For Swift 3

@IBAction func playPause(sender : UIButton){

   if sender.isSelected {
      player.pause()
   }else{
      player.play()
  }
  sender.isSelected = !sender.isSelected
}


答:
You can do it by jquery on simple way.</p>

```<code> $(document).ready(function(){
     var heights = window.innerHeight;
    $(".class ").style.height = heights + "px";
 });
</code>```

Title: CSS/HTML5: How to adjust div tag height equal to browser window's current height?

Body:
You can do it by jquery on simple way.

 $(document).ready(function(){
     var heights = window.innerHeight;
    $(".class ").style.height = heights + "px";
 });