问:
How to sum a column of one pandas dataframe to each column of another dataframe?
Situation:

Both dataframes (df1 and df2) have the same three indices, e.g. "A", "B", "C".
df1 and df2 differ in the number of their columns.
All cells in df1 and df2 are filled with data of the type float.

df1:

```<code>   AA    BB   CC   DD
A  28.0   2.3  2.0  113
B  24.0   2.4  2.4  116
C  33.5  10.0  4.0    0
</code>```

df2:

```<code>    AAA   BBB   CCC    DDD    EEE
A  1.01  4.04  7.07  10.10  13.13
B  2.02  5.05  8.08  11.11  14.14
C  3.03  6.06  9.09  12.12  15.15
</code>```

Goal:

After the column chosen from df2 (e.g. "BBB") is summed with each column of df1, the results should be stored in a new dataframe (df_new).
df_new should be of the format of df1 (number of columns and rows) and have the same column-names and indices as df1.

new_df:

```<code>    AA      BB      CC      DD
A   32.04   6.34    6.04    117.04
B   29.05   7.45    7.45    121.05
C   39.56   16.06   10.06   6.06
</code>```

My approach:

To sum the 3rd column of df2 with each column of df1, I tried:

df_new = df1.add(df2.iloc[:,2])

Result:

As desired, df_new matches df1 in structure and labels.
The problem is: All cells show "NaN" instead of the desired sums as floats.

df_new:

```<code>    AA  BB  CC  DD
A   NaN NaN NaN NaN
B   NaN NaN NaN NaN
C   NaN NaN NaN NaN
</code>```

Body:
Situation:

Both dataframes (df1 and df2) have the same three indices, e.g. "A", "B", "C".
df1 and df2 differ in the number of their columns.
All cells in df1 and df2 are filled with data of the type float.

df1:

   AA    BB   CC   DD
A  28.0   2.3  2.0  113
B  24.0   2.4  2.4  116
C  33.5  10.0  4.0    0

df2:

    AAA   BBB   CCC    DDD    EEE
A  1.01  4.04  7.07  10.10  13.13
B  2.02  5.05  8.08  11.11  14.14
C  3.03  6.06  9.09  12.12  15.15

Goal:

After the column chosen from df2 (e.g. "BBB") is summed with each column of df1, the results should be stored in a new dataframe (df_new).
df_new should be of the format of df1 (number of columns and rows) and have the same column-names and indices as df1.

new_df:

    AA      BB      CC      DD
A   32.04   6.34    6.04    117.04
B   29.05   7.45    7.45    121.05
C   39.56   16.06   10.06   6.06

My approach:

To sum the 3rd column of df2 with each column of df1, I tried:

df_new = df1.add(df2.iloc[:,2])

Result:

As desired, df_new matches df1 in structure and labels.
The problem is: All cells show "NaN" instead of the desired sums as floats.

df_new:

    AA  BB  CC  DD
A   NaN NaN NaN NaN
B   NaN NaN NaN NaN
C   NaN NaN NaN NaN

Body:
Here's one way, using add

In [293]: df1.add(df2['BBB'], axis=0)
Out[293]:
      AA     BB     CC      DD
A  32.04   6.34   6.04  117.04
B  29.05   7.45   7.45  121.05
C  39.56  16.06  10.06    6.06


来源: stackexchange

问:
camera application gets stuck after taking pic and do not return to my application
I am using nexus 5 for testing.
Sometimes my Camera application gets stuck/hang after taking pic and do not return to my application. It return after few second and on activityResult() does not get called. and  in samsung galaxy j5 sometimes white screen appears after clicking pic.

My code

```<code>public void openCamera() {

        if (!checkPermission(Manifest.permission.CAMERA, context)) {
            requestPermission(Manifest.permission.CAMERA, 11, getActivity());
            return;
        }

        if (!checkPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, context)) {
            requestPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, 121, getActivity());
            return;
        }

        if (!checkPermission(Manifest.permission.READ_EXTERNAL_STORAGE, context)) {
            requestPermission(Manifest.permission.READ_EXTERNAL_STORAGE, 121, getActivity());
            return;
        }
        boolean flag = true;
        try {
            photoFile = createImageFile();

        } catch (Exception ex) {
            flag = false;
            Toast.makeText(context, ""+ex, Toast.LENGTH_LONG).show();
            UtilityMethods.saveException(ex.getMessage(),"ab");
        }

        if (photoFile != null&&flag) {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

            if(Build.VERSION.SDK_INT>=24) {
                intent.putExtra(MediaStore.EXTRA_OUTPUT, FileProvider.getUriForFile(context, context.getApplicationContext().getPackageName() + ".provider", photoFile));
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            }else {
                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
            }

            intent.putExtra("android.intent.extras.CAMERA_FACING", 1);

        }else{
            UtilityMethods.saveException("file exception"+photoFile,"abc");
        }
    }
</code>```

Another method

```<code> private File createImageFile() throws Exception {

        String imageFileName = "JPEG_img";

        File storageDir = Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_PICTURES);
        if (!storageDir.exists()) {
            if (!storageDir.mkdirs()) {
                return null;
            }
        }
        File image = File.createTempFile(
                imageFileName,  /* prefix */
                ".jpg",         /* suffix */
                storageDir      /* directory */
        );

        pathOfPic = image.getAbsolutePath();
        return image;
    }
</code>```

答:
Working with files has been chnaged in API 24.
Here is the solution for you:

https://inthecheesefactory.com/blog/how-to-share-access-to-file-with-fileprovider-on-android-nougat/en

ContentLicense: CC BY-SA 3.0

Body:
I am using nexus 5 for testing.
Sometimes my Camera application gets stuck/hang after taking pic and do not return to my application. It return after few second and on activityResult() does not get called. and  in samsung galaxy j5 sometimes white screen appears after clicking pic.

My code

public void openCamera() {

        if (!checkPermission(Manifest.permission.CAMERA, context)) {
            requestPermission(Manifest.permission.CAMERA, 11, getActivity());
            return;
        }

        if (!checkPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, context)) {
            requestPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, 121, getActivity());
            return;
        }

        if (!checkPermission(Manifest.permission.READ_EXTERNAL_STORAGE, context)) {
            requestPermission(Manifest.permission.READ_EXTERNAL_STORAGE, 121, getActivity());
            return;
        }
        boolean flag = true;
        try {
            photoFile = createImageFile();

        } catch (Exception ex) {
            flag = false;
            Toast.makeText(context, ""+ex, Toast.LENGTH_LONG).show();
            UtilityMethods.saveException(ex.getMessage(),"ab");
        }

        if (photoFile != null&&flag) {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

            if(Build.VERSION.SDK_INT>=24) {
                intent.putExtra(MediaStore.EXTRA_OUTPUT, FileProvider.getUriForFile(context, context.getApplicationContext().getPackageName() + ".provider", photoFile));
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            }else {
                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
            }

            intent.putExtra("android.intent.extras.CAMERA_FACING", 1);

        }else{
            UtilityMethods.saveException("file exception"+photoFile,"abc");
        }
    }

Another method

 private File createImageFile() throws Exception {

        String imageFileName = "JPEG_img";

        File storageDir = Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_PICTURES);
        if (!storageDir.exists()) {
            if (!storageDir.mkdirs()) {
                return null;
            }
        }
        File image = File.createTempFile(
                imageFileName,  /* prefix */
                ".jpg",         /* suffix */
                storageDir      /* directory */
        );

        pathOfPic = image.getAbsolutePath();
        return image;
    }


问:
android application's retrofit base_url
I want to build an api for an android studio application to make the base url of the retrofit. I am having problems to make the base_url. I want to know how I should make the base_url of the retrofit. I am having problems validating the base_url. I want to know the procedure to make a base_url for retrofit.

答:
If this is my url
http://api.themoviedb.org/3/movie/top_rated?api_key=12345678910111213

Then base url becomes

http://api.themoviedb.org/

It will be passed in as

```<code>retrofit = new Retrofit.Builder()
                    .baseUrl("http://api.themoviedb.org/");
</code>```

and the remaining part will become get or post query

Title: android application's retrofit base_url

Body:
If this is my url
http://api.themoviedb.org/3/movie/top_rated?api_key=12345678910111213

Then base url becomes

http://api.themoviedb.org/

It will be passed in as

retrofit = new Retrofit.Builder()
                    .baseUrl("http://api.themoviedb.org/");

and the remaining part will become get or post query


问:
How to classify my array of object compared to my table?
I want to reorder my array of object, I want it follows (const quote) the theme position (const themeOrder).

```<code>const quote = [{
  theme: 'spirituality'
}, {
  theme: 'politic'
}, {
  theme: 'military'
}, {
  theme: 'politic'
}, {
  theme: 'tech'
}];
const themeOrder = ['tech', 'politic', 'military', 'spirituality'];
</code>```

I want a result like

```<code>newQuote = [{
  theme: 'tech'
}, {
  theme: 'politic'
}, {
  theme: 'military'
}, {
  theme: 'spirituality'
}]
</code>```

答:
Just sort() the elements based on their index in themeOrder:

```<code>quote.sort((x,y) => themeOrder.indexOf(x.theme) > themeOrder.indexOf(y.theme) ? 1 : -1))
</code>```

See Documentation

Body:
I want to reorder my array of object, I want it follows (const quote) the theme position (const themeOrder).

const quote = [{
  theme: 'spirituality'
}, {
  theme: 'politic'
}, {
  theme: 'military'
}, {
  theme: 'politic'
}, {
  theme: 'tech'
}];
const themeOrder = ['tech', 'politic', 'military', 'spirituality'];

I want a result like

newQuote = [{
  theme: 'tech'
}, {
  theme: 'politic'
}, {
  theme: 'military'
}, {
  theme: 'spirituality'
}]

Body:
Just sort() the elements based on their index in themeOrder:

quote.sort((x,y) => themeOrder.indexOf(x.theme) > themeOrder.indexOf(y.theme) ? 1 : -1))

See Documentation


问:
How can I merge array's items?
I have an array like this:

```<code>$arr = array ( [0] => array("red","green"),
               [1] => array("blue","yellow")
             );
</code>```

And this is expected result:

```<code>Array ( [0] => red [1] => green [2] => blue [3] => yellow )
</code>```

See? I want to merge all items of $arr (which are also array themselves). How can I do that?

I can do a loop on it and then use array_merge() every time like this:

```<code>$res = [];
foreach ( $arr as $item ) {
    $res = array_merge($res, $item);
}
</code>```

It works as well. But I guess I can write it better. Any idea?

答:
It's a style exercise, but if the structure remains the same as in your example, you can play with this:

```<code>$arr = array ( '0' => array("red","green"),
               '1' => array("blue","yellow")
             );

$res = explode(",",str_replace(array('[',']'),'',json_encode($arr)));
</code>```

Hope this helps.

Title: How can I merge array's items?

Body:
I have an array like this:

$arr = array ( [0] => array("red","green"),
               [1] => array("blue","yellow")
             );

And this is expected result:

Array ( [0] => red [1] => green [2] => blue [3] => yellow )

See? I want to merge all items of $arr (which are also array themselves). How can I do that?

I can do a loop on it and then use array_merge() every time like this:

$res = [];
foreach ( $arr as $item ) {
    $res = array_merge($res, $item);
}

It works as well. But I guess I can write it better. Any idea?

Body:
It's a style exercise, but if the structure remains the same as in your example, you can play with this:

$arr = array ( '0' => array("red","green"),
               '1' => array("blue","yellow")
             );

$res = explode(",",str_replace(array('[',']'),'',json_encode($arr)));

Hope this helps.


问:
when should we care about cache missing?
I want to explain my question through a practical problem I met in my project.

I am writing a c library( which behaves like a programmable vi editor), and i plan to provide a series of APIs ( more than 20 in total ):

```<code>void vi_dw(struct vi *vi);
void vi_de(struct vi *vi);
void vi_d0(struct vi *vi);
void vi_d$(struct vi *vi);
...
void vi_df(struct vi *, char target);
void vi_dd(struct vi *vi);
</code>```

These APIs do not perform core operations, they are just wrappers. For example, I can implement vi_de() like this:

```<code>void vi_de(struct vi *vi){
    vi_v(vi);  //enter visual mode
    vi_e(vi);  //press key 'e'
    vi_d(vi);  //press key 'd'
}
</code>```

However, if the wrapper is as simple as such, I have to write more than 20 similar wrapper functions.

So, I consider implementing  more complex wrappers to reduce the amount:

```<code>void vi_d_move(struct vi *vi, vi_move_func_t move){
   vi_v(vi);
   move(vi);
   vi_d(vi);
}
static inline void vi_dw(struct vi *vi){
    vi_d_move(vi, vi_w);
}
static inline void vi_de(struct vi *vi){
    vi_d_move(vi, vi_e);
}
...
</code>```

The function vi_d_move() is a better wrapper function, he can convert a part of similar move operation to APIs, but not all, like vi_f(), which need another wrapper with a third argument char target .

I finished explaining the example picked from my project.
The pseudo code above is simper than real case, but is enough to show that:

The more complex the wrapper is, the less wrappers we need, and the slower they will be.(they will become more indirect or need to consider more conditions).

There are two extremes:

use only one wrapper but complex enough to adopt all move operations and convert them into corresponding APIs.

use more than twenty small and simple wrappers. one wrapper is one API.

For case 1, the wrapper itself is slow, but it has more chance resident in cache, because it is often executed(all APIs share it). It's a slow but hot path.

For case 2, these wrappers are simple and fast, but has less chance resident in cache. At least, for any API first time called, a cache miss will happen.(CPU need to fetch instructions from memory, but not L1, L2).

Currently, I implemented five wrappers, each of them are relatively simple and fast.  this seems to be a balance, but just seems. I chose five just because I felt the move operation can be divided into five groups naturally. I have no idea how to evaluate it, I don't mean a profiler, I mean, in theory, what main factors should be considered in such case?

In the post end, I want to add more detail for these APIs:

These APIs need to be fast. Because this library is designed as a high performance virtual editor. The delete/copy/paste operation is designed to approach the bare C code.

A user program based on this library seldom calls all these APIs, only parts of them, and usually no more than 10 times for each.

In real case, the size of these simple wrappers are about 80 bytes each, and will be no more than 160 bytes even merged into a single complex one. (but will introduce more if-else branches).

4, As with the situation the library is used, I will take lua-shell as example(a little off-topic, but some friends want to know why I so care its performance):

lua-shell is a *nix shell which uses lua as its script. Its command execution unit(which do forks(), execute()..) is just a C module registered into the lua state machine.

Lua-shell treats everything  as lua .

So, When user input:

```<code>local files = `ls -la`
</code>```

And press Enter. The  string input is first sent to lua-shell's preprocessor————which convert mixed-syntax to pure lua code:

```<code>local file = run_command("ls -la")
</code>```

run_command() is  the entry of lua-shell's command execution unit, which, I said before, is a C module.

We can talk about libvi now. lua-shell's preprocessor is the first user of the library I am writing. Here is its relative codes(pseudo):

```<code>#include"vi.h"
vi_loadstr("local files = `ls -la`");
vi_f(vi, '`');
vi_x(vi);
vi_i(vi, "run_command(\"");
vi_f(vi, '`');
vi_x(vi);
vi_a(" \") ");
</code>```

The code above is parts of luashell's preprocessor implementation.
After generating the pure lua code, he feeds it to Lua State Machine and run it.

The shell user is sensitive to the time interval between Enter and a new prompt, and in most case lua-shell needs preprocess script with  larger size and more complicate mixed-syntax.

This is a typical situation where libvi is used.

答:
I won't care that much about cache misses (especially in your case), unless your benchmarks (with compiler optimizations enabled, i.e. compile with gcc -O2 -mtune=native if using GCC....) indicate that they matter.

If performances matters that much, enable more optimizations (perhaps compiling and linking your entire application or library with gcc -flto -O2 -mtune=native that is with link-time optimizations), and hand-optimize only what is critical. You should trust your optimizing compiler.

If you are in the design phase, consider perhaps making your application multi-threaded or somehow concurrent and parallel. With care, this could speedup it more than cache optimizations.

It is unclear what your library is about and what are your design goals. A possibility to add flexibility might be embed some interpreter (like lua or guile or python, etc...) in your application, hence configuring it thru scripts. In many cases, such an embedding could be fast enough (especially when the application specific primitives are of high enough level). Another (more complex) possibility is to provide metaprogramming abilities perhaps thru some JIT compiling library like libjit or libgccjit (so you would sort-of "compile" user scripts into dynamically produced machine code).

BTW, your question seems to focus on instruction cache misses. I would believe that data cache misses are more important (and less optimizable by the compiler), and that is why you would prefer e.g. vectors to linked lists (and more generally care about low-level data structures, focusing on using sequential -or cache-friendly- accesses)

(you could find a good video by Herb Sutter which explains that last point; I forgot the reference)

In some very specific cases, with recent GCC or Clang, adding a few __builtin_prefetch might slightly improve performance (by decreasing cache misses), but it could also harm it significantly, so I don't recommend using it in general, but see this.

Body:
I want to explain my question through a practical problem I met in my project.

I am writing a c library( which behaves like a programmable vi editor), and i plan to provide a series of APIs ( more than 20 in total ):

void vi_dw(struct vi *vi);
void vi_de(struct vi *vi);
void vi_d0(struct vi *vi);
void vi_d$(struct vi *vi);
...
void vi_df(struct vi *, char target);
void vi_dd(struct vi *vi);

These APIs do not perform core operations, they are just wrappers. For example, I can implement vi_de() like this:

void vi_de(struct vi *vi){
    vi_v(vi);  //enter visual mode
    vi_e(vi);  //press key 'e'
    vi_d(vi);  //press key 'd'
}

However, if the wrapper is as simple as such, I have to write more than 20 similar wrapper functions.

So, I consider implementing  more complex wrappers to reduce the amount:

void vi_d_move(struct vi *vi, vi_move_func_t move){
   vi_v(vi);
   move(vi);
   vi_d(vi);
}
static inline void vi_dw(struct vi *vi){
    vi_d_move(vi, vi_w);
}
static inline void vi_de(struct vi *vi){
    vi_d_move(vi, vi_e);
}
...

The function vi_d_move() is a better wrapper function, he can convert a part of similar move operation to APIs, but not all, like vi_f(), which need another wrapper with a third argument char target .

I finished explaining the example picked from my project.
The pseudo code above is simper than real case, but is enough to show that:

The more complex the wrapper is, the less wrappers we need, and the slower they will be.(they will become more indirect or need to consider more conditions).

There are two extremes:

use only one wrapper but complex enough to adopt all move operations and convert them into corresponding APIs.

use more than twenty small and simple wrappers. one wrapper is one API.

For case 1, the wrapper itself is slow, but it has more chance resident in cache, because it is often executed(all APIs share it). It's a slow but hot path.

For case 2, these wrappers are simple and fast, but has less chance resident in cache. At least, for any API first time called, a cache miss will happen.(CPU need to fetch instructions from memory, but not L1, L2).

Currently, I implemented five wrappers, each of them are relatively simple and fast.  this seems to be a balance, but just seems. I chose five just because I felt the move operation can be divided into five groups naturally. I have no idea how to evaluate it, I don't mean a profiler, I mean, in theory, what main factors should be considered in such case?

In the post end, I want to add more detail for these APIs:

These APIs need to be fast. Because this library is designed as a high performance virtual editor. The delete/copy/paste operation is designed to approach the bare C code.

A user program based on this library seldom calls all these APIs, only parts of them, and usually no more than 10 times for each.

In real case, the size of these simple wrappers are about 80 bytes each, and will be no more than 160 bytes even merged into a single complex one. (but will introduce more if-else branches).

4, As with the situation the library is used, I will take lua-shell as example(a little off-topic, but some friends want to know why I so care its performance):

lua-shell is a *nix shell which uses lua as its script. Its command execution unit(which do forks(), execute()..) is just a C module registered into the lua state machine.

Lua-shell treats everything  as lua .

So, When user input:

local files = `ls -la`

And press Enter. The  string input is first sent to lua-shell's preprocessor————which convert mixed-syntax to pure lua code:

local file = run_command("ls -la")

run_command() is  the entry of lua-shell's command execution unit, which, I said before, is a C module.

We can talk about libvi now. lua-shell's preprocessor is the first user of the library I am writing. Here is its relative codes(pseudo):

#include"vi.h"
vi_loadstr("local files = `ls -la`");
vi_f(vi, '`');
vi_x(vi);
vi_i(vi, "run_command(\"");
vi_f(vi, '`');
vi_x(vi);
vi_a(" \") ");

The code above is parts of luashell's preprocessor implementation.
After generating the pure lua code, he feeds it to Lua State Machine and run it.

The shell user is sensitive to the time interval between Enter and a new prompt, and in most case lua-shell needs preprocess script with  larger size and more complicate mixed-syntax.

This is a typical situation where libvi is used.


问:
WPF close secondary window before main window
I have 2 windows in a WPF application, and If I close the Main one, I want to close the other too.

I achieved this by setting in my App.xaml:

```<code>ShutdownMode="OnMainWindowClose"
</code>```

The 2 windows have a Window_Closing event in which I de-initialise some components. Now what I want to achieve is: if I close the MainWindow, the Window_Closing event of the second window must execute before the closing event of the Main one, because the de-init of the second one has to be executed before the first. Any idea on how can I achive this?

答:
Use the Application.Current.Windows collection. It contains the list of all the windows of your app; you can iterate through them and operate on them.

In this case, you can write:

```<code>public void MainWindow_Closing(object sender, CancelEventArgs e)
{
    foreach (Window w in Application.Current.Windows)
    {
        if (w.Title == "Secondary Window") // <-- or whatever check you want to identify the secondary Window
        {
            w.Close();
            break;
        }
    }
}
</code>```

This allows you to gain a flexible behavior, for example you can close ALL the secondary windows, not just one.

Body:
I have 2 windows in a WPF application, and If I close the Main one, I want to close the other too.

I achieved this by setting in my App.xaml:

ShutdownMode="OnMainWindowClose"

The 2 windows have a Window_Closing event in which I de-initialise some components. Now what I want to achieve is: if I close the MainWindow, the Window_Closing event of the second window must execute before the closing event of the Main one, because the de-init of the second one has to be executed before the first. Any idea on how can I achive this?

Body:
Use the Application.Current.Windows collection. It contains the list of all the windows of your app; you can iterate through them and operate on them.

In this case, you can write:

public void MainWindow_Closing(object sender, CancelEventArgs e)
{
    foreach (Window w in Application.Current.Windows)
    {
        if (w.Title == "Secondary Window") // <-- or whatever check you want to identify the secondary Window
        {
            w.Close();
            break;
        }
    }
}

This allows you to gain a flexible behavior, for example you can close ALL the secondary windows, not just one.


问:
How to convert yuy2 to a BITMAP in C++
I'm using a security camera DLL to retreive the image from the camera. The DLL call a function of my program passing the image buffer as a parameter, but the image is in yuy2 format. I need to convert this buffer to RGB, but I tried every formula I found on Internet with no success. Every example I tried (including http://msdn.microsoft.com/en-us/library/aa904813(VS.80).aspx#yuvformats_2) gives me wrong colors.

I'm able to convert the buffer to a BW image using only the Y component of the pixel, but I really need the color picture. I debugged (assembly only) the DLL that shows the image in the screen and it uses DirectDraw to do this.

答: If you were already using DirectShow to get video data out of the security camera, then you could simply add the "Color Space Converter Filter"  to your DirectShow graph.  But if you aren't using DirectShow already (it sounds like you're not) then it will be much, much simpler to just convert the data to RGB yourself using the formulas that Daniel linked to.  Adding DirectShow to a project is very complicated.</p>

ContentLicense: CC BY-SA 2.5

Title: How to convert yuy2 to a BITMAP in C++


问:
Xamarin App crashes calling HTTPS
I created a simple Xamarin.Forms App to check HTTPS using https://jsonplaceholder.typicode.com/.

But the App crashes using HTTPS.

```<code> public RestService() {
      client = new HttpClient();
      client.MaxResponseContentBufferSize = 256000;
    }

public async Task<List<Item>> RefreshDataAsync() {
  string url = "http://jsonplaceholder.typicode.com/posts";
  // Crash using this URL
  //string url = "https://jsonplaceholder.typicode.com/posts";
  var uri = new Uri(string.Format(url, string.Empty));
  List<Item> Items = new List<Item>();

  var content = await client.GetStringAsync(uri);
    Items = JsonConvert.DeserializeObject<List<Item>>(content);

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

Is it a problem with the website or httpClient or do I do somethin wrong ?

Thats the Exception

```<code>{System.Net.Http.HttpRequestException: An error occurred while sending the request ---> System.Net.WebException: Error: SecureChannelFailure (The authentication or decryption has failed.) ---> System.IO.IOException: The authentication or decryption has failed. ---> System.IO.IOException: The authentication or decryption has failed. ---> Mono.Security.Protocol.Tls.TlsException: The authentication or decryption has failed.
  at Mono.Security.Protocol.Tls.RecordProtocol.EndReceiveRecord (System.IAsyncResult asyncResult) [0x00037] in <d2bf9ddce2b945f79db1e7c4354bafea>:0
  at Mono.Security.Protocol.Tls.SslClientStream.SafeEndReceiveRecord (System.IAsyncResult ar, System.Boolean ignoreEmpty) [0x00000] in <d2bf9ddce2b945f79db1e7c4354bafea>:0
  at Mono.Security.Protocol.Tls.SslClientStream.NegotiateAsyncWorker (System.IAsyncResult result) [0x00071] in <d2bf9ddce2b945f79db1e7c4354bafea>:0
   --- End of inner exception stack trace ---
  at Mono.Security.Protocol.Tls.SslClientStream.EndNegotiateHandshake (System.IAsyncResult result) [0x00032] in <d2bf9ddce2b945f79db1e7c4354bafea>:0
  at Mono.Security.Protocol.Tls.SslStreamBase.AsyncHandshakeCallback (System.IAsyncResult asyncResult) [0x0000c] in <d2bf9ddce2b945f79db1e7c4354bafea>:0
   --- End of inner exception stack trace ---
  at Mono.Security.Protocol.Tls.SslStreamBase.EndRead (System.IAsyncResult asyncResult) [0x0004b] in <d2bf9ddce2b945f79db1e7c4354bafea>:0
  at Mono.Net.Security.Private.LegacySslStream.EndAuthenticateAsClient (System.IAsyncResult asyncResult) [0x0000e] in <a547bd0d78184f26ab08d022f013c1e1>:0
  at Mono.Net.Security.Private.LegacySslStream.AuthenticateAsClient (System.String targetHost, System.Security.Cryptography.X509Certificates.X509CertificateCollection clientCertificates, System.Security.Authentication.SslProtocols enabledSslProtocols, System.Boolean checkCertificateRevocation) [0x0000e] in <a547bd0d78184f26ab08d022f013c1e1>:0
  at Mono.Net.Security.MonoTlsStream.CreateStream (System.Byte[] buffer) [0x0007b] in <a547bd0d78184f26ab08d022f013c1e1>:0
  at System.Net.WebConnection.CreateStream (System.Net.HttpWebRequest request) [0x00073] in <a547bd0d78184f26ab08d022f013c1e1>:0
   --- End of inner exception stack trace ---
  at System.Net.HttpWebRequest.EndGetResponse (System.IAsyncResult asyncResult) [0x00058] in <a547bd0d78184f26ab08d022f013c1e1>:0
  at System.Threading.Tasks.TaskFactory`1[TResult].FromAsyncCoreLogic (System.IAsyncResult iar, System.Func`2[T,TResult] endFunction, System.Action`1[T] endAction, System.Threading.Tasks.Task`1[TResult] promise, System.Boolean requiresSynchronization) [0x0000f] in <3fd174ff54b146228c505f23cf75ce71>:0
--- End of stack trace from previous location where exception was thrown ---
  at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x0003e] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x00028] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x00008] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1+ConfiguredTaskAwaiter[TResult].GetResult () [0x00000] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Net.Http.HttpClientHandler+<SendAsync>d__63.MoveNext () [0x003e6] in <b696532a7c264e5e866cb15a1b40a4a4>:0
   --- End of inner exception stack trace ---
  at System.Net.Http.HttpClientHandler+<SendAsync>d__63.MoveNext () [0x00449] in <b696532a7c264e5e866cb15a1b40a4a4>:0
--- End of stack trace from previous location where exception was thrown ---
  at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x0003e] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x00028] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x00008] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1+ConfiguredTaskAwaiter[TResult].GetResult () [0x00000] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Net.Http.HttpClient+<SendAsyncWorker>d__49.MoveNext () [0x000ca] in <b696532a7c264e5e866cb15a1b40a4a4>:0
--- End of stack trace from previous location where exception was thrown ---
  at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x0003e] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x00028] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x00008] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1+ConfiguredTaskAwaiter[TResult].GetResult () [0x00000] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Net.Http.HttpClient+<GetStringAsync>d__55.MoveNext () [0x0007d] in <b696532a7c264e5e866cb15a1b40a4a4>:0
--- End of stack trace from previous location where exception was thrown ---
  at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x0003e] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x00028] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x00008] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Runtime.CompilerServices.TaskAwaiter`1[TResult].GetResult () [0x00000] in <3fd174ff54b146228c505f23cf75ce71>:0
  at getWeather.RestService+<RefreshDataAsync>d__2.MoveNext () [0x0006e] in C:\Users\afelde\documents\visual studio 2017\Projects\getWeather\getWeather\getWeather\RestService.cs:30 }
</code>```

答:
I found a post about your issue (https://forums.xamarin.com/discussion/10405/the-authentication-or-decryption-has-failed-in-the-web-request)

Here in the comments you will find someone suggesting to use the package modernhttpclient

The way to work with this package:
HttpClient client = new HttpClient(new NativeMessageHandler());

The NativeMessagehandler will solve the certifcations issue ( since u using https it gave a authentication error, this will solve it)

For the rest you can use the client as you were already using it.

Good luck

Title: Xamarin App crashes calling HTTPS

Body:
I created a simple Xamarin.Forms App to check HTTPS using https://jsonplaceholder.typicode.com/.

But the App crashes using HTTPS.

 public RestService() {
      client = new HttpClient();
      client.MaxResponseContentBufferSize = 256000;
    }

public async Task<List<Item>> RefreshDataAsync() {
  string url = "http://jsonplaceholder.typicode.com/posts";
  // Crash using this URL
  //string url = "https://jsonplaceholder.typicode.com/posts";
  var uri = new Uri(string.Format(url, string.Empty));
  List<Item> Items = new List<Item>();

  var content = await client.GetStringAsync(uri);
    Items = JsonConvert.DeserializeObject<List<Item>>(content);

  return Items;
}
}

Is it a problem with the website or httpClient or do I do somethin wrong ?

Thats the Exception

{System.Net.Http.HttpRequestException: An error occurred while sending the request ---> System.Net.WebException: Error: SecureChannelFailure (The authentication or decryption has failed.) ---> System.IO.IOException: The authentication or decryption has failed. ---> System.IO.IOException: The authentication or decryption has failed. ---> Mono.Security.Protocol.Tls.TlsException: The authentication or decryption has failed.
  at Mono.Security.Protocol.Tls.RecordProtocol.EndReceiveRecord (System.IAsyncResult asyncResult) [0x00037] in <d2bf9ddce2b945f79db1e7c4354bafea>:0
  at Mono.Security.Protocol.Tls.SslClientStream.SafeEndReceiveRecord (System.IAsyncResult ar, System.Boolean ignoreEmpty) [0x00000] in <d2bf9ddce2b945f79db1e7c4354bafea>:0
  at Mono.Security.Protocol.Tls.SslClientStream.NegotiateAsyncWorker (System.IAsyncResult result) [0x00071] in <d2bf9ddce2b945f79db1e7c4354bafea>:0
   --- End of inner exception stack trace ---
  at Mono.Security.Protocol.Tls.SslClientStream.EndNegotiateHandshake (System.IAsyncResult result) [0x00032] in <d2bf9ddce2b945f79db1e7c4354bafea>:0
  at Mono.Security.Protocol.Tls.SslStreamBase.AsyncHandshakeCallback (System.IAsyncResult asyncResult) [0x0000c] in <d2bf9ddce2b945f79db1e7c4354bafea>:0
   --- End of inner exception stack trace ---
  at Mono.Security.Protocol.Tls.SslStreamBase.EndRead (System.IAsyncResult asyncResult) [0x0004b] in <d2bf9ddce2b945f79db1e7c4354bafea>:0
  at Mono.Net.Security.Private.LegacySslStream.EndAuthenticateAsClient (System.IAsyncResult asyncResult) [0x0000e] in <a547bd0d78184f26ab08d022f013c1e1>:0
  at Mono.Net.Security.Private.LegacySslStream.AuthenticateAsClient (System.String targetHost, System.Security.Cryptography.X509Certificates.X509CertificateCollection clientCertificates, System.Security.Authentication.SslProtocols enabledSslProtocols, System.Boolean checkCertificateRevocation) [0x0000e] in <a547bd0d78184f26ab08d022f013c1e1>:0
  at Mono.Net.Security.MonoTlsStream.CreateStream (System.Byte[] buffer) [0x0007b] in <a547bd0d78184f26ab08d022f013c1e1>:0
  at System.Net.WebConnection.CreateStream (System.Net.HttpWebRequest request) [0x00073] in <a547bd0d78184f26ab08d022f013c1e1>:0
   --- End of inner exception stack trace ---
  at System.Net.HttpWebRequest.EndGetResponse (System.IAsyncResult asyncResult) [0x00058] in <a547bd0d78184f26ab08d022f013c1e1>:0
  at System.Threading.Tasks.TaskFactory`1[TResult].FromAsyncCoreLogic (System.IAsyncResult iar, System.Func`2[T,TResult] endFunction, System.Action`1[T] endAction, System.Threading.Tasks.Task`1[TResult] promise, System.Boolean requiresSynchronization) [0x0000f] in <3fd174ff54b146228c505f23cf75ce71>:0
--- End of stack trace from previous location where exception was thrown ---
  at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x0003e] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x00028] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x00008] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1+ConfiguredTaskAwaiter[TResult].GetResult () [0x00000] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Net.Http.HttpClientHandler+<SendAsync>d__63.MoveNext () [0x003e6] in <b696532a7c264e5e866cb15a1b40a4a4>:0
   --- End of inner exception stack trace ---
  at System.Net.Http.HttpClientHandler+<SendAsync>d__63.MoveNext () [0x00449] in <b696532a7c264e5e866cb15a1b40a4a4>:0
--- End of stack trace from previous location where exception was thrown ---
  at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x0003e] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x00028] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x00008] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1+ConfiguredTaskAwaiter[TResult].GetResult () [0x00000] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Net.Http.HttpClient+<SendAsyncWorker>d__49.MoveNext () [0x000ca] in <b696532a7c264e5e866cb15a1b40a4a4>:0
--- End of stack trace from previous location where exception was thrown ---
  at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x0003e] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x00028] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x00008] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1+ConfiguredTaskAwaiter[TResult].GetResult () [0x00000] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Net.Http.HttpClient+<GetStringAsync>d__55.MoveNext () [0x0007d] in <b696532a7c264e5e866cb15a1b40a4a4>:0
--- End of stack trace from previous location where exception was thrown ---
  at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x0003e] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x00028] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x00008] in <3fd174ff54b146228c505f23cf75ce71>:0
  at System.Runtime.CompilerServices.TaskAwaiter`1[TResult].GetResult () [0x00000] in <3fd174ff54b146228c505f23cf75ce71>:0
  at getWeather.RestService+<RefreshDataAsync>d__2.MoveNext () [0x0006e] in C:\Users\afelde\documents\visual studio 2017\Projects\getWeather\getWeather\getWeather\RestService.cs:30 }


问:
ios access to album, ok in ipad, not ok in iphones
Our app needs to access user's album.

NSPhotoLibraryUsageDescription is already set in Info.plist.

Works ok in ipad mini 1(ios 9.3.5), promote access to user's album and can access to user's album.
But not ok in iphones(iphone 6,ios 10), does not promote needs access to album and can not open user's album.

And there is no such setting as access to album in setting -> privacy.

Here is our info.plist:

edit:

It is a bug in our app.

Setting a wrong app route. ImagePicker library does not work correctly. Nothing to do with this plist. Has been fixed

答:
It is a bug in our app.

Setting a wrong app root.

ImagePicker library does not work correctly.

Nothing to do with this plist. Has been fixed


问:
How to parse complex data using alamofire object mapper?
I am trying to parse JOSN data using Alamofire object mapper..Done with basic things but stuck with complex things like

1.How can I access values in "settings_data"? (which is best way to access nested object)

2.where can i define .GET, .POST method type and where we should pass parameter ?  like for normal alamofire request we write as

```<code>  Alamofire.request(url, method: .get, parameters: nil, encoding: JSONEncoding.default)
            .responseJSON { response in
</code>```

is there any good way to achieve the same?

JOSN Response

```<code>{
    "err": 0,
    "result": [{
        "id": 71930,
        "account_id": 40869,
        "status": "enabled",
        "settings_data": {
            "time_format": "12h",
            "timezone": "US/Pacific",
            "fingerprint_versions": {
                "browser.browser-js": 1
            },
            "integrations": {
                "jira": {},
                "datadog": {},
                "bitbucket": {},
                "github": {},
                "trello": {
                    "board_id": "xxx",
                    "enabled": true,
                    "access_token_user_id": 1234,
                    "list_id": "xxxxx"
                },
                "slack": {
                    "channel_id": "xxxx",
                    "enabled": true,
                    "access_token_user_id": "xx"
                },
                "webhook": {},
                "victorops": {},
                "asana": {},
                "pivotal": {},
                "campfire": {},
                "sprintly": {},
                "pagerduty": {},
                "hipchat": {},
                "email": {
                    "enabled": true
                },
                "flowdock": {}
            }
        },
        "date_created": 1468068105,
        "date_modified": 1493409629,
        "name": "Android_ParentApp"
    }, {
        "id": 71931,
        "account_id": 40869,
        "status": "enabled",
        "settings_data": {
            "time_format": "12h",
            "timezone": "US/Pacific",
            "fingerprint_versions": {
                "browser.browser-js": 1
            },
            "integrations": {
                "jira": {},
                "datadog": {},
                "bitbucket": {},
                "github": {},
                "trello": {
                    "board_id": "xxxx",
                    "enabled": true,
                    "access_token_user_id": 1234,
                    "list_id": "xxxxx"
                },
                "slack": {
                    "channel_id": "xxxxx",
                    "enabled": true,
                    "access_token_user_id": "xxx"
                },
                "webhook": {},
                "victorops": {},
                "asana": {},
                "pivotal": {},
                "campfire": {},
                "sprintly": {},
                "pagerduty": {},
                "hipchat": {},
                "email": {
                    "enabled": true
                },
                "flowdock": {}
            }
        },
        "date_created": 1468068142,
        "date_modified": 1493409658,
        "name": "Android_TeacherApp"
    }]
}
</code>```

Model Class - Project.swift

```<code>import Foundation
import ObjectMapper

class Project: NSObject, Mappable {

    var projectId: Int?
    var accountId: Int?
    var dateCreated: Int?
    var dateModified: Int?
    var name: String?
    var status: String?

    override init() {
        super.init()
    }

    convenience required init?(map: Map) {
        self.init()
    }

    func mapping(map: Map) {
        projectId <- map["id"]
        accountId <- map["account_id"]
        dateCreated <- map["date_created"]
        dateModified <- map["date_modified"]
        name <- map["name"]
        status <- map["status"]
    }
}
</code>```

ViewController.swift

```<code>import UIKit
import Alamofire
import AlamofireObjectMapper

class ViewController: UIViewController {

    var projects:[Project] = []

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        fetchData()

    }

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

    func fetchData(){
        UIApplication.shared.isNetworkActivityIndicatorVisible = true
        let apiUrl = "https://raw.githubusercontent.com/javalnanda/AlamofireObjectMapperSample/master/AOMsample.json"
        Alamofire.request(apiUrl).validate().responseArray(keyPath: "result") { (response: DataResponse<[Project]>) in
            UIApplication.shared.isNetworkActivityIndicatorVisible = false
            switch response.result {
            case .success:
                print(response.result)
                self.projects = response.result.value ?? []
               // print("sss \(self.projects)")

                for project in self.projects {
                    print(  project.name ?? "")
                }
            case .failure(let error):
                print(error)
            }
        }
    }

}
</code>```

答:
The best way to implement these types of complex json is to split each subcategory to different objects and make them conform to protocol mappable. Then parse the values inside that function. See the example of SettingsModel with time_format and timezone parsed. You can implement the rest of the classes like this

```<code>    import Foundation
    import ObjectMapper

    class Project: NSObject, Mappable {

        var projectId: Int?
        var accountId: Int?
        var dateCreated: Int?
        var dateModified: Int?
        var name: String?
        var status: String?
        var settings: SettingsModel?
        override init() {
            super.init()
        }

        convenience required init?(map: Map) {
            self.init()
        }

        func mapping(map: Map) {
            projectId <- map["id"]
            accountId <- map["account_id"]
            dateCreated <- map["date_created"]
            dateModified <- map["date_modified"]
            name <- map["name"]
            status <- map["status"]
            settings <- map["settings_data"]
        }
    }

import UIKit
import ObjectMapper

class SettingsModel: NSObject,Mappable {

     var time_format:String?
     var timezone:String?

     override init() {
        super.init()
    }

    convenience required init?(map: Map) {
        self.init()
    }

    func mapping(map: Map) {
       time_format <- map["time_format"]
       timezone <- map["timezone"]
}
}
</code>```

If you don't wish to create new objects you can parse like

```<code>func mapping(map: Map) {
                projectId <- map["id"]
                accountId <- map["account_id"]
                dateCreated <- map["date_created"]
                dateModified <- map["date_modified"]
                name <- map["name"]
                status <- map["status"]
                time_format <- map["settings_data.time_format"]
                timezone <- map["settings_data.timezone"]

            }
</code>```

Body:
I am trying to parse JOSN data using Alamofire object mapper..Done with basic things but stuck with complex things like

1.How can I access values in "settings_data"? (which is best way to access nested object)

2.where can i define .GET, .POST method type and where we should pass parameter ?  like for normal alamofire request we write as

  Alamofire.request(url, method: .get, parameters: nil, encoding: JSONEncoding.default)
            .responseJSON { response in

is there any good way to achieve the same?

JOSN Response

{
    "err": 0,
    "result": [{
        "id": 71930,
        "account_id": 40869,
        "status": "enabled",
        "settings_data": {
            "time_format": "12h",
            "timezone": "US/Pacific",
            "fingerprint_versions": {
                "browser.browser-js": 1
            },
            "integrations": {
                "jira": {},
                "datadog": {},
                "bitbucket": {},
                "github": {},
                "trello": {
                    "board_id": "xxx",
                    "enabled": true,
                    "access_token_user_id": 1234,
                    "list_id": "xxxxx"
                },
                "slack": {
                    "channel_id": "xxxx",
                    "enabled": true,
                    "access_token_user_id": "xx"
                },
                "webhook": {},
                "victorops": {},
                "asana": {},
                "pivotal": {},
                "campfire": {},
                "sprintly": {},
                "pagerduty": {},
                "hipchat": {},
                "email": {
                    "enabled": true
                },
                "flowdock": {}
            }
        },
        "date_created": 1468068105,
        "date_modified": 1493409629,
        "name": "Android_ParentApp"
    }, {
        "id": 71931,
        "account_id": 40869,
        "status": "enabled",
        "settings_data": {
            "time_format": "12h",
            "timezone": "US/Pacific",
            "fingerprint_versions": {
                "browser.browser-js": 1
            },
            "integrations": {
                "jira": {},
                "datadog": {},
                "bitbucket": {},
                "github": {},
                "trello": {
                    "board_id": "xxxx",
                    "enabled": true,
                    "access_token_user_id": 1234,
                    "list_id": "xxxxx"
                },
                "slack": {
                    "channel_id": "xxxxx",
                    "enabled": true,
                    "access_token_user_id": "xxx"
                },
                "webhook": {},
                "victorops": {},
                "asana": {},
                "pivotal": {},
                "campfire": {},
                "sprintly": {},
                "pagerduty": {},
                "hipchat": {},
                "email": {
                    "enabled": true
                },
                "flowdock": {}
            }
        },
        "date_created": 1468068142,
        "date_modified": 1493409658,
        "name": "Android_TeacherApp"
    }]
}

Model Class - Project.swift

import Foundation
import ObjectMapper

class Project: NSObject, Mappable {

    var projectId: Int?
    var accountId: Int?
    var dateCreated: Int?
    var dateModified: Int?
    var name: String?
    var status: String?

    override init() {
        super.init()
    }

    convenience required init?(map: Map) {
        self.init()
    }

    func mapping(map: Map) {
        projectId <- map["id"]
        accountId <- map["account_id"]
        dateCreated <- map["date_created"]
        dateModified <- map["date_modified"]
        name <- map["name"]
        status <- map["status"]
    }
}

ViewController.swift

import UIKit
import Alamofire
import AlamofireObjectMapper

class ViewController: UIViewController {

    var projects:[Project] = []

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        fetchData()

    }

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

    func fetchData(){
        UIApplication.shared.isNetworkActivityIndicatorVisible = true
        let apiUrl = "https://raw.githubusercontent.com/javalnanda/AlamofireObjectMapperSample/master/AOMsample.json"
        Alamofire.request(apiUrl).validate().responseArray(keyPath: "result") { (response: DataResponse<[Project]>) in
            UIApplication.shared.isNetworkActivityIndicatorVisible = false
            switch response.result {
            case .success:
                print(response.result)
                self.projects = response.result.value ?? []
               // print("sss \(self.projects)")

                for project in self.projects {
                    print(  project.name ?? "")
                }
            case .failure(let error):
                print(error)
            }
        }
    }

}

Body:
The best way to implement these types of complex json is to split each subcategory to different objects and make them conform to protocol mappable. Then parse the values inside that function. See the example of SettingsModel with time_format and timezone parsed. You can implement the rest of the classes like this

    import Foundation
    import ObjectMapper

    class Project: NSObject, Mappable {

        var projectId: Int?
        var accountId: Int?
        var dateCreated: Int?
        var dateModified: Int?
        var name: String?
        var status: String?
        var settings: SettingsModel?
        override init() {
            super.init()
        }

        convenience required init?(map: Map) {
            self.init()
        }

        func mapping(map: Map) {
            projectId <- map["id"]
            accountId <- map["account_id"]
            dateCreated <- map["date_created"]
            dateModified <- map["date_modified"]
            name <- map["name"]
            status <- map["status"]
            settings <- map["settings_data"]
        }
    }

import UIKit
import ObjectMapper

class SettingsModel: NSObject,Mappable {

     var time_format:String?
     var timezone:String?

     override init() {
        super.init()
    }

    convenience required init?(map: Map) {
        self.init()
    }

    func mapping(map: Map) {
       time_format <- map["time_format"]
       timezone <- map["timezone"]
}
}

If you don't wish to create new objects you can parse like

func mapping(map: Map) {
                projectId <- map["id"]
                accountId <- map["account_id"]
                dateCreated <- map["date_created"]
                dateModified <- map["date_modified"]
                name <- map["name"]
                status <- map["status"]
                time_format <- map["settings_data.time_format"]
                timezone <- map["settings_data.timezone"]

            }


问:
Angular ng-hide not working
I am trying to make the ng-hide or ng-show in Angular working based on a $scope variable.

The
Hello
 should be hided now but it still shows..

What am I doing wrong?

Controller:

```<code>angular
    .module('myApp', [])
    .controller('MainController', MainController);

  function MainController($scope) {
    $scope.state = true;
  }
</code>```

Html:

```<code><body ng-controller="MainController">
    <h1>Hello Plunker!</h1>

    <div ng-hide"state">
      <p>hello</p>
    </div>

    {{ state }}
  </body>
</code>```

Plunker link
https://plnkr.co/edit/xxWVeThH8m218aS4Dago?p=preview

答:
```<code>angular.module('myApp', [])
        .controller('mainController', ['$scope',
            function($scope) {
                $scope.state = true;
            }
        ]);

<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>    angular.module('myApp', [])
            .controller('mainController', ['$scope',
                function($scope) {
                    $scope.state = true;
                }
            ]);</code>```

hello

        {{ state }}

```
</div>
</div>

</code>```

Title: Angular ng-hide not working

Body:
I am trying to make the ng-hide or ng-show in Angular working based on a $scope variable.

The
Hello
 should be hided now but it still shows..

What am I doing wrong?

Controller:

angular
    .module('myApp', [])
    .controller('MainController', MainController);

  function MainController($scope) {
    $scope.state = true;
  }

Html:

Hello Plunker!

hello

    {{ state }}

Plunker link
https://plnkr.co/edit/xxWVeThH8m218aS4Dago?p=preview

Body:
angular.module('myApp', [])
        .controller('mainController', ['$scope',
            function($scope) {
                $scope.state = true;
            }
        ]);

    angular.module('myApp', [])
            .controller('mainController', ['$scope',
                function($scope) {
                    $scope.state = true;
                }
            ]);

    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    <!-- need to assign value of ng-app to module name for automatically bootstrapping the angularjs application -->
    <div ng-app="myApp" ng-controller="mainController">
        <div ng-hide = "state"> <!-- here -->
          <p>hello</p>
        </div>
        {{ state }}
      </div>


问:
dynamic declaration/query in oracle 9i
In Oracle, given a list of table names, I want to perform 'select column1 into var1 from table' statements on a mass number of tables. And I want to do this for all columns of a table. I cannot declare the type of var1 until the query with user_tab_columns returns the column's type. I tried to declare var1 as sys.anytype but got ORA-00932 with error message such as "inconsistent datatypes: expected CHAR got CHAR".

So how can I get past this error or how can I dynamically declare a variable? Many thanks.

答:
Craig is right you should probably declare it as a VARCHAR2 instad of an anytype.

This article by Jeff Hunter has a nice function that makes this easy to populate your variable in way that won't break if your data can't be converted.

```<code>CREATE OR REPLACE FUNCTION getData(data IN SYS.ANYDATA)
    RETURN VARCHAR2
    AS
      l_varchar2   VARCHAR2(4000);
      l_rc         NUMBER;
    BEGIN

      CASE data.getTypeName
        when 'SYS.NUMBER' then
          l_rc := data.getNumber(l_varchar2);
        when 'SYS.DATE' then
          l_rc := data.getDate(l_varchar2);
        when 'SYS.VARCHAR2' then
          l_rc := data.getVarchar2(l_varchar2);
        else
          l_varchar2 := '** unknown **';
      END CASE;

      RETURN l_varchar2;

    END;
</code>```

Title: dynamic declaration/query in oracle 9i

Body:
Craig is right you should probably declare it as a VARCHAR2 instad of an anytype.

This article by Jeff Hunter has a nice function that makes this easy to populate your variable in way that won't break if your data can't be converted.

CREATE OR REPLACE FUNCTION getData(data IN SYS.ANYDATA)
    RETURN VARCHAR2
    AS
      l_varchar2   VARCHAR2(4000);
      l_rc         NUMBER;
    BEGIN

      CASE data.getTypeName
        when 'SYS.NUMBER' then
          l_rc := data.getNumber(l_varchar2);
        when 'SYS.DATE' then
          l_rc := data.getDate(l_varchar2);
        when 'SYS.VARCHAR2' then
          l_rc := data.getVarchar2(l_varchar2);
        else
          l_varchar2 := '** unknown **';
      END CASE;

      RETURN l_varchar2;

    END;


问:
javascript merge array of objects, resulting object values in array
Would like to merge an array of objects resulting in an object of unique keys and array of values (duplication of values is ok). Solutions in vanilla JS or lodash preferred.

eg - from this:

```<code>[{
  a: 1,
  b: 2
}, {
  a: 1,
  c: 3
}]
</code>```

to this:

```<code>{
  a: [1, 1],
  b: [2],
  c: [3]
}
</code>```

答:
ES6 variant:

const a = [{
  a: 1,
  b: 2
}, {
  a: 1,
  c: 3
}]

const b = a.reduce((acc, cur) => Object.assign(acc,
  ...Object.keys(cur).map(key => ({ [key]: (acc[key] || []).concat(cur[key]) })))
, {})

console.log(b)```

Body:
Would like to merge an array of objects resulting in an object of unique keys and array of values (duplication of values is ok). Solutions in vanilla JS or lodash preferred.

eg - from this:

[{
  a: 1,
  b: 2
}, {
  a: 1,
  c: 3
}]

to this:

{
  a: [1, 1],
  b: [2],
  c: [3]
}


问:
Find the Run Time of Select Ruby Code

Problem

Howdy guys, so I want to find the run time of a block of code in Ruby, but I am not entirely sure as to how I could do it. I want to run some code, and then output how long it took to run that code because I have a super huge program and the run time changes a lot. I want to make sure it always has a consistent run time (I could do it by sleeping it for a fraction of a second) but that isn't my problem. I want to find out how long the run time actually is so the program can know if it needs to slow things down or speed things up.

My Thoughts

So, I have an idea as to how it could work. I have never used Time in ruby but I have an idea as to how I could use that. I could have a variable equal to the time (in milliseconds) and then another variable that I make at the end of the code block that does it again, and then I just subtract them, but I have (1) never used Time and (2) I don't actually know if that is the best way.

Thanks in advance!

答:
[http://ruby-doc.org/core-1.9.3/Time.html
You want to to use the Time object. (Time Docs)

For example,

```<code>  start = Time.now
 # code to time
 finish = Time.now

 diff = finish - start
</code>```

diff would be in seconds, as a floating point number.

EDIT: end is reserved.
or you can use
    require 'benchmark'

```<code> def foo
  time = Benchmark.measure {
   code to test
   }
</code>```

puts time.real #or save it to logs
end
Sample output:

```<code>   2.2.3 :001 > foo
   5.230000   0.020000   5.250000 (  5.274806)
</code>```

Values are CPU time, system time, total and real elapsed time.
[http://ruby-doc.org/stdlib-2.0.0/libdoc/benchmark/rdoc/Benchmark.html#method-c-bm
Source: Ruby docs.

Title: Find the Run Time of Select Ruby Code

Body:
[http://ruby-doc.org/core-1.9.3/Time.html
You want to to use the Time object. (Time Docs)

For example,

  start = Time.now
 # code to time
 finish = Time.now

 diff = finish - start

diff would be in seconds, as a floating point number.

EDIT: end is reserved.
or you can use
    require 'benchmark'

 def foo
  time = Benchmark.measure {
   code to test
   }

puts time.real #or save it to logs
end
Sample output:

   2.2.3 :001 > foo
   5.230000   0.020000   5.250000 (  5.274806)

Values are CPU time, system time, total and real elapsed time.
[http://ruby-doc.org/stdlib-2.0.0/libdoc/benchmark/rdoc/Benchmark.html#method-c-bm
Source: Ruby docs.


问:
classifier equivalent on custom maven plugins
I have a project with a Scala core library, a maven plug-in, a gradle plug-in and a bunch of other bits that are not needed for this question. It is built using gradle. (It seems easier to build a maven plug-in using gradle than a gradle plug-in using maven)

Due to Scala versions and compatibility different projects using the maven plug-in need different builds of the core library. Currently I need to build against 2.11.7 and 2.12.1. The core library can be solved with classifiers quite easily. E.G :

```<code><dependency>
    <groupId>org.catapult.sa</groupId>
    <artifactId>tribble-core</artifactId>
    <version>0.5-SNAPSHOT</version>
    <classifier>2.11.7</classifier>
    <scope>test</scope>
</dependency>
</code>```

However maven plugin config does not have classifiers so we can't do:

```<code><plugin>
    <groupId>org.catapult.sa</groupId>
    <artifactId>tribble-maven-plugin</artifactId>
    <version>0.5-SNAPSHOT</version>
    <classifier>2.11.7</classifier> <!-- this errors with Unrecognised tag: 'classifier'-->
    <configuration>...</configuration>
</plugin>
</code>```

The code for both versions of the maven plug-in is exactly the same it just has slightly different dependencies.  The code in core is also exactly the same but built against different compilers.

I can handle this manually with a setting in the build, changing the artifactId of the maven plugin, and building twice, but is that the "right" way to solve this problem? Is there a better way or more automate-able way?

答:
Classifiers can be added at the execution configuration level, an example:

```<code>  <plugins>
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-jar-plugin</artifactId>
      <version>2.6</version>
      <executions>
        <execution>
          <id>pre-process-classes</id>
          <phase>compile</phase>
          <goals>
            <goal>jar</goal>
          </goals>
          <configuration>
            <classifier>pre-process</classifier> <!-- here -->
          </configuration>
        </execution>
      </executions>
    </plugin>
  </plugins>
</code>```

it's a bit buried in the detail of the POM reference in fact the example above is from the PluginManagement section but the principles are the same.
This should allow you to target for each version of build you require without having to set the artifactid manually.

Body:
I have a project with a Scala core library, a maven plug-in, a gradle plug-in and a bunch of other bits that are not needed for this question. It is built using gradle. (It seems easier to build a maven plug-in using gradle than a gradle plug-in using maven)

Due to Scala versions and compatibility different projects using the maven plug-in need different builds of the core library. Currently I need to build against 2.11.7 and 2.12.1. The core library can be solved with classifiers quite easily. E.G :

<dependency>
    <groupId>org.catapult.sa</groupId>
    <artifactId>tribble-core</artifactId>
    <version>0.5-SNAPSHOT</version>
    <classifier>2.11.7</classifier>
    <scope>test</scope>
</dependency>

However maven plugin config does not have classifiers so we can't do:

<plugin>
    <groupId>org.catapult.sa</groupId>
    <artifactId>tribble-maven-plugin</artifactId>
    <version>0.5-SNAPSHOT</version>
    <classifier>2.11.7</classifier>
    <configuration>...</configuration>
</plugin>

The code for both versions of the maven plug-in is exactly the same it just has slightly different dependencies.  The code in core is also exactly the same but built against different compilers.

I can handle this manually with a setting in the build, changing the artifactId of the maven plugin, and building twice, but is that the "right" way to solve this problem? Is there a better way or more automate-able way?

Body:
Classifiers can be added at the execution configuration level, an example:

  <plugins>
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-jar-plugin</artifactId>
      <version>2.6</version>
      <executions>
        <execution>
          <id>pre-process-classes</id>
          <phase>compile</phase>
          <goals>
            <goal>jar</goal>
          </goals>
          <configuration>
            <classifier>pre-process</classifier> <!-- here -->
          </configuration>
        </execution>
      </executions>
    </plugin>
  </plugins>

it's a bit buried in the detail of the POM reference in fact the example above is from the PluginManagement section but the principles are the same.
This should allow you to target for each version of build you require without having to set the artifactid manually.


问:
Log4j2 create new log file if not exist
I am using RollingRandomAccessFile appende for log4j logging and everything is working fine ,

```<code>    <RollingRandomAccessFile name="xxx.FLT" fileName="${sys:xxx.log.path}FLT.log" filePattern="${sys:xxx.log.path}FLT.log.%i" append="true" immediateFlush="true" bufferSize="262144">
        <PatternLayout pattern="%d{MM-dd-yyyy HH:mm:ss,SSS} [%t] %level{WARN=WARNING, DEBUG=FINE, ERROR=SEVERE} %logger{36} - %convInfo %msg%n"/>
        <Policies>
            <SizeBasedTriggeringPolicy size="100MB"/>
        </Policies>
        <DefaultRolloverStrategy fileIndex="max" min="1" max="5" compressionLevel="3"/>
    </RollingRandomAccessFile>
</code>```

At the application startup all the log files are created. I have an another process that remove log file from the disc if they are not getting update after some time.

if this process removed a log file, it will not create again at a new log event.

I want to create new log file if not exist in the given location at the time of new log event has been occurred

I know when the application restart missing files will be created again , but i want to create log file at the time of a log event occurred.

I am preferred to have a configuration level change other than a code level change.

答: All you need to do is to make sure your removal of log files is only handled by log4j. This way you will never loose the current log file.</p>

Title: Log4j2 create new log file if not exist

Body:
I am using RollingRandomAccessFile appende for log4j logging and everything is working fine ,

    <RollingRandomAccessFile name="xxx.FLT" fileName="${sys:xxx.log.path}FLT.log" filePattern="${sys:xxx.log.path}FLT.log.%i" append="true" immediateFlush="true" bufferSize="262144">
        <PatternLayout pattern="%d{MM-dd-yyyy HH:mm:ss,SSS} [%t] %level{WARN=WARNING, DEBUG=FINE, ERROR=SEVERE} %logger{36} - %convInfo %msg%n"/>
        <Policies>
            <SizeBasedTriggeringPolicy size="100MB"/>
        </Policies>
        <DefaultRolloverStrategy fileIndex="max" min="1" max="5" compressionLevel="3"/>
    </RollingRandomAccessFile>

At the application startup all the log files are created. I have an another process that remove log file from the disc if they are not getting update after some time.

if this process removed a log file, it will not create again at a new log event.

I want to create new log file if not exist in the given location at the time of new log event has been occurred

I know when the application restart missing files will be created again , but i want to create log file at the time of a log event occurred.

I am preferred to have a configuration level change other than a code level change.


问:
update and print array element?
You are given an array of N positive integers, A1, A2 ,…, AN.

Also, given a Q updates of form:- i j: Update Ai = j. 1 ≤ i ≤ N.

Perform all updates and after each such update report mode of the array. Therefore, return an array of Q elements, where ith element is mode of the array after ith update has been executed.

Notes

Mode is the most frequently occuring element on the array.

If multiple modes are possible, return the smallest one.

Update array input is via a Q*2 array, where each row represents a update.

For example,

```<code>A=[2, 2, 2, 3, 3]

Updates=    [ [1, 3] ]
            [ [5, 4] ]
            [ [2, 4] ]

A = [3, 2, 2, 3, 3] after 1st update.
3 is mode.

A = [3, 2, 2, 3, 4] after 2nd update.
2 and 3 both are mode. Return smaller i.e. 2.

A = [3, 4, 2, 3, 4] after 3rd update.
3 and 4 both are mode. Return smaller i.e. 3.

Return array [3, 2, 3].
Constraints
1 ≤ N, Q ≤ 105
1 ≤ j, Ai ≤ 109
</code>```

What's wrong with my implementation using simple array?

```<code>  /**
     * @input A : Integer array
     * @input n1 : Integer array's ( A ) length
     * @input B : 2D integer array
     * @input n21 : Integer array's ( B ) rows
     * @input n22 : Integer array's ( B ) columns
     *
     * @Output Integer array. You need to malloc memory, and fill the length in len1
     */
    int* getMode(int* A, int n1, int** B, int n21, int n22, int *len1) {
        int *ans = (int *) malloc (sizeof(int)); // dynamic allocation of array
        int x = 0,i,j;
        for(i = 0; i < n1 ; i ++ )
            for(j = 0; j < n21; j++)
                A[B[j][0]] = B[j][1];
            // frequency calculate

            int c[n1] ;

            for(i = 0; i < n1; i++)
                c[i] = 0;

            for(i = 0; i < n1; i++)
                c[A[i]]++;

            int mx = INT_MAX;
            int idx = -1, idx1 = -1;

            for(i = 0; i < n1; i++){
                if (mx  < A[i]){
                    idx1 = idx;
                    mx = A[i];
                    idx = i;
                }

            int p;
            if (A[idx]> A[idx1])
                p = A[idx];
            else
                p = A[idx1];

            ans[x++] = p; }

        return ans; }
</code>```

How can we solve it? Can anyone please suggest some answer?

答:
My answer in c++ :</p>

```<code>class compare
{
    public:
    bool operator()(pair<int,int> p1,pair<int,int> p2)
    {
        if(p1.first==p2.first)
        return p1.second>p2.second;
        return p1.first<p2.first;
    }
};
vector<int> Solution::getMode(vector<int> &a, vector<vector<int> > &b) {
    map<int,int> m;// map store the exact count of elements
    int n=a.size();
    for(int i=0;i<n;i++)
    {
        m[a[i]]++;
    }
    vector<int> ans;

// take a max heap which store element count and its value
    priority_queue<pair<int,int> ,vector<pair<int,int> >,compare >pq;
    for(int i=0;i<n;i++)
    {
        pq.push(make_pair(m[a[i]],a[i]));
    }
    int i=0,q=b.size();
    while(i<q)
    {
        int index=b[i][0]-1;
        int val=b[i][1];
        int val1=a[index];
        a[index]=val;
        if(val!=val1)
        {
            m[val1]--;
        m[val]++;
        pq.push(make_pair(m[val1],val1));
        pq.push(make_pair(m[val],val));
        }
        while(true)
        {
            pair<int,int> t=pq.top();
            int cnt=t.first;int vall=t.second;
            if(m[vall]==cnt)
            {

         // when top of heap has cnt same as in map then this the answer for the ith query
                ans.push_back(vall);
                break;
            }
            else
            pq.pop();
        }
        i++;
    }
    return ans;
}
</code>```

Title: update and print array element?

Body:
You are given an array of N positive integers, A1, A2 ,…, AN.

Also, given a Q updates of form:- i j: Update Ai = j. 1 ≤ i ≤ N.

Perform all updates and after each such update report mode of the array. Therefore, return an array of Q elements, where ith element is mode of the array after ith update has been executed.

Notes

Mode is the most frequently occuring element on the array.

If multiple modes are possible, return the smallest one.

Update array input is via a Q*2 array, where each row represents a update.

For example,

A=[2, 2, 2, 3, 3]

Updates=    [ [1, 3] ]
            [ [5, 4] ]
            [ [2, 4] ]

A = [3, 2, 2, 3, 3] after 1st update.
3 is mode.

A = [3, 2, 2, 3, 4] after 2nd update.
2 and 3 both are mode. Return smaller i.e. 2.

A = [3, 4, 2, 3, 4] after 3rd update.
3 and 4 both are mode. Return smaller i.e. 3.

Return array [3, 2, 3].
Constraints
1 ≤ N, Q ≤ 105
1 ≤ j, Ai ≤ 109

What's wrong with my implementation using simple array?

  /**
     * @input A : Integer array
     * @input n1 : Integer array's ( A ) length
     * @input B : 2D integer array
     * @input n21 : Integer array's ( B ) rows
     * @input n22 : Integer array's ( B ) columns
     *
     * @Output Integer array. You need to malloc memory, and fill the length in len1
     */
    int* getMode(int* A, int n1, int** B, int n21, int n22, int *len1) {
        int *ans = (int *) malloc (sizeof(int)); // dynamic allocation of array
        int x = 0,i,j;
        for(i = 0; i < n1 ; i ++ )
            for(j = 0; j < n21; j++)
                A[B[j][0]] = B[j][1];
            // frequency calculate

            int c[n1] ;

            for(i = 0; i < n1; i++)
                c[i] = 0;

            for(i = 0; i < n1; i++)
                c[A[i]]++;

            int mx = INT_MAX;
            int idx = -1, idx1 = -1;

            for(i = 0; i < n1; i++){
                if (mx   A[idx1])
                p = A[idx];
            else
                p = A[idx1];

            ans[x++] = p; }

        return ans; }

How can we solve it? Can anyone please suggest some answer?

Body:
My answer in c++ :

class compare
{
    public:
    bool operator()(pair<int,int> p1,pair<int,int> p2)
    {
        if(p1.first==p2.first)
        return p1.second>p2.second;
        return p1.first<p2.first;
    }
};
vector<int> Solution::getMode(vector<int> &a, vector<vector<int> > &b) {
    map<int,int> m;// map store the exact count of elements
    int n=a.size();
    for(int i=0;i<n;i++)
    {
        m[a[i]]++;
    }
    vector<int> ans;

// take a max heap which store element count and its value
    priority_queue<pair<int,int> ,vector<pair<int,int> >,compare >pq;
    for(int i=0;i<n;i++)
    {
        pq.push(make_pair(m[a[i]],a[i]));
    }
    int i=0,q=b.size();
    while(i<q)
    {
        int index=b[i][0]-1;
        int val=b[i][1];
        int val1=a[index];
        a[index]=val;
        if(val!=val1)
        {
            m[val1]--;
        m[val]++;
        pq.push(make_pair(m[val1],val1));
        pq.push(make_pair(m[val],val));
        }
        while(true)
        {
            pair<int,int> t=pq.top();
            int cnt=t.first;int vall=t.second;
            if(m[vall]==cnt)
            {

         // when top of heap has cnt same as in map then this the answer for the ith query
                ans.push_back(vall);
                break;
            }
            else
            pq.pop();
        }
        i++;
    }
    return ans;
}


问:
how to supply only second optional parameter in php?
I have this function:

```<code>function generic_notify($subject = "notify triggered", $message = "<p>Generic notification</p>", $to = "pavel.janicek@mydomain.mydomain"){
    EDD()->emails->send( $to, $subject, $message );
}
</code>```

In some cases, I am completely fine to just call generic_notify(); and know that some function was called, because the above will send me mail.

In other cases, I would like to just change message, or just subject or send it to other email.

If I wanted to just change the message, is it possible? And if yes, how?

答:
You can't but if I were you just put a condition inside that function

```<code>function generic_notify($subject = null, $message = null, $to = null){

    // your default value
    $defaultSubject = "notify triggered";
    $defaultMessage = "<p>Generic notification</p>";
    $defaultTo = "pavel.janicek@mydomain.mydomain";

    $to = (!empty($to)) ? $to : $defaultTo;
    $subject = (!empty($subject)) ? $subject : $defaultSubject;
    $message = (!empty($message)) ? $message : $defaultMessage;

        echo "Subject: ".$subject ."<br>";
        echo "Message: ".$message ."<br>";
        echo "TO: ".$to."<br>";
}

// if you want not to change all the default parameter just leave blank
generic_notify();

// if you want to change the default parameter just put a value that is not null on it
generic_notify(null, '<p>Change Message</p>', null);
</code>```

Demo

Body:
I have this function:

function generic_notify($subject = "notify triggered", $message = "
Generic notification
", $to = "pavel.janicek@mydomain.mydomain"){
    EDD()->emails->send( $to, $subject, $message );
}

In some cases, I am completely fine to just call generic_notify(); and know that some function was called, because the above will send me mail.

In other cases, I would like to just change message, or just subject or send it to other email.

If I wanted to just change the message, is it possible? And if yes, how?

Body:
You can't but if I were you just put a condition inside that function

function generic_notify($subject = null, $message = null, $to = null){

    // your default value
    $defaultSubject = "notify triggered";
    $defaultMessage = "<p>Generic notification</p>";
    $defaultTo = "pavel.janicek@mydomain.mydomain";

    $to = (!empty($to)) ? $to : $defaultTo;
    $subject = (!empty($subject)) ? $subject : $defaultSubject;
    $message = (!empty($message)) ? $message : $defaultMessage;

        echo "Subject: ".$subject ."<br>";
        echo "Message: ".$message ."<br>";
        echo "TO: ".$to."<br>";
}

// if you want not to change all the default parameter just leave blank
generic_notify();

// if you want to change the default parameter just put a value that is not null on it
generic_notify(null, '<p>Change Message</p>', null);

Demo


问:
endeca property value in lowercase
I have to store value in one Endeca property but in lowercase. Values can be in uppercase or in lowercase in the source file but I have to store it in lowercase in the Endeca property.

Any pointer on how I can proceed will be helpful.

Thanks
Neha

答:
This can be done using oracle endeca developer studio.

1) Firstly open your pipeline using developer studio which is in app path under config folder.

2) Then under the project explorer window, click on dimension tab.

3) Finally at the top pane, click on values to add for the property you want.

4) Run the baseline update.

Title: endeca property value in lowercase


问:
How to use Angular UI Bootstrap Tooltip
I want to use Angular UI Bootstrap Tooltip ui.bootstrap.tooltip separated.

I'm able to use tooltip by adding full ui-bootstrap file, like:

```<code><script src="http://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.13.0.js"></script>
<script>var App = angular.module("App", ['ui.bootstrap']);</script>
</code>```

But I want to include only tooltip functionality instead of adding full UI Bootstrap featured.

答:
You can use this block of code

```<code><div ng-app="myApp" ng-controller="TooltipDemoCtrl">
  <div class="well">
    <div>Dynamic Tooltip Popup Text <input type="text" ng-model="dynamicTooltip"></div>
    <div>Dynamic Tooltip Placement <input type="text" ng-model="dynamicTooltipPlacement"></div>
    <p>
      Need some <a><span tooltip="{{dynamicTooltip}}" tooltip-placement={{dynamicTooltipPlacement}}>tips</span></a> ?
    </p>
  </div>
</div>
</code>```

Controller

```<code>var app = angular.module('myApp', ['ui.bootstrap']);
var TooltipDemoCtrl = function ($scope) {

  $scope.dynamicTooltip = "Here is the help";
  $scope.dynamicTooltipText = "tips";

};
</code>```

Here is the working link to JSFIDDLE to see it working.

Title: How to use Angular UI Bootstrap Tooltip

Body:
I want to use Angular UI Bootstrap Tooltip ui.bootstrap.tooltip separated.

I'm able to use tooltip by adding full ui-bootstrap file, like:

But I want to include only tooltip functionality instead of adding full UI Bootstrap featured.

Body:
You can use this block of code

<div ng-app="myApp" ng-controller="TooltipDemoCtrl">
  <div class="well">
    <div>Dynamic Tooltip Popup Text <input type="text" ng-model="dynamicTooltip"></div>
    <div>Dynamic Tooltip Placement <input type="text" ng-model="dynamicTooltipPlacement"></div>
    <p>
      Need some <a><span tooltip="{{dynamicTooltip}}" tooltip-placement={{dynamicTooltipPlacement}}>tips</span></a> ?
    </p>
  </div>
</div>

Controller

var app = angular.module('myApp', ['ui.bootstrap']);
var TooltipDemoCtrl = function ($scope) {

  $scope.dynamicTooltip = "Here is the help";
  $scope.dynamicTooltipText = "tips";

};

Here is the working link to JSFIDDLE to see it working.


问:
Center align the absolute div without using left:0, right:0, width:100%
How to center a absolute div without using left, right and width:100%? And the width should be auto

```<code>div{
    position: absolute;
    width: 100%;
    margin: 0 auto;
    display: table;
}
</code>```

答:
I just centered this horizontally as OP didn't state whether it is centered horizontally or vertically

div {
  position: relative;
  width: 300px;
  height: 200px;
  background-color:blue;
}

p {
  position: absolute;
  margin: 0 50%;
  transform:translate(-50%, 0);
  width: auto;
  background-color: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <p> SAMPLE CONTENT </p>
</div></code>```

Body:
How to center a absolute div without using left, right and width:100%? And the width should be auto

div{
    position: absolute;
    width: 100%;
    margin: 0 auto;
    display: table;
}

Body:
I just centered this horizontally as OP didn't state whether it is centered horizontally or vertically

div {
  position: relative;
  width: 300px;
  height: 200px;
  background-color:blue;
}

p {
  position: absolute;
  margin: 0 50%;
  transform:translate(-50%, 0);
  width: auto;
  background-color: red;
}

<div>
  <p> SAMPLE CONTENT </p>
</div>


问:
jquery slow when using children() with rows
Recently I asked a question on SO regarding changing row background color on click and hover using jquery.  Below is the link to it, and I implemented the solution marked as answer. The problem is when I am having lot of rows, the hover as well as click takes a lot of time. I am using IE8 with latest version of jquery. Below is the link to question

jquery row hover and click events

Here is the code I implemented:

http://jsfiddle.net/EPUrh/

if you hover and click, its working and its fast for less rows, but if there are lot of rows/columns, it gets really slow and sometimes throws an error if I want to stop the script. When I compare the same in Firefox, it very fast. I have problem with this only in IE8. Can any one suggest a workaround for this?

答:
Some random comments that may help:

You could use tr.clicked td as your css selector then apply the "clicked" class to the row instead of each individual table cell...  It would probably be much faster than needing to query all of the cells in the table.  Here is a jsFiddle example of how much cleaner it can be when you rely upon the CSS to handle the "children" portion that for you.

Also, instead of .siblings().children() try .parent().find('td').not($this.children()) -- that would end up using getElementsByTagName as opposed to having to call childNodes on all the tr and then append those lists to each other...

Also - anytime you are working on performance issues like this, try running some sample code through jsperf - it will help you test two different methods .parent().find('td') vs .siblings().children() for instance this test shows that the siblings().children() method is ~ 78% slower than .parent().find('td').not() when using chrome, 38% slower in safari.  I don't have IE8, but I imagine you would see significant improvement using that method.

There are a few good tips on this blog post about performance of selectors, etc.  Pay very close attention to the Bonus Tip – Storing jQuery results for later section.


问:
Expected condition failed: waiting for visibility of element located by By.xpath
I am trying to click on Sign in link on site alibaba.com

This is my test case:

```<code>public class TestCase {

    public static void main(String[] args) throws InterruptedException {
        // TODO Auto-generated method stub

        String URL = "http://www.alibaba.com/";
        WebDriver driver;
        System.setProperty("webdriver.chrome.driver",
                "D:\\chromedriver_win32\\chromedriver.exe");
        driver = new ChromeDriver();
        driver.get(URL);
        Thread.sleep(2000);
        SignIn.SignIn_click(driver).click();
    }

}
</code>```

This is object class where in am locating the web element

```<code>package PageObjects;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

public class SignIn {

    private static WebElement element = null;

    public static WebElement SignIn_click(WebDriver driver) {
        element = (new WebDriverWait(driver, 10)).until(ExpectedConditions
                .visibilityOfElementLocated(By
                        .xpath("//a[@data-val='ma_signin']")));
        element = driver.findElement(By
                .xpath("//a[@data-val='ma_signin']"));
        return element;

    }

}
</code>```

But when I run this code , I'm always getting this exception:

```<code>Exception in thread "main" org.openqa.selenium.TimeoutException: Expected condition failed: waiting for visibility of element located by By.xpath: //a[@data-val='ma_signin'] (tried for 10 second(s) with 500 MILLISECONDS interval)
    Build info: version: 'unknown', revision: '86a5d70', time: '2017-02-16 07:47:51 -0800'
    System info: host: 'ANUM-PC', ip: '172.16.11.162', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0_121'
    Driver info: org.openqa.selenium.chrome.ChromeDriver
    Capabilities [{applicationCacheEnabled=false, rotatable=false, mobileEmulationEnabled=false, networkConnectionEnabled=false, chrome={chromedriverVersion=2.30.477700 (0057494ad8732195794a7b32078424f92a5fce41), userDataDir=C:\Users\Anum\AppData\Local\Temp\scoped_dir1716_14873}, takesHeapSnapshot=true, pageLoadStrategy=normal, databaseEnabled=false, handlesAlerts=true, hasTouchScreen=false, version=59.0.3071.115, platform=XP, browserConnectionEnabled=false, nativeEvents=true, acceptSslCerts=true, locationContextEnabled=true, webStorageEnabled=true, browserName=chrome, takesScreenshot=true, javascriptEnabled=true, cssSelectorsEnabled=true, unexpectedAlertBehaviour=}]
    Session ID: d0c1083c113270bd4ded08846544878e
        at org.openqa.selenium.support.ui.WebDriverWait.timeoutException(WebDriverWait.java:80)
        at org.openqa.selenium.support.ui.FluentWait.until(FluentWait.java:257)
        at PageObjects.SignIn.SignIn_click(SignIn.java:15)
        at AutomationFramework.TestCase.main(TestCase.java:24)
</code>```

Please help me on this.

答:
Here is the Answer to your Question:

The xpath you have constructed //a[@data-val='ma_signin'] is not unique. The xpath matches with 3 nodes. If you want to click on Sign In button you can consider using this unique xpath:

```<code>//div[@id='J_SC_header']//div[@class='sc-hd-row sc-hd-main']//a[@rel='nofollow'][@data-val='ma_signin']
</code>```

Body:
I am trying to click on Sign in link on site alibaba.com

This is my test case:

public class TestCase {

    public static void main(String[] args) throws InterruptedException {
        // TODO Auto-generated method stub

        String URL = "http://www.alibaba.com/";
        WebDriver driver;
        System.setProperty("webdriver.chrome.driver",
                "D:\\chromedriver_win32\\chromedriver.exe");
        driver = new ChromeDriver();
        driver.get(URL);
        Thread.sleep(2000);
        SignIn.SignIn_click(driver).click();
    }

}

This is object class where in am locating the web element

package PageObjects;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

public class SignIn {

    private static WebElement element = null;

    public static WebElement SignIn_click(WebDriver driver) {
        element = (new WebDriverWait(driver, 10)).until(ExpectedConditions
                .visibilityOfElementLocated(By
                        .xpath("//a[@data-val='ma_signin']")));
        element = driver.findElement(By
                .xpath("//a[@data-val='ma_signin']"));
        return element;

    }

}

But when I run this code , I'm always getting this exception:

Exception in thread "main" org.openqa.selenium.TimeoutException: Expected condition failed: waiting for visibility of element located by By.xpath: //a[@data-val='ma_signin'] (tried for 10 second(s) with 500 MILLISECONDS interval)
    Build info: version: 'unknown', revision: '86a5d70', time: '2017-02-16 07:47:51 -0800'
    System info: host: 'ANUM-PC', ip: '172.16.11.162', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0_121'
    Driver info: org.openqa.selenium.chrome.ChromeDriver
    Capabilities [{applicationCacheEnabled=false, rotatable=false, mobileEmulationEnabled=false, networkConnectionEnabled=false, chrome={chromedriverVersion=2.30.477700 (0057494ad8732195794a7b32078424f92a5fce41), userDataDir=C:\Users\Anum\AppData\Local\Temp\scoped_dir1716_14873}, takesHeapSnapshot=true, pageLoadStrategy=normal, databaseEnabled=false, handlesAlerts=true, hasTouchScreen=false, version=59.0.3071.115, platform=XP, browserConnectionEnabled=false, nativeEvents=true, acceptSslCerts=true, locationContextEnabled=true, webStorageEnabled=true, browserName=chrome, takesScreenshot=true, javascriptEnabled=true, cssSelectorsEnabled=true, unexpectedAlertBehaviour=}]
    Session ID: d0c1083c113270bd4ded08846544878e
        at org.openqa.selenium.support.ui.WebDriverWait.timeoutException(WebDriverWait.java:80)
        at org.openqa.selenium.support.ui.FluentWait.until(FluentWait.java:257)
        at PageObjects.SignIn.SignIn_click(SignIn.java:15)
        at AutomationFramework.TestCase.main(TestCase.java:24)

Please help me on this.

Body:
Here is the Answer to your Question:

The xpath you have constructed //a[@data-val='ma_signin'] is not unique. The xpath matches with 3 nodes. If you want to click on Sign In button you can consider using this unique xpath:

//div[@id='J_SC_header']//div[@class='sc-hd-row sc-hd-main']//a[@rel='nofollow'][@data-val='ma_signin']


问:
View's height is 0 under certain conditions when transitioning between Activities
Here is the context: I have a Activity with complex layout to which I want to transition using relatively complex Transitions. The catch is that I need to position one view (scroll_frame) below the image (I can't use XML), so I need to know it's height. It works fine the first time, however after some number of going back and forth between Activities image's height is suddenly zero (caching, race conditions?)

Here is the snippet of onCreate:

```<code>    super.onCreate(savedInstanceState)
    postponeEnterTransition()
    setContentView(R.layout.some_id)

    // ... non-essential stuff.

    Glide.with(this)
            .load([some resource id])
            .into(object : SimpleTarget<Drawable>() {
                override fun onResourceReady(d: Drawable?, t: Transition<in Drawable>?) {
                    // Prepare image.
                    image.setImageDrawable(d)

                    val margin = Math.max(image.measuredHeight, 0)

                    // ... non-essential stuff

                    layoutParams.setMargins(0, margin, 0, 0)

                    // Critical part.
                    scroll_frame?.layoutParams = layoutParams

                    // Start transition.
                    startPostponedEnterTransition()
                }
            })
</code>```

答:
The thing is that views are not given the measured height in onCreate.

Try this:

```<code>  //Put this in onCreate
  imageView.post(new Runnable() {
        @Override
        public void run() {
            //This is called after view measurements are done.
            //Run your glide code here.
        }
    });
</code>```

Hope this helps.

Body:
Here is the context: I have a Activity with complex layout to which I want to transition using relatively complex Transitions. The catch is that I need to position one view (scroll_frame) below the image (I can't use XML), so I need to know it's height. It works fine the first time, however after some number of going back and forth between Activities image's height is suddenly zero (caching, race conditions?)

Here is the snippet of onCreate:

    super.onCreate(savedInstanceState)
    postponeEnterTransition()
    setContentView(R.layout.some_id)

    // ... non-essential stuff.

    Glide.with(this)
            .load([some resource id])
            .into(object : SimpleTarget<Drawable>() {
                override fun onResourceReady(d: Drawable?, t: Transition<in Drawable>?) {
                    // Prepare image.
                    image.setImageDrawable(d)

                    val margin = Math.max(image.measuredHeight, 0)

                    // ... non-essential stuff

                    layoutParams.setMargins(0, margin, 0, 0)

                    // Critical part.
                    scroll_frame?.layoutParams = layoutParams

                    // Start transition.
                    startPostponedEnterTransition()
                }
            })

Body:
The thing is that views are not given the measured height in onCreate.

Try this:

  //Put this in onCreate
  imageView.post(new Runnable() {
        @Override
        public void run() {
            //This is called after view measurements are done.
            //Run your glide code here.
        }
    });

Hope this helps.