问:
how to set the position of images when changing from landscape to portrait mode in android
hi
i am adding some images dynamically through touch event. that is, where ever i touch and click add image, image is added to that position. when i change from portrait to landscape the position of the image should be adjusted accordingly.. for that i am setting the margins and adjusting the position of the image. but, this is possible only one side. Like, if i add images in portrait mode. i will apply scaling and adjust it when configuration changes to landscape. but, if i want to add images in landscape the position of the image is not added to the particular position where i touch. how do i resolve this. kindly help me out. Here is the piece of code i am sharing

public void AddButtons(int id)
    {

```<code>        int x = Integer.parseInt(StickyNotesList.get(id).getX());

        int y = Integer.parseInt(StickyNotesList.get(id).getY());

    float scale=pageViewManager.mDocument.getmPageSizeY()/pageViewManager.mDocument.getPageheight();

    RelativeLayout r=new RelativeLayout(stickynoteContext);
    /*AbsoluteLayout r = new AbsoluteLayout(stickynoteContext);
    AbsoluteLayout.LayoutParams params = new AbsoluteLayout.LayoutParams(pageViewManager.mDocument.mPageSizeX,pageViewManager.mDocument.mPageSizeY, (int) (x*scale), (int)(y*scale-(pageViewManager.getTitleViewHeight())));*/

    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(pageViewManager.mDocument.mPageSizeX,pageViewManager.mDocument.mPageSizeY);
    params.setMargins(x*scale, y*scale-pageViewManager.getTitleViewHeight(), 0, 0);
r.setLayoutParams(params);

    final Button btn = new Button(stickynoteContext);
    Drawable BG1 = (Drawable) getResources()
    .getDrawable(R.drawable.stickynote_icon);
    btn.setBackgroundDrawable(BG1);
    btn.setWidth((int)(stickynoteImag_Width*scale));
    btn.setHeight((int)(stickynoteImag_Height*scale));
    btn.setId(id+1);
    btn.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            updateStickyNotes(btn.getId());
        }
    });
    r.addView(btn);
    this.addView(r);
    StickyNoteLayout.add(r);
    r.invalidate();
    StickyNoteLayout.get(id).invalidate();
        }
</code>```

答: While changing the orientation, OS restarts the activity, so if you want to handle the orientation change you should check the orientation. There is a sample code here http://www.southparksystems.com/devzilla/2010/3/3/switching-layouts-when-screen-orientation-changes-in-android.html</p>

Body:
hi
i am adding some images dynamically through touch event. that is, where ever i touch and click add image, image is added to that position. when i change from portrait to landscape the position of the image should be adjusted accordingly.. for that i am setting the margins and adjusting the position of the image. but, this is possible only one side. Like, if i add images in portrait mode. i will apply scaling and adjust it when configuration changes to landscape. but, if i want to add images in landscape the position of the image is not added to the particular position where i touch. how do i resolve this. kindly help me out. Here is the piece of code i am sharing

public void AddButtons(int id)
    {

        int x = Integer.parseInt(StickyNotesList.get(id).getX());

        int y = Integer.parseInt(StickyNotesList.get(id).getY());

    float scale=pageViewManager.mDocument.getmPageSizeY()/pageViewManager.mDocument.getPageheight();

    RelativeLayout r=new RelativeLayout(stickynoteContext);
    /*AbsoluteLayout r = new AbsoluteLayout(stickynoteContext);
    AbsoluteLayout.LayoutParams params = new AbsoluteLayout.LayoutParams(pageViewManager.mDocument.mPageSizeX,pageViewManager.mDocument.mPageSizeY, (int) (x*scale), (int)(y*scale-(pageViewManager.getTitleViewHeight())));*/

    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(pageViewManager.mDocument.mPageSizeX,pageViewManager.mDocument.mPageSizeY);
    params.setMargins(x*scale, y*scale-pageViewManager.getTitleViewHeight(), 0, 0);
r.setLayoutParams(params);

    final Button btn = new Button(stickynoteContext);
    Drawable BG1 = (Drawable) getResources()
    .getDrawable(R.drawable.stickynote_icon);
    btn.setBackgroundDrawable(BG1);
    btn.setWidth((int)(stickynoteImag_Width*scale));
    btn.setHeight((int)(stickynoteImag_Height*scale));
    btn.setId(id+1);
    btn.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            updateStickyNotes(btn.getId());
        }
    });
    r.addView(btn);
    this.addView(r);
    StickyNoteLayout.add(r);
    r.invalidate();
    StickyNoteLayout.get(id).invalidate();
        }


来源: stackexchange

问:
Creating a Zoom Effect on an image on hover using CSS?
I'm currently trying to create a zoom effect on hover over one of my four images. The problem is most examples usually use tables or mask divs to apply some sort of effect.

Here's one example that implements what I would like this.

This is my code so far.

HTML

```<code><div id="menu">
<img class ="blog" src="http://s18.postimg.org/il7hbk7i1/image.png" alt="">
<img class ="music" src="http://s18.postimg.org/4st2fxgqh/image.png" alt="">
<img class ="projects" src="http://s18.postimg.org/sxtrxn115/image.png" alt="">
<img class ="bio" src="http://s18.postimg.org/5xn4lb37d/image.png" alt="">
</div>
</code>```

CSS

```<code>#menu {
    max-width: 1200px;
    text-align: center;
    margin: auto;
}

#menu img {
    width: 250px;
    height: 375px;
    padding: 0px 5px 0px 5px;
    overflow: hidden;
}

.blog {
    height: 375px;
    -webkit-transition: all 1s ease;
    -moz-transition: all 1s ease;
    -o-transition: all 1s ease;
    -ms-transition: all 1s ease;
    transition: all 1s ease;
}

.blog:hover {
    cursor: pointer;
    height:475px;
    width: 350px;
}

.music {
    height: 375px;
}

.projects {
    height: 375px;
}

.bio {
    height: 375px;
}
</code>```

答:
```<code><!DOCTYPE html>
<html>
<head>
<style>
.zoom {

  overflow: hidden;
}

.zoom img {
  transition: transform .5s ease;
}
.zoom:hover img {
  transform: scale(1.5);
}

</style>
</head>
<body>

<h1>Image Zoom On Hover</h1>
<div class="zoom">
  <img src="/image-path-url" alt="">
</div>

</body>
</html>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm currently trying to create a zoom effect on hover over one of my four images. The problem is most examples usually use tables or mask divs to apply some sort of effect.

Here's one example that implements what I would like this.

This is my code so far.

HTML

CSS

#menu {
    max-width: 1200px;
    text-align: center;
    margin: auto;
}

#menu img {
    width: 250px;
    height: 375px;
    padding: 0px 5px 0px 5px;
    overflow: hidden;
}

.blog {
    height: 375px;
    -webkit-transition: all 1s ease;
    -moz-transition: all 1s ease;
    -o-transition: all 1s ease;
    -ms-transition: all 1s ease;
    transition: all 1s ease;
}

.blog:hover {
    cursor: pointer;
    height:475px;
    width: 350px;
}

.music {
    height: 375px;
}

.projects {
    height: 375px;
}

.bio {
    height: 375px;
}

ContentLicense: CC BY-SA 4.0


问:
Simple method to modify json keys casing to camelCase from snake_case
I have lots of json parsing and all the json I am receiving is having keys in snake case like user_name. And for parsing I need it in camel case like userName.

The sample json file would look like this:

```<code>[{
   "user_id" : 1,
   "user_name" : "Abcd"
},
{
   "org_id" : 11,
   "org_name" : "some_name"
}
...
]
</code>```

Expected output:

```<code>[{
   "userId" : 1,
   "userName" : "Abcd"
},
{
   "orgId" : 11,
   "orgName" : "some_name"
}
...
]
</code>```

The json I am receiving is not having any particular fixed notation and it can be anything. But all the keys will be in snake case. And I need to convert it to camelCase.

What I cannot do is, find and replace, because it also replace snake casing strings in values as well.

Is there any easy method, which can do the same?

答:
If u use lodash I would suggest my solution for this:

snake_case -> camelCase

```<code>function camelCaseDeep(anything) {
  const thing = _.cloneDeep(anything);

  if (
    _.isEmpty(thing) ||
    (!_.isObject(thing) && !_.isArray(thing))
  ) {
    return thing;
  }

  if (_.isArray(thing)) {
    const arr = thing;
    return arr.map(el => camelCaseDeep(el))
  }

  // thing can be only not empty object here
  const objWithMappedKeys = _.mapKeys(thing, (value, key) => _.camelCase(key));
  const objWithMappedValues = _.mapValues(objWithMappedKeys, value => camelCaseDeep(value));

  return objWithMappedValues;
}
</code>```

camelCase -> snake_case

```<code>function snakeCaseDeep(anything) {
  const thing = _.cloneDeep(anything);

  if (
    _.isEmpty(thing) ||
    (!_.isObject(thing) && !_.isArray(thing))
  ) {
    return thing;
  }

  if (_.isArray(thing)) {
    const arr = thing;
    return arr.map(el => snakeCaseDeep(el))
  }

  // thing can be only not empty object here
  const objWithMappedKeys = _.mapKeys(thing, (value, key) => _.snakeCase(key));
  const objWithMappedValues = _.mapValues(objWithMappedKeys, value => snakeCaseDeep(value));

  return objWithMappedValues;
}
</code>```

Body:
I have lots of json parsing and all the json I am receiving is having keys in snake case like user_name. And for parsing I need it in camel case like userName.

The sample json file would look like this:

[{
   "user_id" : 1,
   "user_name" : "Abcd"
},
{
   "org_id" : 11,
   "org_name" : "some_name"
}
...
]

Expected output:

[{
   "userId" : 1,
   "userName" : "Abcd"
},
{
   "orgId" : 11,
   "orgName" : "some_name"
}
...
]

The json I am receiving is not having any particular fixed notation and it can be anything. But all the keys will be in snake case. And I need to convert it to camelCase.

What I cannot do is, find and replace, because it also replace snake casing strings in values as well.

Is there any easy method, which can do the same?

Body:
If u use lodash I would suggest my solution for this:

snake_case -> camelCase

function camelCaseDeep(anything) {
  const thing = _.cloneDeep(anything);

  if (
    _.isEmpty(thing) ||
    (!_.isObject(thing) && !_.isArray(thing))
  ) {
    return thing;
  }

  if (_.isArray(thing)) {
    const arr = thing;
    return arr.map(el => camelCaseDeep(el))
  }

  // thing can be only not empty object here
  const objWithMappedKeys = _.mapKeys(thing, (value, key) => _.camelCase(key));
  const objWithMappedValues = _.mapValues(objWithMappedKeys, value => camelCaseDeep(value));

  return objWithMappedValues;
}

camelCase -> snake_case

function snakeCaseDeep(anything) {
  const thing = _.cloneDeep(anything);

  if (
    _.isEmpty(thing) ||
    (!_.isObject(thing) && !_.isArray(thing))
  ) {
    return thing;
  }

  if (_.isArray(thing)) {
    const arr = thing;
    return arr.map(el => snakeCaseDeep(el))
  }

  // thing can be only not empty object here
  const objWithMappedKeys = _.mapKeys(thing, (value, key) => _.snakeCase(key));
  const objWithMappedValues = _.mapValues(objWithMappedKeys, value => snakeCaseDeep(value));

  return objWithMappedValues;
}


问:
How can i declare an array of custom objects in XAML and support binding
I have been working on a CustomControl which contains an ItemsControl. I have added a dependency property so i can set the ItemsSource property of the ItemsControl in the XAML where the control is used. I have declared my array of custom objects directly in the XAML. This works quite nicely however i have hit a problem with binding any of the public properties on the custom objects in the XAML. The custom objects are not dependency objects...

I would appreciate some pointers.

If this is too convoluted to achieve in XAML i will just bind the ItemsSource to a property on my view model...

XAML:

```<code><local:OptionsControl Title="Options" Message="Select an option:">
    <local:OptionsControl.Options>
        <x:Array Type="{x:Type local:OptionInfo}">
           <local:OptionInfo Name="OptionOne" SelectCommand="{Binding ?"}/>
           <local:OptionInfo Name="OptionTwo" SelectCommand="{Binding ?"}/>
           <local:OptionInfo Name="OptionThree" SelectCommand="{Binding ?"}/>
        </x:Array>
    </local:OptionsControl.Options>
</local:OptionsControl>
</code>```

答:
You don't explain fully what you are doing.

You can define an x:array with a type and bind the itemssource to that.  You can bind to pubic properties of that type, no problem.

You can even define a class inherits observablecollection, define the items of that in xaml and bind an itemssource to that.

https://social.technet.microsoft.com/wiki/contents/articles/26200.wpf-dynamicresource-observablecollection.aspx

Body:
I have been working on a CustomControl which contains an ItemsControl. I have added a dependency property so i can set the ItemsSource property of the ItemsControl in the XAML where the control is used. I have declared my array of custom objects directly in the XAML. This works quite nicely however i have hit a problem with binding any of the public properties on the custom objects in the XAML. The custom objects are not dependency objects...

I would appreciate some pointers.

If this is too convoluted to achieve in XAML i will just bind the ItemsSource to a property on my view model...

XAML:

<local:OptionsControl Title="Options" Message="Select an option:">
    <local:OptionsControl.Options>
        <x:Array Type="{x:Type local:OptionInfo}">
           <local:OptionInfo Name="OptionOne" SelectCommand="{Binding ?"}/>
           <local:OptionInfo Name="OptionTwo" SelectCommand="{Binding ?"}/>
           <local:OptionInfo Name="OptionThree" SelectCommand="{Binding ?"}/>
        </x:Array>
    </local:OptionsControl.Options>
</local:OptionsControl>


问:
How to explain the reverse of a sequence by slice notation a[::-1]
From the python.org tutorial

Slice indices have useful defaults; an omitted first index defaults to zero, an omitted second index defaults to the size of the string being sliced.

```<code>>>> a = "hello"
>>> print(a[::-1])
olleh
</code>```

As the tutorial says a[::-1] should equals to a[0:5:-1]

but a[0:5:-1] is empty as follows:

```<code>>>> print(len(a[0:5:-1]))
0
</code>```

The question is not a duplicate of explain-slice-notation. That question is about the general use of slicing in python.

答:
For Python slicing for a sequence[start:stop:step], have derived these rules:

start:stop  = start:stop:1

start:stop:(+ or -) step - It means when traversing skip N items in the sequence. However, (-) indicates backward traversal

Remember, position of last item in sequence is -1, and the one before than is -2, and so on..

# start:stop: +step Rules

Always traverse in forward

Always start from beginning of sequence as its a positive step ( forward )

Start at requested position, stop at requested position but exclude the item stop position

Default start: If start is not provided, start at 0

Default stop: if stop is not provided, it means until the end of the sequence including the last value

If item at stop position is not reachable (item is beyond the end of sequence traversal), slice does not return anything

# start:stop:-step Rules

Always traverse in reverse

If start position is provided, start from there, but traverse in reverse ( its a step back )

If stop is provided, stop traversing there but exclude this

Default start: If start position is not provided, start position is the last position of the sequence ( since negative traversal)

Default stop: If stop is not provided, it is the beginning of the list ( position 0)

If item at stop position is not reachable (item is beyond the end of sequence traversal), slice does not return anything

Body:
From the python.org tutorial

Slice indices have useful defaults; an omitted first index defaults to zero, an omitted second index defaults to the size of the string being sliced.

>>> a = "hello"
>>> print(a[::-1])
olleh

As the tutorial says a[::-1] should equals to a[0:5:-1]

but a[0:5:-1] is empty as follows:

>>> print(len(a[0:5:-1]))
0

The question is not a duplicate of explain-slice-notation. That question is about the general use of slicing in python.


问:
warning: passing argument 2 of ‘inet_aton’ from incompatible pointer type........ERROR
I don't know what this error means and what to do to fix it.

I've been following the Sock)et Programming Tutorials In C For Beginners | Part 2 by Eduonix on Youtube but I haven't been able to run anything from this guy, the code is from his tutorial.

If someone could help me understand what this error means and what to do to fix it?

Here is the error:

```<code>inet_aton(address, &remote_address.sin_addr.s_addr);
                   ^
</code>```

```<code>[1007:1003 0:6758] 09:30:39 Wed May 29 [kristjan@Kundrum:pts/5 +1] ~/C_Programming
$ gcc http_client_tcp.c -o http_client_tcp
http_client_tcp.c: In function ‘main’:
http_client_tcp.c:24:24: warning: passing argument 2 of ‘inet_aton’ from incompatible pointer type [-Wincompatible-pointer-types]
     inet_aton(address, &remote_address.sin_addr.s_addr);
                        ^
In file included from http_client_tcp.c:8:0:
/usr/include/arpa/inet.h:73:12: note: expected ‘struct in_addr *’ but argument is of type ‘in_addr_t * {aka unsigned int *}’
 extern int inet_aton (const char *__cp, struct in_addr *__inp) __THROW;
            ^~~~~~~~~
</code>```

I'm using Debian Linux 9.9 stretch and coding in Visual Studio Code but the error doesn't come in the Visual Code editor/debugger only if I compile in the shell.

Here is the code:

```<code>#include <stdio.h>
#include <stdlib.h>

#include <sys/socket.h>
#include <sys/types.h>

#include <netinet/in.h>
#include <arpa/inet.h>

#include <unistd.h> // for close

int main(int argc, char *argv[])
{
    char *address;
    address = argv[1];

    int client_socket;
    client_socket = socket(AF_INET, SOCK_STREAM, 0);

    // connect to an address
    struct sockaddr_in remote_address;
    remote_address.sin_family = AF_INET;
    remote_address.sin_port = htons(80);
    inet_aton(address, &remote_address.sin_addr.s_addr);

    connect(client_socket, (struct sockaddr *) &remote_address, sizeof(remote_address));

    char request[] = "GET / HTTP/1.1\r\n\r\n";
    char response[4096];

    send(client_socket, request, sizeof(request), 0);
    recv(client_socket, &response, sizeof(response), 0);

    printf("response from server: %s\n", response);
    close(client_socket);

    return 0;
}
</code>```

答:
Check the types. From the man page

int inet_aton(const char *cp, struct in_addr *inp);

the second argument is a pointer to struct in_addr type variable.

In your code, you defined  remote_address as

```<code> struct sockaddr_in remote_address;
</code>```

where struct sockaddr_in is defined as

```<code>struct sockaddr_in {
    short            sin_family;   // e.g. AF_INET
    unsigned short   sin_port;     // e.g. htons(3490)
    struct in_addr   sin_addr;     // ***** this is the target
    char             sin_zero[8];  // zero this if you want to
};
</code>```

So, your usage

```<code> inet_aton(address, &remote_address.sin_addr.s_addr);
</code>```

should be

```<code>inet_aton(address, &(remote_address.sin_addr)); // explicit parenthesis to clarify type
</code>```

Body:
I don't know what this error means and what to do to fix it.

I've been following the Sock)et Programming Tutorials In C For Beginners | Part 2 by Eduonix on Youtube but I haven't been able to run anything from this guy, the code is from his tutorial.

If someone could help me understand what this error means and what to do to fix it?

Here is the error:

inet_aton(address, &remote_address.sin_addr.s_addr);
                   ^

[1007:1003 0:6758] 09:30:39 Wed May 29 [kristjan@Kundrum:pts/5 +1] ~/C_Programming
$ gcc http_client_tcp.c -o http_client_tcp
http_client_tcp.c: In function ‘main’:
http_client_tcp.c:24:24: warning: passing argument 2 of ‘inet_aton’ from incompatible pointer type [-Wincompatible-pointer-types]
     inet_aton(address, &remote_address.sin_addr.s_addr);
                        ^
In file included from http_client_tcp.c:8:0:
/usr/include/arpa/inet.h:73:12: note: expected ‘struct in_addr *’ but argument is of type ‘in_addr_t * {aka unsigned int *}’
 extern int inet_aton (const char *__cp, struct in_addr *__inp) __THROW;
            ^~~~~~~~~

I'm using Debian Linux 9.9 stretch and coding in Visual Studio Code but the error doesn't come in the Visual Code editor/debugger only if I compile in the shell.

Here is the code:

#include <stdio.h>
#include <stdlib.h>

#include <sys/socket.h>
#include <sys/types.h>

#include <netinet/in.h>
#include <arpa/inet.h>

#include <unistd.h> // for close

int main(int argc, char *argv[])
{
    char *address;
    address = argv[1];

    int client_socket;
    client_socket = socket(AF_INET, SOCK_STREAM, 0);

    // connect to an address
    struct sockaddr_in remote_address;
    remote_address.sin_family = AF_INET;
    remote_address.sin_port = htons(80);
    inet_aton(address, &remote_address.sin_addr.s_addr);

    connect(client_socket, (struct sockaddr *) &remote_address, sizeof(remote_address));

    char request[] = "GET / HTTP/1.1\r\n\r\n";
    char response[4096];

    send(client_socket, request, sizeof(request), 0);
    recv(client_socket, &response, sizeof(response), 0);

    printf("response from server: %s\n", response);
    close(client_socket);

    return 0;
}

Body:
Check the types. From the man page

int inet_aton(const char *cp, struct in_addr *inp);

the second argument is a pointer to struct in_addr type variable.

In your code, you defined  remote_address as

 struct sockaddr_in remote_address;

where struct sockaddr_in is defined as

struct sockaddr_in {
    short            sin_family;   // e.g. AF_INET
    unsigned short   sin_port;     // e.g. htons(3490)
    struct in_addr   sin_addr;     // ***** this is the target
    char             sin_zero[8];  // zero this if you want to
};

So, your usage

 inet_aton(address, &remote_address.sin_addr.s_addr);

should be

inet_aton(address, &(remote_address.sin_addr)); // explicit parenthesis to clarify type


答:
The tutorial is bad, the correct code is

```<code>inet_aton(address, &remote_address.sin_addr);
</code>```

remote_address.sin_addr is of type in_addr, whose definition is

```<code>struct in_addr {
    unsigned long s_addr;
};
</code>```

The &remote_address.sin_addr.s_addr and &remote_address.sin_addr will evaluate to the same address, but the former is of wrong type. The original will compile with warning in GCC with default settings, but it is a constraint violation!

As for the Visual Studio code, you should look harder, or perhaps compile with -Werror!

Time to look for better tutorials.

Title: warning: passing argument 2 of ‘inet_aton’ from incompatible pointer type........ERROR

Body:
The tutorial is bad, the correct code is

inet_aton(address, &remote_address.sin_addr);

remote_address.sin_addr is of type in_addr, whose definition is

struct in_addr {
    unsigned long s_addr;
};

The &remote_address.sin_addr.s_addr and &remote_address.sin_addr will evaluate to the same address, but the former is of wrong type. The original will compile with warning in GCC with default settings, but it is a constraint violation!

As for the Visual Studio code, you should look harder, or perhaps compile with -Werror!

Time to look for better tutorials.


问:
Modifying pre-receive hooks on Bitbucket Cloud
We have Bitbucket Cloud not Bitbucket Server. Is there a way to modify the "pre-receive" functions on Bitbucket? Goal is to audit pushes to make sure there's no obvious vulnerabilities before the code is available on Bitbucket. Git-hooks might work but there's not really a way to get them into version control in the same repo - the only way I can think of doing that would be to ssh into a Bitbucket server and modify the remote repo but I don't think you can do that?

My only guess is there might be a way to keep the pre-receive hooks in source control by putting the hook somewhere like this in the repo:

```<code>.bitbucket/pre-receive
</code>```

But it's hard to find any info on this online.

答:
Unfortunately, this isn't possible.

The GitHub documentation is talking about GitHub Enterprise Server, a product you would install on your own infrastructure. GitHub as in github.com does not support creating pre-receive hooks at all. This is pretty much the norm amongst the popular cloud git hosting providers - no cloud provider will let you write your own arbitrary code and run it on the same infrastructure that holds your git repo, there's too much danger of you breaking out into other data on the same physical storage.

Until someone develops a safe/sandboxed implementation of server-side hooks, you'll need to find another way.

Full disclosure: I work for Atlassian (though I don't work on Bitbucket Cloud)

Body:
We have Bitbucket Cloud not Bitbucket Server. Is there a way to modify the "pre-receive" functions on Bitbucket? Goal is to audit pushes to make sure there's no obvious vulnerabilities before the code is available on Bitbucket. Git-hooks might work but there's not really a way to get them into version control in the same repo - the only way I can think of doing that would be to ssh into a Bitbucket server and modify the remote repo but I don't think you can do that?

My only guess is there might be a way to keep the pre-receive hooks in source control by putting the hook somewhere like this in the repo:

.bitbucket/pre-receive

But it's hard to find any info on this online.


问:
Wrong image path when running in a subdirectory of my Rails app
I have a rails app running in a subdirectory, like www.domain.com/sub.
The problem is that if I set a image path in my css, like

```<code>/images/my_image.png
</code>```

it breaks when I upload it to my server. I need to set

```<code>/sub/images/my_image.png
</code>```

then it breaks in my development environment.
The same problem occurs in my .js files.

I read something about the rails_relative_url_root environment variable, but couldn't get it to work.

Could anyone help me?

答:
You could use URLs relative to the stylesheet. In your CSS, instead of this:

```<code>/images/my_image.png
</code>```

Do:

```<code>../images/my_image.png
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have a rails app running in a subdirectory, like www.domain.com/sub.
The problem is that if I set a image path in my css, like

/images/my_image.png

it breaks when I upload it to my server. I need to set

/sub/images/my_image.png

then it breaks in my development environment.
The same problem occurs in my .js files.

I read something about the rails_relative_url_root environment variable, but couldn't get it to work.

Could anyone help me?

Body:
You could use URLs relative to the stylesheet. In your CSS, instead of this:

/images/my_image.png

Do:

../images/my_image.png


问:
Render state in another component in reactjs
I'm trying to display current user name in a different component but It's not working, what am I doing wrong ?

Here's where I'm initialising the username (App.js)

class App extends Component{
  constructor(props) {
    super(props);
    this.state = {
      logged_in: localStorage.getItem('token') ? true : false,
      username: ''
    };
  }
  componentDidMount() {
    if (this.state.logged_in) {
      fetch('http://localhost:8000/user/current_user/', {
        headers: {
          Authorization: `JWT ${localStorage.getItem('token')}`
        }
      })
        .then(res => res.json())
        .then(json => {
          this.setState({ username: json.username });
          console.log(json.username);
        });

    }
  }
  render() {
  return (

      <Router history={history}>
        <Switch>
          <Route exact path="/" component={First} />
          <Route path="/home" component={Projects} />
          <Route path="/menu" component={MenuH} />
          <Route path ="/createProject" component={CreateP} />
          <Route path ="/connect" component={Newacount} />
          <Route component={Notfound} />
        </Switch>
      </Router>

  );
  }
}
...
```

<p>And here's how I'm calling it in a different component (projects)</p>

<pre class="lang-js prettyprint-override"><code>{this.state.username}
</code>```

答:
Here's a good discussion about How to pass component via react router.

When following the discussion, you code will look like:

```<code><div className="App">
      <Router history={history}>
        <Switch>
          <!-- Pass username as props here -->
          <Route path="/your-route" render={()=><Projects username={this.state.username}/>} />
        </Switch>
      </Router>
</div>
</code>```

And into your Projects component, you retrieve it with this.props.username.

Body:
I'm trying to display current user name in a different component but It's not working, what am I doing wrong ?

Here's where I'm initialising the username (App.js)

class App extends Component{
  constructor(props) {
    super(props);
    this.state = {
      logged_in: localStorage.getItem('token') ? true : false,
      username: ''
    };
  }
  componentDidMount() {
    if (this.state.logged_in) {
      fetch('http://localhost:8000/user/current_user/', {
        headers: {
          Authorization: `JWT ${localStorage.getItem('token')}`
        }
      })
        .then(res => res.json())
        .then(json => {
          this.setState({ username: json.username });
          console.log(json.username);
        });

    }
  }
  render() {
  return (

      <Router history={history}>
        <Switch>
          <Route exact path="/" component={First} />
          <Route path="/home" component={Projects} />
          <Route path="/menu" component={MenuH} />
          <Route path ="/createProject" component={CreateP} />
          <Route path ="/connect" component={Newacount} />
          <Route component={Notfound} />
        </Switch>
      </Router>

  );
  }
}
...

And here's how I'm calling it in a different component (projects)

{this.state.username}

Body:
Here's a good discussion about How to pass component via react router.

When following the discussion, you code will look like:

<div className="App">
      <Router history={history}>
        <Switch>
          <!-- Pass username as props here -->
          <Route path="/your-route" render={()=><Projects username={this.state.username}/>} />
        </Switch>
      </Router>
</div>

And into your Projects component, you retrieve it with this.props.username.


问:
Error ExecuteNonQuery: Connection property has not been initialized
I am having a problem with the following code:

```<code>namespace Elite_Shop
{
        public partial class Bill : Form
        {
            int j;
            int total = 0;
            SqlConnection sqlcon = new SqlConnection(@"Data Source=HP\SQLEXPRESS;Initial Catalog=EliteShop;Integrated Security=True  ");

        public Bill()
        {
            InitializeComponent();
        }
        public void get_value(int i)
        {
            j = i;
        }
        private void Bill_Load(object sender, EventArgs e)
        {
            if (sqlcon.State == ConnectionState.Open)
            {
                sqlcon.Close();
            }
            sqlcon.Open();
            DataSet1 ds = new DataSet1();
            SqlCommand cmd = new SqlCommand();
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "Select * from Salesman_Table Where SMID="+j+"";
            cmd.ExecuteNonQuery();
            DataTable dt = new DataTable();
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            da.Fill(ds.DataTable1);

            SqlCommand cmd2 = new SqlCommand();
            cmd2.CommandType = CommandType.Text;
            cmd2.CommandText = "Select * from Sale_Table Where OrderID=" + j + "";
            cmd2.ExecuteNonQuery();
            DataTable dt2 = new DataTable();
            SqlDataAdapter da2 = new SqlDataAdapter(cmd2);
            da2.Fill(ds.DataTable2);
            da2.Fill(dt2);

            foreach (DataRow dr2 in dt2.Rows)
            {

                total = total + Convert.ToInt32(dr2["Sub Total"].ToString());
            }
            SaleReport sr = new SaleReport();
            sr.SetDataSource(ds);
            sr.SetParameterValue("Grand Total", total.ToString());
            crystalReportViewer1.ReportSource = sr;
        }
    }
}
</code>```

When executed, the following error message is returned:

ExecuteNonQuery: Connection property has not been initialized.

How do I fix it?

答:
You need to set the Connection property on the SqlCommand:</p>

```<code>cmd.Connection = sqlcon;
</code>```

Body:
I am having a problem with the following code:

namespace Elite_Shop
{
        public partial class Bill : Form
        {
            int j;
            int total = 0;
            SqlConnection sqlcon = new SqlConnection(@"Data Source=HP\SQLEXPRESS;Initial Catalog=EliteShop;Integrated Security=True  ");

        public Bill()
        {
            InitializeComponent();
        }
        public void get_value(int i)
        {
            j = i;
        }
        private void Bill_Load(object sender, EventArgs e)
        {
            if (sqlcon.State == ConnectionState.Open)
            {
                sqlcon.Close();
            }
            sqlcon.Open();
            DataSet1 ds = new DataSet1();
            SqlCommand cmd = new SqlCommand();
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "Select * from Salesman_Table Where SMID="+j+"";
            cmd.ExecuteNonQuery();
            DataTable dt = new DataTable();
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            da.Fill(ds.DataTable1);

            SqlCommand cmd2 = new SqlCommand();
            cmd2.CommandType = CommandType.Text;
            cmd2.CommandText = "Select * from Sale_Table Where OrderID=" + j + "";
            cmd2.ExecuteNonQuery();
            DataTable dt2 = new DataTable();
            SqlDataAdapter da2 = new SqlDataAdapter(cmd2);
            da2.Fill(ds.DataTable2);
            da2.Fill(dt2);

            foreach (DataRow dr2 in dt2.Rows)
            {

                total = total + Convert.ToInt32(dr2["Sub Total"].ToString());
            }
            SaleReport sr = new SaleReport();
            sr.SetDataSource(ds);
            sr.SetParameterValue("Grand Total", total.ToString());
            crystalReportViewer1.ReportSource = sr;
        }
    }
}

When executed, the following error message is returned:

ExecuteNonQuery: Connection property has not been initialized.

How do I fix it?

Body:
You need to set the Connection property on the SqlCommand:

cmd.Connection = sqlcon;


问:
Nifi: Merging all of necessary flowfile in one shot with MergeContent Processor
This is the question about MergeContent processor in Nifi.
Currently, I need to combine all flowfiles with one particular attribute in one shot manner.

But what happens is since there are so many flowFile with the same attribute,
the processor produces a few different flowfiles merged with the attribute, and those few should be combined into one big flowfile together.

Are they any ways to wait for all flowfile with same attribute to come into the MergeContent Processor and merge all of them at one time?

If not, what could be an alternative?

答:
You can increase the "Minimum Number of Entries" and "Maximum Number of Entries" to suit your use case and increase the "Max Bin Age" to a suitable time.

You can refer all the properties for merge-content here : https://nifi.apache.org/docs/nifi-docs/components/org.apache.nifi/nifi-standard-nar/1.6.0/org.apache.nifi.processors.standard.MergeContent/index.html

Also, are you using nifi in a cluster or stand alone? Because the flowfiles in one node cannot be merged with the flowfiles in the other node.

For instance, if you're using a nifi cluster with 5 nodes, each having 10 flowfiles. After using the merge content processor, you will have 5 files.

Let me know if you need further assistance!


问:
Hot reloading of Play Framework (2.4), sbt (0.13.17) and reason for complete project being entirely recompiled
Something seems currently wrong with my web application project and its internal dependencies: if I modify the body of a public, non-static Java method for certain classes, my whole project gets recompiled. This is a huge waste of my time, how can I go about debugging this and fix it ?

If possible I would like sbt to tell me the incremental compile dependency tree (ie: modifying "myMethod" triggers recompile classes A1 and B1, recompiling A triggers recompile A2, recompiling B1 triggers recompile B2, and so on. This would probably give me some clue. Does this even exist ?

答:
There is nothing wrong with Play framework when changing/modifying the code leads to re-compilation. This is basically a feature of Play framework called "Hot Reloading".

Now coming to the second part of your question, you need to understand how play hot reloading works

Let's say your play server is running and you make a code change. Then following steps are followed

It compiles your class file and checks for any compilation issue.

Then compiles remaining code to check if the new code change is breaking any other part of the code.

If there is any compilation issue, it will throw an exception.

Assuming the compilation succeeded, we need to update the loaded classes in the JVM. For that we just remove the old application classloader, and create a new one with the updated classes.

Play application is restarted.

To summarize, play framework discards the old classloader and creates a new one with the updated classes and hence complete project is recompiled again.

Hope that answers your question !!!


问:
How do I make a Sidebar display values from cells?
I have a Google Sheet that I'm using as a database of clients. There are quite a lot of variables (columns) that I need to store per entry, so I thought that it would be easier to view each entry if I could have a Sidebar display all of the values of the active row.

Example: If I click cell C1, it will display the values from C1, C2, C3 and C4 in the sidebar.

Is this possible? I've gotten as far as getting the Sidebar to display but I cannot figure out how to get a value from a cell and print it to the Sidebar.

Thank you in advance, I've reached a dead end with my (very) limited intellect!

答:
Or, five years later, something like this?

This is more perhaps a development of Mogsdad's answer but still responds to the OP.

Data in the TBA is positioned by associations rather than coordinates – Trail, Branch and Aspect lists are read separately and strung together – Floor 1 > Guestroom 3 > Test 1: Dirty. (see TBA overview)

<<< Displays the data for one aspect in the spreadsheet; >>> TBA reruns for new selections in sheet.

I would like to share the code. May I ask what is the best way to do that? (It is very early days)


问:
App crashes when attempting to swap activities
This is a basic activity swapping.

The app does not crash if i declare a local button inside the configureActivitySwap() method like this:

```<code>Button voiceBtn = (findViewById(R.id.goToVoice));
</code>```

But I have to declare the button in the global scope instead so I can use the button in other methods, mainly activating and deactivating the button when it should/should not be pressed.

I also noticed that if I remove the finish(); method and replace it with something else the app functions normally, but I have to have the finish(); method one way or another.

```<code>public class RecogActivity extends AppCompatActivity {

    private Button voiceBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        voiceBtn = findViewById(R.id.goToVoice);
        setContentView(R.layout.main_layout);

        // some unrelated code

        configureActivitySwap();
    }

    public void configureActivitySwap(){
        // Button voiceBtn = (findViewById(R.id.goToVoice));

        voiceBtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }

}
</code>```

My runtime error logs:

```<code>    E/AndroidRuntime: FATAL EXCEPTION: main
        Process: tk.gandriks.gaaudiotransform, PID: 23125
        java.lang.RuntimeException: Unable to start activity ComponentInfo{tk.gandriks.gaaudiotransform/tk.gandriks.gaaudiotransform.RecogActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2957)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3032)
            at android.app.ActivityThread.-wrap11(Unknown Source:0)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1696)
            at android.os.Handler.dispatchMessage(Handler.java:105)
            at android.os.Looper.loop(Looper.java:164)
            at android.app.ActivityThread.main(ActivityThread.java:6944)
            at java.lang.reflect.Method.invoke(Native Method)
            at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)
         Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
            at tk.gandriks.gaaudiotransform.RecogActivity.configureActivitySwap(RecogActivity.java:140)
            at tk.gandriks.gaaudiotransform.RecogActivity.onCreate(RecogActivity.java:124)
            at android.app.Activity.performCreate(Activity.java:7183)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1220)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2910)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3032)
            at android.app.ActivityThread.-wrap11(Unknown Source:0)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1696)
            at android.os.Handler.dispatchMessage(Handler.java:105)
            at android.os.Looper.loop(Looper.java:164)
            at android.app.ActivityThread.main(ActivityThread.java:6944)
            at java.lang.reflect.Method.invoke(Native Method)
            at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)
</code>```

答:
You need to call the setContentView() before calling voiceBtn = findViewById(R.id.goToVoice); Since you don't specify the layout the findViewById method will not get the button instance</p>

```<code>public class RecogActivity extends AppCompatActivity {

   private Button voiceBtn;

   @Override
   protected void onCreate(Bundle savedInstanceState) {

      super.onCreate(savedInstanceState);
      // set the layout first
      setContentView(R.layout.YOUR_LAYOUT_XML_FILE_NAME)

      voiceBtn = findViewById(R.id.goToVoice);

      // some unrelated code

      configureActivitySwap();
 }

 public void configureActivitySwap(){
    // Button voiceBtn = (findViewById(R.id.goToVoice));

    voiceBtn.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View view) {
        finish();
    }
  });
}
</code>```

Body:
This is a basic activity swapping.

The app does not crash if i declare a local button inside the configureActivitySwap() method like this:

Button voiceBtn = (findViewById(R.id.goToVoice));

But I have to declare the button in the global scope instead so I can use the button in other methods, mainly activating and deactivating the button when it should/should not be pressed.

I also noticed that if I remove the finish(); method and replace it with something else the app functions normally, but I have to have the finish(); method one way or another.

public class RecogActivity extends AppCompatActivity {

    private Button voiceBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        voiceBtn = findViewById(R.id.goToVoice);
        setContentView(R.layout.main_layout);

        // some unrelated code

        configureActivitySwap();
    }

    public void configureActivitySwap(){
        // Button voiceBtn = (findViewById(R.id.goToVoice));

        voiceBtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }

}

My runtime error logs:

    E/AndroidRuntime: FATAL EXCEPTION: main
        Process: tk.gandriks.gaaudiotransform, PID: 23125
        java.lang.RuntimeException: Unable to start activity ComponentInfo{tk.gandriks.gaaudiotransform/tk.gandriks.gaaudiotransform.RecogActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2957)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3032)
            at android.app.ActivityThread.-wrap11(Unknown Source:0)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1696)
            at android.os.Handler.dispatchMessage(Handler.java:105)
            at android.os.Looper.loop(Looper.java:164)
            at android.app.ActivityThread.main(ActivityThread.java:6944)
            at java.lang.reflect.Method.invoke(Native Method)
            at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)
         Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
            at tk.gandriks.gaaudiotransform.RecogActivity.configureActivitySwap(RecogActivity.java:140)
            at tk.gandriks.gaaudiotransform.RecogActivity.onCreate(RecogActivity.java:124)
            at android.app.Activity.performCreate(Activity.java:7183)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1220)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2910)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3032)
            at android.app.ActivityThread.-wrap11(Unknown Source:0)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1696)
            at android.os.Handler.dispatchMessage(Handler.java:105)
            at android.os.Looper.loop(Looper.java:164)
            at android.app.ActivityThread.main(ActivityThread.java:6944)
            at java.lang.reflect.Method.invoke(Native Method)
            at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)

Body:
You need to call the setContentView() before calling voiceBtn = findViewById(R.id.goToVoice); Since you don't specify the layout the findViewById method will not get the button instance

public class RecogActivity extends AppCompatActivity {

   private Button voiceBtn;

   @Override
   protected void onCreate(Bundle savedInstanceState) {

      super.onCreate(savedInstanceState);
      // set the layout first
      setContentView(R.layout.YOUR_LAYOUT_XML_FILE_NAME)

      voiceBtn = findViewById(R.id.goToVoice);

      // some unrelated code

      configureActivitySwap();
 }

 public void configureActivitySwap(){
    // Button voiceBtn = (findViewById(R.id.goToVoice));

    voiceBtn.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View view) {
        finish();
    }
  });
}


问:
How to get Rails and all requirements running to use React?
Iam a novice in rails and trying to write my first React frontend. I have read enough to know that there are different methods to use React with rails. I decided to split frontend and backend, and use rails in API mode. I cannot find good sources explaining what I need on my server to get rails and react going, and why. I read so far about npm, node.js, Heroku and so on, but i lack the knowledge to decide what to pick and i dont understand the interactions yet.
Does someone know a good tutorial, some sources or keywords to point me to a direction?</p>

答:
For using react as your client-side application and rails for the server-side you need two different applications. As Rails is MVC I suggest you use just ruby and Sinatra server.
In this situation be careful about the cross-origin errors you have to enable it while using two agents.
Take a look at this.


问:
Bs4 Selectors: Scrape Amazon using Beautiful Soup
I am trying to scrape a site which has links to Amazon with Python using these frameworks - selenium, beautiful soup.

My aim is to scrape the Following Amazon products details -->
 Title, Price, Description, First Review

But I am having a hard time with Beautiful selectors I tried many combinations but I either get a null output or Error, Unfortunately Not so Pro.
The main problem is that Beautiful soup doesn't have XPath selectors (AFAIK).
Should I move to scrapy for this task, or is scrapy is too overwhelming for this simple scraper?

This is for the first product I will iterate this later

```<code>from bs4 import BeautifulSoup
from selenium import webdriver
import time

driver.get('https://www.example.com')
driver.get('https://www.example.com')
first_article = driver.find_element_by_css_selector('div.button')
first_article.click()
html = driver.page_source
soup = BeautifulSoup(html, 'lxml')
# perform the operation
</code>```

After that I have to select the respective path but how to do them?
In Xpath is something like this,

```<code>Title = '//h1[@id="title"]//text()'

Price = '//span[contains(@id,"ourprice") or contains(@id,"saleprice")]/text()'

Category = //a[@class="a-link-normal a-color-tertiary"]//text()'
</code>```

But product details and the path to the first review only I can't yet. Beautiful Soup find_all selectors won't be helpful here I think.

答:
Amazon has anti-scraping mechanisms in place that if it detects scraping it will use a captcha on the scraper so your issue is that it’s returning the html for the captcha and you are not finding anything. </p>

<p>The only way reliable way to scrape amazon will be to use a headless version of Selenium. </p>

Body:
I am trying to scrape a site which has links to Amazon with Python using these frameworks - selenium, beautiful soup.

My aim is to scrape the Following Amazon products details -->
 Title, Price, Description, First Review

But I am having a hard time with Beautiful selectors I tried many combinations but I either get a null output or Error, Unfortunately Not so Pro.
The main problem is that Beautiful soup doesn't have XPath selectors (AFAIK).
Should I move to scrapy for this task, or is scrapy is too overwhelming for this simple scraper?

This is for the first product I will iterate this later

from bs4 import BeautifulSoup
from selenium import webdriver
import time

driver.get('https://www.example.com')
driver.get('https://www.example.com')
first_article = driver.find_element_by_css_selector('div.button')
first_article.click()
html = driver.page_source
soup = BeautifulSoup(html, 'lxml')
# perform the operation

After that I have to select the respective path but how to do them?
In Xpath is something like this,

Title = '//h1[@id="title"]//text()'

Price = '//span[contains(@id,"ourprice") or contains(@id,"saleprice")]/text()'

Category = //a[@class="a-link-normal a-color-tertiary"]//text()'

But product details and the path to the first review only I can't yet. Beautiful Soup find_all selectors won't be helpful here I think.

Body:
Amazon has anti-scraping mechanisms in place that if it detects scraping it will use a captcha on the scraper so your issue is that it’s returning the html for the captcha and you are not finding anything.

The only way reliable way to scrape amazon will be to use a headless version of Selenium.


问:
Ordering a list of dataframes by minimum column value in R
As a preliminary to creating a multivariate logistic regression I'm doing univariate regressions and want to select the variables with p < 0.20 to include in the multivariate model. I can map the required variables to glm and get the output of the models, but am struggling to order them by rank of p-value.

This is what I have so far:

```<code>predictor1 <- c(0,1.1,2.4,3.1,4.0,5.9,4.2,3.3,2.2,1.1)
predictor2 <- as.factor(c("yes","no","no","yes","yes","no","no","yes","no","no"))
predictor3 <- as.factor(c("a", "b", "c", "c", "a", "c", "a", "a", "a", "c"))
outcome <- as.factor(c("alive","dead","alive","dead","alive","dead","alive","dead","alive","dead"))
df <- data.frame(pred1 = predictor1, pred2 = predictor2, pred3 = predictor3, outcome = outcome)
predictors <- c("pred1", "pred2", "pred3")
df %>%
    select(predictors) %>%
    map(~ glm(df$outcome ~ .x, data = df, family = "binomial"))  %>%
    #Extract odds ratio, confidence interval lower and upper bounds, and p value
    map(function (x, y) data.frame(OR = exp(coef(x)),
        lower=exp(confint(x)[,1]),
        upper=exp(confint(x)[,2]),
        Pval = coef(summary(x))[,4]))
</code>```

This code spits out a summary of each model

```<code>$pred1
                OR   lower          upper           Pval
    (Intercept) 0.711082 0.04841674 8.521697    0.7818212
    .x          1.133085 0.52179227 2.653040    0.7465663
$pred2
                OR   lower          upper           Pval
    (Intercept) 1   0.18507173  5.40331     1
    .xyes   1   0.07220425  13.84960    1
$pred3
                OR   lower          upper           Pval
    (Intercept) 0.25    0.0127798   1.689944    0.2149978
    .xb         170179249.43 0.0000000  NA  0.9961777
    .xc         12.00   0.6908931   542.678010  0.1220957
</code>```

but with my real dataset there are dozens of predictors so I need a way to order the output. Preferably by the minimum (non-intercept) p-value in each model. Maybe the data structure I've chosen for the summary of each model isn't the best, so any suggestions on how to get the same information in a more flexible data structure would be good too.

答:
You could just use a do.call(rbind) approach, then order by p-value. The [-1, ] omits the intercepts.

```<code>pl <- do.call(rbind, sapply(predictors, function(x) {
  fo <- reformulate(x, response="outcome")
  summary(glm(fo, data=df, family="binomial"))$coef[-1, ]
  }))
pl[order(pl[, 4]), ]
#             Estimate   Std. Error       z value  Pr(>|z|)
# pred3c  2.484907e+00    1.6072751  1.546037e+00 0.1220957
# pred1   1.249440e-01    0.3866195  3.231703e-01 0.7465663
# pred3b  1.895236e+01 3956.1804861  4.790571e-03 0.9961777
# pred2  -5.733167e-16    1.2909944 -4.440892e-16 1.0000000
</code>```

Data

```<code>df <- structure(list(pred1 = c(0, 1.1, 2.4, 3.1, 4, 5.9, 4.2, 3.3,
2.2, 1.1), pred2 = structure(c(2L, 1L, 1L, 2L, 2L, 1L, 1L, 2L,
1L, 1L), .Label = c("no", "yes"), class = "factor"), pred3 = structure(c(1L,
2L, 3L, 3L, 1L, 3L, 1L, 1L, 1L, 3L), .Label = c("a", "b", "c"
), class = "factor"), outcome = structure(c(1L, 2L, 1L, 2L, 1L,
2L, 1L, 2L, 1L, 2L), .Label = c("alive", "dead"), class = "factor")), class = "data.frame", row.names = c(NA,
-10L))

predictors <- c("pred1", "pred2", "pred3")
</code>```

Body:
As a preliminary to creating a multivariate logistic regression I'm doing univariate regressions and want to select the variables with p < 0.20 to include in the multivariate model. I can map the required variables to glm and get the output of the models, but am struggling to order them by rank of p-value.

This is what I have so far:

predictor1 <- c(0,1.1,2.4,3.1,4.0,5.9,4.2,3.3,2.2,1.1)
predictor2 <- as.factor(c("yes","no","no","yes","yes","no","no","yes","no","no"))
predictor3 <- as.factor(c("a", "b", "c", "c", "a", "c", "a", "a", "a", "c"))
outcome <- as.factor(c("alive","dead","alive","dead","alive","dead","alive","dead","alive","dead"))
df <- data.frame(pred1 = predictor1, pred2 = predictor2, pred3 = predictor3, outcome = outcome)
predictors <- c("pred1", "pred2", "pred3")
df %>%
    select(predictors) %>%
    map(~ glm(df$outcome ~ .x, data = df, family = "binomial"))  %>%
    #Extract odds ratio, confidence interval lower and upper bounds, and p value
    map(function (x, y) data.frame(OR = exp(coef(x)),
        lower=exp(confint(x)[,1]),
        upper=exp(confint(x)[,2]),
        Pval = coef(summary(x))[,4]))

This code spits out a summary of each model

$pred1
                OR   lower          upper           Pval
    (Intercept) 0.711082 0.04841674 8.521697    0.7818212
    .x          1.133085 0.52179227 2.653040    0.7465663
$pred2
                OR   lower          upper           Pval
    (Intercept) 1   0.18507173  5.40331     1
    .xyes   1   0.07220425  13.84960    1
$pred3
                OR   lower          upper           Pval
    (Intercept) 0.25    0.0127798   1.689944    0.2149978
    .xb         170179249.43 0.0000000  NA  0.9961777
    .xc         12.00   0.6908931   542.678010  0.1220957

but with my real dataset there are dozens of predictors so I need a way to order the output. Preferably by the minimum (non-intercept) p-value in each model. Maybe the data structure I've chosen for the summary of each model isn't the best, so any suggestions on how to get the same information in a more flexible data structure would be good too.

Body:
You could just use a do.call(rbind) approach, then order by p-value. The [-1, ] omits the intercepts.

pl <- do.call(rbind, sapply(predictors, function(x) {
  fo <- reformulate(x, response="outcome")
  summary(glm(fo, data=df, family="binomial"))$coef[-1, ]
  }))
pl[order(pl[, 4]), ]
#             Estimate   Std. Error       z value  Pr(>|z|)
# pred3c  2.484907e+00    1.6072751  1.546037e+00 0.1220957
# pred1   1.249440e-01    0.3866195  3.231703e-01 0.7465663
# pred3b  1.895236e+01 3956.1804861  4.790571e-03 0.9961777
# pred2  -5.733167e-16    1.2909944 -4.440892e-16 1.0000000

Data

df <- structure(list(pred1 = c(0, 1.1, 2.4, 3.1, 4, 5.9, 4.2, 3.3,
2.2, 1.1), pred2 = structure(c(2L, 1L, 1L, 2L, 2L, 1L, 1L, 2L,
1L, 1L), .Label = c("no", "yes"), class = "factor"), pred3 = structure(c(1L,
2L, 3L, 3L, 1L, 3L, 1L, 1L, 1L, 3L), .Label = c("a", "b", "c"
), class = "factor"), outcome = structure(c(1L, 2L, 1L, 2L, 1L,
2L, 1L, 2L, 1L, 2L), .Label = c("alive", "dead"), class = "factor")), class = "data.frame", row.names = c(NA,
-10L))

predictors <- c("pred1", "pred2", "pred3")


问:
Handling Null Pointer while using lambda
Will below code ever get nullPointerException unless e.getKey() returns null

```<code>Map<Integer, Optional<SecurityAttributeChange>> spnCreationDetails;
Optional.ofNullable(spnCreationDetails.get(e.getKey()).orElse(new SecurityAttributeChange()).getNewAttribute())
                                    .orElse(new SecurityAttr())
                                    .getUserName());
</code>```

I am getting NPE in this line, is there anyway to debug this? I know spnCreationDetails.get(e.getKey()) returns null, Am i missing anything in handling null over here?

- EDIT

Here is the almost complete method which will help to give input on how to refactor this so that it's readable.

```<code>private void updateAuditFields(List<SecurityAttributeChange> securityChanges, Map<Integer, Map<String, Object>> result) {

    Map<Integer, Optional<SecurityAttributeChange>> spnModificationDetails = ...

    Map<Integer, Optional<SecurityAttributeChange>> spnCreationDetails = ...

    result.entrySet().stream().forEach(e -> {
        e.getValue()
                .put("userIdLastChanged",
                        Optional.ofNullable(Optional.ofNullable(spnModificationDetails.get(e.getKey()))
                                .orElse(Optional.of(new SecurityAttributeChange()))
                                .get()
                                .getNewAttribute()).orElse(new SecurityAttr()).getUserName());

        e.getValue()
                .put("lastChangedDatetime",
                        Optional.ofNullable(Optional.ofNullable(spnModificationDetails.get(e.getKey()))
                                .orElse(Optional.of(new SecurityAttributeChange()))
                                .get()
                                .getNewAttribute()).orElse(new SecurityAttr()).getKnowledgeBeginDate());

        e.getValue()
                .put("userIdCreated", Optional.ofNullable(
                        Optional.ofNullable(spnCreationDetails.get(e.getKey())).orElse(Optional.of(new SecurityAttributeChange())).get().getNewAttribute())
                        .orElse(new SecurityAttr())
                        .getUserName());

        e.getValue()
                .put("createdDatetime",
                        Optional.ofNullable(Optional.ofNullable(spnCreationDetails.get(e.getKey()))
                                .orElse(Optional.of(new SecurityAttributeChange()))
                                .get()
                                .getNewAttribute()).orElse(new SecurityAttr()).getKnowledgeBeginDate());

    });
}
</code>```

答:
If spnCreationDetails.get(e.getKey()) can be null, you probably need:

```<code>Optional.ofNullable(spnCreationDetails.get(e.getKey()))
        .orElse(new SecurityAttributeChange())
        .getNewAttribute()
        .orElse(new SecurityAttr())
        .getUserName();
</code>```

i.e. spnCreationDetails.get(e.getKey()) should be wrapped with an Optional.

EDIT: Seeing your comment, spnCreationDetails.get(e.getKey()) can return either a null or an Optional<SecurityAttributeChange>, so it would be better to transform only the null into a new Optional:

```<code>spnCreationDetails.getOrDefault(e.getKey(),Optional.empty())
                  .orElse(new SecurityAttributeChange())
                  .getNewAttribute()
                  .orElse(new SecurityAttr())
                  .getUserName();
</code>```

Body:
Will below code ever get nullPointerException unless e.getKey() returns null

Map<Integer, Optional<SecurityAttributeChange>> spnCreationDetails;
Optional.ofNullable(spnCreationDetails.get(e.getKey()).orElse(new SecurityAttributeChange()).getNewAttribute())
                                    .orElse(new SecurityAttr())
                                    .getUserName());

I am getting NPE in this line, is there anyway to debug this? I know spnCreationDetails.get(e.getKey()) returns null, Am i missing anything in handling null over here?

- EDIT

Here is the almost complete method which will help to give input on how to refactor this so that it's readable.

private void updateAuditFields(List<SecurityAttributeChange> securityChanges, Map<Integer, Map<String, Object>> result) {

    Map<Integer, Optional<SecurityAttributeChange>> spnModificationDetails = ...

    Map<Integer, Optional<SecurityAttributeChange>> spnCreationDetails = ...

    result.entrySet().stream().forEach(e -> {
        e.getValue()
                .put("userIdLastChanged",
                        Optional.ofNullable(Optional.ofNullable(spnModificationDetails.get(e.getKey()))
                                .orElse(Optional.of(new SecurityAttributeChange()))
                                .get()
                                .getNewAttribute()).orElse(new SecurityAttr()).getUserName());

        e.getValue()
                .put("lastChangedDatetime",
                        Optional.ofNullable(Optional.ofNullable(spnModificationDetails.get(e.getKey()))
                                .orElse(Optional.of(new SecurityAttributeChange()))
                                .get()
                                .getNewAttribute()).orElse(new SecurityAttr()).getKnowledgeBeginDate());

        e.getValue()
                .put("userIdCreated", Optional.ofNullable(
                        Optional.ofNullable(spnCreationDetails.get(e.getKey())).orElse(Optional.of(new SecurityAttributeChange())).get().getNewAttribute())
                        .orElse(new SecurityAttr())
                        .getUserName());

        e.getValue()
                .put("createdDatetime",
                        Optional.ofNullable(Optional.ofNullable(spnCreationDetails.get(e.getKey()))
                                .orElse(Optional.of(new SecurityAttributeChange()))
                                .get()
                                .getNewAttribute()).orElse(new SecurityAttr()).getKnowledgeBeginDate());

    });
}

Body:
If spnCreationDetails.get(e.getKey()) can be null, you probably need:

Optional.ofNullable(spnCreationDetails.get(e.getKey()))
        .orElse(new SecurityAttributeChange())
        .getNewAttribute()
        .orElse(new SecurityAttr())
        .getUserName();

i.e. spnCreationDetails.get(e.getKey()) should be wrapped with an Optional.

EDIT: Seeing your comment, spnCreationDetails.get(e.getKey()) can return either a null or an Optional<SecurityAttributeChange>, so it would be better to transform only the null into a new Optional:

spnCreationDetails.getOrDefault(e.getKey(),Optional.empty())
                  .orElse(new SecurityAttributeChange())
                  .getNewAttribute()
                  .orElse(new SecurityAttr())
                  .getUserName();


问:
What does the main thread do when run on ui thread is called from a normal thread (non ui)?
I have noticed that the main looper is called during animations, skipping over some animations if the ui thread is doing something labor intensive. One way of solving this problem is to run a thread or runnable or callable and then they join on the ui thread (automatically for callable, and manually by invoking the run on ui thread).

But does that mean that the ui thread may be interrupted during something important by the other threads?
Ie if the other thread returns some data but the ui is in the middle of doing something with the old data.

Short answer:
The main thread will finish what it is doing and will not be interupted, the other thread will post a runnable with the new data on the main thread and continue doing other stuff (if there are any), eventually the main thread will run the runnable containing the new data from the other thread.

答:
runOnUiThread() works as follows

Runs the specified action on the UI thread. If the current thread is
  the UI thread, then the action is executed immediately. If the current
  thread is not the UI thread, the action is posted to the event queue
  of the UI thread.

So, to understand it by using the scenario you posted it would work something like, the main thread will execute the current event that it is working with and will add your event to the event queue of UI thread.


问:
Page redirecting when clicking on blank space on angular 2
I want to redirect to another page when I get some response from the server. (This process is too slow, and take almost 60 seconds to get the response from server). Meanwhile, I will show some spinner kind of thing, And when I get the response, I will redirect to another page. Looks simple?

Yes, But the problem is, Page is not getting redirected automatically when I get the response. It stays on the same page, Now, If I click anywhere on the page, It redirected to another page, Little weird situation.

```<code>this.optimizationService
      .runOptimization(this.runOptimizationModel)
      .subscribe(optimizationResult => {  // this is the first service which send request to server.

        this.optimizationService.notificationEvent.subscribe(eventData => {
          console.log(eventData); // this is another external service for notifications in which, when I will get the response, I want to redirect to another page.
          if (eventData && eventData.length) {
            this._router.navigate([this.optimizationResultScreenURL, 'e1517589-905e-485b-b7ee-7bc6521dcc93']); // This is url rerouting. If I cut and paste this line after first service subscription, it is working fine.
          }
        });
      });
</code>```

Is this situation, because, we are getting a response from the second service after 60 seconds. This is a little weird scenario, but it is happening.
 Is this 60 second the villain.

答:
Could you try something along these lines? (Multiple nested subscribes are not a good practice)

```<code>this.optimizationService
      .runOptimization(this.runOptimizationModel)
      .pipe(
            switchMap(optiResult => this.optimizationService.notificationEvent),
            filter(eventData => eventData && eventData.length),
            tap(eventData => this._router.navigate(/* extract URL data here */))
      )
      .subscribe();
</code>```

I'm not entirely clear on what the first request does, or where you use its response, but the theory in my answer is to use RxJS operators to control the flow. Hope this is useful.

Body:
I want to redirect to another page when I get some response from the server. (This process is too slow, and take almost 60 seconds to get the response from server). Meanwhile, I will show some spinner kind of thing, And when I get the response, I will redirect to another page. Looks simple?

Yes, But the problem is, Page is not getting redirected automatically when I get the response. It stays on the same page, Now, If I click anywhere on the page, It redirected to another page, Little weird situation.

this.optimizationService
      .runOptimization(this.runOptimizationModel)
      .subscribe(optimizationResult => {  // this is the first service which send request to server.

        this.optimizationService.notificationEvent.subscribe(eventData => {
          console.log(eventData); // this is another external service for notifications in which, when I will get the response, I want to redirect to another page.
          if (eventData && eventData.length) {
            this._router.navigate([this.optimizationResultScreenURL, 'e1517589-905e-485b-b7ee-7bc6521dcc93']); // This is url rerouting. If I cut and paste this line after first service subscription, it is working fine.
          }
        });
      });

Is this situation, because, we are getting a response from the second service after 60 seconds. This is a little weird scenario, but it is happening.
 Is this 60 second the villain.

Body:
Could you try something along these lines? (Multiple nested subscribes are not a good practice)

this.optimizationService
      .runOptimization(this.runOptimizationModel)
      .pipe(
            switchMap(optiResult => this.optimizationService.notificationEvent),
            filter(eventData => eventData && eventData.length),
            tap(eventData => this._router.navigate(/* extract URL data here */))
      )
      .subscribe();

I'm not entirely clear on what the first request does, or where you use its response, but the theory in my answer is to use RxJS operators to control the flow. Hope this is useful.


问:
Ruby two strings in an IF condition
In my rails project I've if statement with string conditions which doesn't work.

```<code>  if shop.details['company_role'] == 'CEO' || 'founder'
        'Other'
      else
        shop.details['customer_kind']
      end
  end
</code>```

When I've case with company_role = founder it didn't return me 'Other' but customer_kind

答:
```<code>if shop.details['company_role'].in?('CEO','founder')
  'Other'
else
  shop.details['customer_kind']
end
</code>```

Title: Ruby two strings in an IF condition

Body:
In my rails project I've if statement with string conditions which doesn't work.

  if shop.details['company_role'] == 'CEO' || 'founder'
        'Other'
      else
        shop.details['customer_kind']
      end
  end

When I've case with company_role = founder it didn't return me 'Other' but customer_kind


问:
Can a class inside a class call a getter method from the outer class?
I have a class inside a class.

The outer class does some processing to generate an array of values.

I want the inner class to be able to access the outer class' array.

Is there a clean way to achieve this?

I'm thinking to have a method in the outer class that calls a method in the inner class sending him the address of the array and the inner class needs to hold a pointer in its private member section in order to later point to it by assignment from the method that receives the address. But this feels a little clunky.

答:
Upon construction you can pass a reference of outer class to the constructor of the inner class. Using the reference you can call any function of the outer class.</p>

```<code>
// The actual definition of the inner class.
class inner {
  public:
    inner(outer& o) : outer_(o) // Set the reference.
    {

    }

    // The function using the data in outer.
    void do_stuff()
    {
      int x = outer_.get_data() + 5;
    }

  private:
    // A reference to the outer class.
    outer& outer_;

}

// The actual outer class.
class outer {
 public:
   outer() : inner_(*this) // Set the reference using the this object.
   {

   }

   // This is the function you would like to call.
   int get_data();

 private:
   inner inner_;
}

</code>```

Body:
Upon construction you can pass a reference of outer class to the constructor of the inner class. Using the reference you can call any function of the outer class.

// The actual definition of the inner class.
class inner {
  public:
    inner(outer& o) : outer_(o) // Set the reference.
    {

    }

    // The function using the data in outer.
    void do_stuff()
    {
      int x = outer_.get_data() + 5;
    }

  private:
    // A reference to the outer class.
    outer& outer_;

}

// The actual outer class.
class outer {
 public:
   outer() : inner_(*this) // Set the reference using the this object.
   {

   }

   // This is the function you would like to call.
   int get_data();

 private:
   inner inner_;
}


问:
Facing error with JMeter in Non-GUI mode. Error: "Malformed option -"
I am using Jmeter(5.1.1) in Non-GUI mode and unable to execute it. It still runs fine in GUI mode but fails in Non-GUI with "Error: Malformed option -". I removed the listeners from the JMX file but it still has some HTTP Request which are disabled will that be the problem here.?
I am currently using this command in my Windows 7 machine with Java 8.

Commands:

```<code>jmeter -n -t (location: C:\Users\File.jmx) -l (location: C:\Users\Results.csv)
</code>```

Its not showing results neither updating the results.csv file, after each run its just showing "

Error: Malformed option -

" in command window. Can someone tell me what i am missing or what should i follow.?

答:
First you have to go to Jmeter/bin path where your Jmeter jar is located.

(For Example, C:\apache-jmeter-5.0\bin)

Now after going to that path using cmd, use below command given that your abc.jmx file is at the above mentioned location only and once execution starts it will automatically create def.jtl at that location, hope this have given you clarity:

jmeter -n -t abc.jmx -l def.jtl

Body:
I am using Jmeter(5.1.1) in Non-GUI mode and unable to execute it. It still runs fine in GUI mode but fails in Non-GUI with "Error: Malformed option -". I removed the listeners from the JMX file but it still has some HTTP Request which are disabled will that be the problem here.?
I am currently using this command in my Windows 7 machine with Java 8.

Commands:

jmeter -n -t (location: C:\Users\File.jmx) -l (location: C:\Users\Results.csv)

Its not showing results neither updating the results.csv file, after each run its just showing "

Error: Malformed option -

" in command window. Can someone tell me what i am missing or what should i follow.?


问:
Task scheduling for ASP.NET with access to HttpContext
First of all, my aim is to implement task scheduling in which the job is to create an offline HTML file of the current webpage everyday.

I have tried Quartz.NET but it seems unfit because HttpContext cannot be accessed by the Job class. As the content of the page highly rely on server side data, and there are lot of client side edits when the offline file is being generated, these could be very complex if no direct access into 'ready-made' HttpContext.

Any recommendation and idea for me?

(I'm using earlier version of ASP.NET instead of Core, so HttpContextAccessor is not considered either.)

答:
While creating Job you have access to HttpContext, you can supply all the information from HttpContext to JobBuilder.

Code taken from https://www.quartz-scheduler.net/documentation/quartz-3.x/tutorial/more-about-jobs.html

Code is in c#, I hope you would be able to do same in vb.net

```<code>// define the job and tie it to our DumbJob class

IJobDetail job = JobBuilder.Create<DumbJob>()
    .WithIdentity("myJob", "group1")
    .UsingJobData("jobSays", "Hello World!") // key value (put required key and value from HttpContext)
    .UsingJobData("myFloatValue", 3.141f)
    .Build();
</code>```

Here’s a quick example of getting data from the JobDataMap during the job’s execution:

Getting Values from a JobDataMap

```<code>public class DumbJob : IJob
{
    public async Task Execute(IJobExecutionContext context)
    {
        JobKey key = context.JobDetail.Key;

        JobDataMap dataMap = context.JobDetail.JobDataMap;

        string jobSays = dataMap.GetString("jobSays");
        float myFloatValue = dataMap.GetFloat("myFloatValue");

        await Console.Error.WriteLineAsync("Instance " + key + " of DumbJob says: " + jobSays + ", and val is: " + myFloatValue);
    }
}
</code>```

Body:
While creating Job you have access to HttpContext, you can supply all the information from HttpContext to JobBuilder.

Code taken from https://www.quartz-scheduler.net/documentation/quartz-3.x/tutorial/more-about-jobs.html

Code is in c#, I hope you would be able to do same in vb.net

// define the job and tie it to our DumbJob class

IJobDetail job = JobBuilder.Create<DumbJob>()
    .WithIdentity("myJob", "group1")
    .UsingJobData("jobSays", "Hello World!") // key value (put required key and value from HttpContext)
    .UsingJobData("myFloatValue", 3.141f)
    .Build();

Here’s a quick example of getting data from the JobDataMap during the job’s execution:

Getting Values from a JobDataMap

public class DumbJob : IJob
{
    public async Task Execute(IJobExecutionContext context)
    {
        JobKey key = context.JobDetail.Key;

        JobDataMap dataMap = context.JobDetail.JobDataMap;

        string jobSays = dataMap.GetString("jobSays");
        float myFloatValue = dataMap.GetFloat("myFloatValue");

        await Console.Error.WriteLineAsync("Instance " + key + " of DumbJob says: " + jobSays + ", and val is: " + myFloatValue);
    }
}


问:
No advertisement is shown from Admob
I had an Google Admob account which was banned by any reason (for 30 days, and I've no goddamn idea why) probably for "watching" the interstitial which I cannot avoid.

I then had to create a new account on AdMob because I do not have the time to wait 30 days for this.

I also have my iOS application linked to Firebase (On my old gmail account) which is linked to my banned AdMob account.

I replaced my key in info.plist and googleService-info.plist
I changed the app unit ID.

```<code>        interstitial = GADInterstitial(adUnitID: "ca-app-pub-MY-ID-is-here")
        let request = GADRequest()

        request.testDevices = [ kGADSimulatorID]
        interstitial.load(request)
        interstitial.delegate = self

</code>```

```<code>                                    if self.interstitial.isReady
                                    {
                                        self.interstitial.present(fromRootViewController: self)
                                    }
                                    else
                                    {
                                        print("Advertisement is not ready!")

                                        self.performSegue(withIdentifier: "History", sender: self)
                                    }
</code>```

No ads is being displayed on the application, but why? Is it impossible to add advertisement to this right now? Even thought I changed my account?

The new account is NOT linked to the Firebase, does that matter?

I expect advertisement to show up but it doesnt.

答:
First you should always use test ads otherwise you could get banned. Second try your code using test ad unit IDs - then you can see if problem lies in your code or account. If test ads work then the problem is not in your code! If not then post all the code or check account.

One more thing make sure you didn’t link your app with old AdMob account?

Regarding previous answer new AdMob SDK 7.44.0 app id goes to info.plist not AppDelegate. What version are you using if newer the AppDelegate or other place in app should include

```<code> GADMobileAds.sharedInstance().start(completionHandler: nil)
</code>```

Title: No advertisement is shown from Admob

Body:
I had an Google Admob account which was banned by any reason (for 30 days, and I've no goddamn idea why) probably for "watching" the interstitial which I cannot avoid.

I then had to create a new account on AdMob because I do not have the time to wait 30 days for this.

I also have my iOS application linked to Firebase (On my old gmail account) which is linked to my banned AdMob account.

I replaced my key in info.plist and googleService-info.plist
I changed the app unit ID.

        interstitial = GADInterstitial(adUnitID: "ca-app-pub-MY-ID-is-here")
        let request = GADRequest()

        request.testDevices = [ kGADSimulatorID]
        interstitial.load(request)
        interstitial.delegate = self

                                    if self.interstitial.isReady
                                    {
                                        self.interstitial.present(fromRootViewController: self)
                                    }
                                    else
                                    {
                                        print("Advertisement is not ready!")

                                        self.performSegue(withIdentifier: "History", sender: self)
                                    }

No ads is being displayed on the application, but why? Is it impossible to add advertisement to this right now? Even thought I changed my account?

The new account is NOT linked to the Firebase, does that matter?

I expect advertisement to show up but it doesnt.

Body:
First you should always use test ads otherwise you could get banned. Second try your code using test ad unit IDs - then you can see if problem lies in your code or account. If test ads work then the problem is not in your code! If not then post all the code or check account.

One more thing make sure you didn’t link your app with old AdMob account?

Regarding previous answer new AdMob SDK 7.44.0 app id goes to info.plist not AppDelegate. What version are you using if newer the AppDelegate or other place in app should include

 GADMobileAds.sharedInstance().start(completionHandler: nil)


答:
Use map_dfr instead of map, filter rows with intercept then do arrange. Use tidy from broom instead of your custom function.

```<code>library(broom)
df %>%
   select(predictors) %>%
   map(~ glm(df$outcome ~ .x, data = df, family = "binomial")) %>%
   map_dfr(tidy, .id='Model') %>%
   filter(term!="(Intercept)") %>% arrange(p.value)

# A tibble: 4 x 6
Model term   estimate std.error statistic p.value
<chr> <chr>     <dbl>     <dbl>     <dbl>   <dbl>
1 pred3 .xc    2.48e+ 0     1.61   1.55e+ 0   0.122
2 pred1 .x     1.25e- 1     0.387  3.23e- 1   0.747
3 pred3 .xb    1.90e+ 1  3956.     4.79e- 3   0.996
4 pred2 .xyes -5.73e-16     1.29  -4.44e-16   1.000
</code>```

Title: Ordering a list of dataframes by minimum column value in R

Body:
Use map_dfr instead of map, filter rows with intercept then do arrange. Use tidy from broom instead of your custom function.

library(broom)
df %>%
   select(predictors) %>%
   map(~ glm(df$outcome ~ .x, data = df, family = "binomial")) %>%
   map_dfr(tidy, .id='Model') %>%
   filter(term!="(Intercept)") %>% arrange(p.value)

# A tibble: 4 x 6
Model term   estimate std.error statistic p.value
<chr> <chr>     <dbl>     <dbl>     <dbl>   <dbl>
1 pred3 .xc    2.48e+ 0     1.61   1.55e+ 0   0.122
2 pred1 .x     1.25e- 1     0.387  3.23e- 1   0.747
3 pred3 .xb    1.90e+ 1  3956.     4.79e- 3   0.996
4 pred2 .xyes -5.73e-16     1.29  -4.44e-16   1.000


问:
Table reference for VLOOKUP VBA
I'm trying to use a table as reference for my VLOOKUP function using VBA, but it doesn't seem to work. Could somebody help me? My guess is that I'm not calling the tables properly.

Some info:

Table_3 and Table1 are set tables

Both of them are not fixed (data is added to it)

```<code>Range("Table_3[Status]") = Application.WorksheetFunction.VLookup(Range("Table_3[Part_Number]"), Range("Table1[[#All];[Part Number]:[Status]]"), 3, False)
</code>```

答:
You could try:</p>

```<code>Option Explicit

Sub test()

    Dim tbl1 As ListObject, tbl3 As ListObject

    'Set you sheet
    With ThisWorkbook.Worksheets("Sheet1")
        'Set tables
        Set tbl1 = .ListObjects("Table1")
        Set tbl3 = .ListObjects("Table_3")
        tbl3.ListColumns("Status").DataBodyRange.FormulaR1C1 = "=VLOOKUP([Part Number],Table1[#All],3,FALSE)"
    End With

End Sub
</code>```

Title: Table reference for VLOOKUP VBA

Body:
I'm trying to use a table as reference for my VLOOKUP function using VBA, but it doesn't seem to work. Could somebody help me? My guess is that I'm not calling the tables properly.

Some info:

Table_3 and Table1 are set tables

Both of them are not fixed (data is added to it)

Range("Table_3[Status]") = Application.WorksheetFunction.VLookup(Range("Table_3[Part_Number]"), Range("Table1[[#All];[Part Number]:[Status]]"), 3, False)

Body:
You could try:

Option Explicit

Sub test()

    Dim tbl1 As ListObject, tbl3 As ListObject

    'Set you sheet
    With ThisWorkbook.Worksheets("Sheet1")
        'Set tables
        Set tbl1 = .ListObjects("Table1")
        Set tbl3 = .ListObjects("Table_3")
        tbl3.ListColumns("Status").DataBodyRange.FormulaR1C1 = "=VLOOKUP([Part Number],Table1[#All],3,FALSE)"
    End With

End Sub


问:
Mongoose - finding subdocuments by criteria
I've just got stuck with this problem. I've got two Mongoose schemas:

```<code>var childrenSchema = mongoose.Schema({
    name: {
        type: String
    },
    age: {
        type: Number,
        min: 0
    }
});

var parentSchema = mongoose.Schema({
    name : {
        type: String
    },
    children: [childrenSchema]
});
</code>```

Question is, how to fetch all subdocuments (in this case, childrenSchema objects) from every parent document? Let's suppose I have some data:

```<code>var parents = [
    { name: "John Smith",
    children: [
        { name: "Peter", age: 2 }, { name: "Margaret", age: 20 }
    ]},
    { name: "Another Smith",
    children: [
        { name: "Martha", age: 10 }, { name: "John", age: 22 }
    ]}
];
</code>```

I would like to retrieve - in a single query - all children older than 18. Is it possible? Every answer will be appreciated, thanks!

答:
A. Jesse Jiryu Davis's response works like a charm, however for later versions of Mongoose (Mongoose 5.x) we get the error:

Mongoose 5.x disallows passing a spread of operators to Model.aggregate(). Instead of Model.aggregate({ $match }, { $skip }), do Model.aggregate([{ $match }, { $skip }])

So the code would simply now be:

```<code>> db.parents.aggregate([{
    $match: {'children.age': {$gte: 18}}
}, {
    $unwind: '$children'
}, {
    $match: {'children.age': {$gte: 18}}
}, {
    $project: {
        name: '$children.name',
        age:'$children.age'
    }
}])
{
    "result" : [
        {
            "_id" : ObjectId("51a7bf04dacca8ba98434eb5"),
            "name" : "Margaret",
            "age" : 20
        },
        {
            "_id" : ObjectId("51a7bf04dacca8ba98434eb6"),
            "name" : "John",
            "age" : 22
        }
    ],
    "ok" : 1
}
</code>```

(note the array brackets around the queries)

Hope this helps someone!

Body:
I've just got stuck with this problem. I've got two Mongoose schemas:

var childrenSchema = mongoose.Schema({
    name: {
        type: String
    },
    age: {
        type: Number,
        min: 0
    }
});

var parentSchema = mongoose.Schema({
    name : {
        type: String
    },
    children: [childrenSchema]
});

Question is, how to fetch all subdocuments (in this case, childrenSchema objects) from every parent document? Let's suppose I have some data:

var parents = [
    { name: "John Smith",
    children: [
        { name: "Peter", age: 2 }, { name: "Margaret", age: 20 }
    ]},
    { name: "Another Smith",
    children: [
        { name: "Martha", age: 10 }, { name: "John", age: 22 }
    ]}
];

I would like to retrieve - in a single query - all children older than 18. Is it possible? Every answer will be appreciated, thanks!

Body:
A. Jesse Jiryu Davis's response works like a charm, however for later versions of Mongoose (Mongoose 5.x) we get the error:

Mongoose 5.x disallows passing a spread of operators to Model.aggregate(). Instead of Model.aggregate({ $match }, { $skip }), do Model.aggregate([{ $match }, { $skip }])

So the code would simply now be:

> db.parents.aggregate([{
    $match: {'children.age': {$gte: 18}}
}, {
    $unwind: '$children'
}, {
    $match: {'children.age': {$gte: 18}}
}, {
    $project: {
        name: '$children.name',
        age:'$children.age'
    }
}])
{
    "result" : [
        {
            "_id" : ObjectId("51a7bf04dacca8ba98434eb5"),
            "name" : "Margaret",
            "age" : 20
        },
        {
            "_id" : ObjectId("51a7bf04dacca8ba98434eb6"),
            "name" : "John",
            "age" : 22
        }
    ],
    "ok" : 1
}

(note the array brackets around the queries)

Hope this helps someone!


答:
Try I guess) In your // some unrelated code is contains setContentView method?

```<code>public class RecogActivity extends AppCompatActivity {

    private Button voiceBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        voiceBtn = findViewById(R.id.goToVoice);

        setContentView(R.layout.some_layout)
        // some unrelated code

        configureActivitySwap();
    }

    public void configureActivitySwap(){
        // Button voiceBtn = (findViewById(R.id.goToVoice));

        voiceBtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }

}
</code>```

You caught NPE because of findViewById is calling on inflated view. You are have been calling findViewById before setContentView in the first case and got the exception. And in the second case - in configureActivitySwap, that going after setContentView. Move setContentView after super.onCreate(savedInstanceState) and all will be working fine.

Title: App crashes when attempting to swap activities

Body:
This is a basic activity swapping.

The app does not crash if i declare a local button inside the configureActivitySwap() method like this:

Button voiceBtn = (findViewById(R.id.goToVoice));

But I have to declare the button in the global scope instead so I can use the button in other methods, mainly activating and deactivating the button when it should/should not be pressed.

I also noticed that if I remove the finish(); method and replace it with something else the app functions normally, but I have to have the finish(); method one way or another.

public class RecogActivity extends AppCompatActivity {

    private Button voiceBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        voiceBtn = findViewById(R.id.goToVoice);
        setContentView(R.layout.main_layout);

        // some unrelated code

        configureActivitySwap();
    }

    public void configureActivitySwap(){
        // Button voiceBtn = (findViewById(R.id.goToVoice));

        voiceBtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }

}

My runtime error logs:

    E/AndroidRuntime: FATAL EXCEPTION: main
        Process: tk.gandriks.gaaudiotransform, PID: 23125
        java.lang.RuntimeException: Unable to start activity ComponentInfo{tk.gandriks.gaaudiotransform/tk.gandriks.gaaudiotransform.RecogActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2957)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3032)
            at android.app.ActivityThread.-wrap11(Unknown Source:0)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1696)
            at android.os.Handler.dispatchMessage(Handler.java:105)
            at android.os.Looper.loop(Looper.java:164)
            at android.app.ActivityThread.main(ActivityThread.java:6944)
            at java.lang.reflect.Method.invoke(Native Method)
            at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)
         Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
            at tk.gandriks.gaaudiotransform.RecogActivity.configureActivitySwap(RecogActivity.java:140)
            at tk.gandriks.gaaudiotransform.RecogActivity.onCreate(RecogActivity.java:124)
            at android.app.Activity.performCreate(Activity.java:7183)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1220)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2910)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3032)
            at android.app.ActivityThread.-wrap11(Unknown Source:0)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1696)
            at android.os.Handler.dispatchMessage(Handler.java:105)
            at android.os.Looper.loop(Looper.java:164)
            at android.app.ActivityThread.main(ActivityThread.java:6944)
            at java.lang.reflect.Method.invoke(Native Method)
            at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)

Body:
Try I guess) In your // some unrelated code is contains setContentView method?

public class RecogActivity extends AppCompatActivity {

    private Button voiceBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        voiceBtn = findViewById(R.id.goToVoice);

        setContentView(R.layout.some_layout)
        // some unrelated code

        configureActivitySwap();
    }

    public void configureActivitySwap(){
        // Button voiceBtn = (findViewById(R.id.goToVoice));

        voiceBtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }

}

You caught NPE because of findViewById is calling on inflated view. You are have been calling findViewById before setContentView in the first case and got the exception. And in the second case - in configureActivitySwap, that going after setContentView. Move setContentView after super.onCreate(savedInstanceState) and all will be working fine.


问:
Make ui-icon appear on same line as other text within

I'm bad with CSS, and I'm trying to get the ui-icon on the same line as the text in a LI.

```<code><ul>
    <li class="ui-state-default">
        <span>Hello</span>
        <span class="ui-icon ui-icon-close"></span>
    </li>
</ul>
</code>```

Normally text doesn't do that within a li, so I think it's something with the ui-icon css, but I couldn't find what was causing it.

答:
Further to my question comment above, I've found this in my jQuery-ui CSS, assuming that's what you're using:

```<code>/* states and images */
.ui-icon { display: block; text-indent: -99999px; overflow: hidden; background-repeat: no-repeat; }
</code>```

Changing (or overriding) the display: block using display: inline-block should allow the icon to appear on the same line

Title: Make ui-icon appear on same line as other text within <li>

Body:
I'm bad with CSS, and I'm trying to get the ui-icon on the same line as the text in a LI.

        Hello

Normally text doesn't do that within a li, so I think it's something with the ui-icon css, but I couldn't find what was causing it.

Body:
Further to my question comment above, I've found this in my jQuery-ui CSS, assuming that's what you're using:

/* states and images */
.ui-icon { display: block; text-indent: -99999px; overflow: hidden; background-repeat: no-repeat; }

Changing (or overriding) the display: block using display: inline-block should allow the icon to appear on the same line