问:
Add function in a PowerShell script
I am trying to incorporate this function to my script but it shows me errors If I add any other code before this function as seen below. I enclosed the parameter in {} and the error no longer shows but it messes up my output since the parameters are no longer being defined. I have other code that needs to run and before this part of the script executes. You can see adding any other code before this function causes errors.

So I don't know how to include this part of the script with my other code and have it work. Any Help?

答:
Place the script into a function. You just surround the code in a function.

```<code>Function Get-Traceroute{
    [CmdletBinding()]
    param(
        [Parameter(Mandatory=$True,ValueFromPipeline=$True)]
        [String]$Target,

        [Parameter(ValueFromPipeline)]
        [Alias("c")]
        [ValidateRange(5,100)]
        [int]$PingCycles = 10, #Default to 10 pings per hop; minimum of 5, maximum of 100

        [Parameter(ValueFromPipeline)]
        [Alias("b")]
        [ValidateRange(32,1000)]
        [int]$BufLen = 32, #Default to 32 bytes of data in the ICMP packet, maximum of 1000 bytes

        [Parameter(ValueFromPipeline)]
        [Alias("s")]
        [IPAddress]$DNSServer = $Null,

        [Parameter(ValueFromPipeline)]
        [Alias("f")]
        [String]$Filename = "Traceroute_$Target"

    )
    Function script:Set-Variables {
    ...more code here...
}
</code>```

Then you can just call the function Get-TraceRoute -Target 8.8.8.8

Title: Add function in a PowerShell script

Body:
Place the script into a function. You just surround the code in a function.

Function Get-Traceroute{
    [CmdletBinding()]
    param(
        [Parameter(Mandatory=$True,ValueFromPipeline=$True)]
        [String]$Target,

        [Parameter(ValueFromPipeline)]
        [Alias("c")]
        [ValidateRange(5,100)]
        [int]$PingCycles = 10, #Default to 10 pings per hop; minimum of 5, maximum of 100

        [Parameter(ValueFromPipeline)]
        [Alias("b")]
        [ValidateRange(32,1000)]
        [int]$BufLen = 32, #Default to 32 bytes of data in the ICMP packet, maximum of 1000 bytes

        [Parameter(ValueFromPipeline)]
        [Alias("s")]
        [IPAddress]$DNSServer = $Null,

        [Parameter(ValueFromPipeline)]
        [Alias("f")]
        [String]$Filename = "Traceroute_$Target"

    )
    Function script:Set-Variables {
    ...more code here...
}

Then you can just call the function Get-TraceRoute -Target 8.8.8.8


来源: stackexchange

答:
Decorators and parameters need to be placed at the top of a script.

So, your parameter declaration (the [CmdletBinding] to then end of the param() block) should be at the top of the script.  Then you can include that other function in it's entirety.  For instance, it would look like...

```<code> [Parameter(ValueFromPipeline)]
    [Alias("s")]
    [IPAddress]$DNSServer = $null,

    [Parameter(ValueFromPipeline)]
    [Alias("f")]
    [String]$Filename = "Traceroute_$Target"

    )#end of your original param block

Function Get-TraceRoute{
    param(
    [Parameter(Mandatory=$True,ValueFromPipeline=$True)]
    [String]$Target,
#. omitting 230 lines.#

$PerTraceArr | Format-Table -Autosize
}#end of Get-TraceRoute
</code>```

You would then end the script like so:

```<code>}#end of Get-TraceRoute

Get-TraceRoute -Target $ip #or whichever params you want to pass in to your `.ps1` file.
</code>```

ContentLicense: CC BY-SA 4.0

Title: Add function in a PowerShell script

Body:
I am trying to incorporate this function to my script but it shows me errors If I add any other code before this function as seen below. I enclosed the parameter in {} and the error no longer shows but it messes up my output since the parameters are no longer being defined. I have other code that needs to run and before this part of the script executes. You can see adding any other code before this function causes errors.

So I don't know how to include this part of the script with my other code and have it work. Any Help?

Body:
Decorators and parameters need to be placed at the top of a script.

So, your parameter declaration (the [CmdletBinding] to then end of the param() block) should be at the top of the script.  Then you can include that other function in it's entirety.  For instance, it would look like...

 [Parameter(ValueFromPipeline)]
    [Alias("s")]
    [IPAddress]$DNSServer = $null,

    [Parameter(ValueFromPipeline)]
    [Alias("f")]
    [String]$Filename = "Traceroute_$Target"

    )#end of your original param block

Function Get-TraceRoute{
    param(
    [Parameter(Mandatory=$True,ValueFromPipeline=$True)]
    [String]$Target,
#. omitting 230 lines.#

$PerTraceArr | Format-Table -Autosize
}#end of Get-TraceRoute

You would then end the script like so:

}#end of Get-TraceRoute

Get-TraceRoute -Target $ip #or whichever params you want to pass in to your `.ps1` file.


问:
Getting 404 with Nginx reverse proxy
relatively new with nginx servers, and trying to do relatively tricky stuff. Go easy please.

I don't know what's wrong with my config. I'm trying to do a pretty basic reverse proxy. The first server block that does the SSL encryption definitely works. And if i uncomment the second server block, all my traffic is forwarded over to my main server, which works perfectly. The problem is, I only want certain subdomains exposed to the internet, like my gitea server. so I've commented out the second block and added the server block at the bottom, which only matches with the gitea subdomain. When I do that, all I get is a 404.

I'm also seeing some weird issues where if I go to the site without specifying a subdomain, I get a page from a site I'm no longer hosting, like it's been cached. I saw a stackoverflow post that recommended removing the sendfile option, which didn't seem to affect anything. Thought I'd ask you guys.

I should also mention that the address I'm forwarding through is on the other side of a wireguard tunnel. I don't think that's an issue since I've seen it work regardless, but it could be.

```<code>user www-data;
worker_processes auto;
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;

events {
    worker_connections 768;
    # multi_accept on;
}

stream
{
    server
    {
        listen      [::]:443 ssl ipv6only=on;
        listen      443 ssl;
        proxy_pass  127.0.0.1:80;

        ssl_certificate     /etc/letsencrypt/live/domain.com/fullchain.pem;
        ssl_certificate_key /etc/letsencrypt/live/domain.com/privkey.pem;
        include             /etc/letsencrypt/options-ssl-nginx.conf;
        ssl_dhparam         /etc/letsencrypt/ssl-dhparams.pem;
    }

#   server
#   {
#       listen 80;
#       proxy_pass 10.67.19.2:80;
#   }
}

http {

    ##
    # Basic Settings
    ##

#   sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;
    # server_tokens off;

    # server_names_hash_bucket_size 64;
    # server_name_in_redirect off;

    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    ##
    # SSL Settings
    ##

#   ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE
#   ssl_prefer_server_ciphers on;

    ##
    # Logging Settings
    ##

    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;

    ##
    # Gzip Settings
    ##

    gzip on;

    # gzip_vary on;
    # gzip_proxied any;
    # gzip_comp_level 6;
    # gzip_buffers 16 8k;
    # gzip_http_version 1.1;
    # gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

    ##
    # Virtual Host Configs
    ##

#   include /etc/nginx/conf.d/*.conf;
#   include /etc/nginx/sites-enabled/*.conf;
    server
    {
        listen 80;
        server_name gitea.*;
        location /
        {
            proxy_pass http://10.76.91.3:80;
        }
    }
}
</code>```

答:
If anyone else has this problem. I didn't realize that when you proxy a website with a url based on a subdomain, you have to include the subdomain on the proxied address.

So instead of forwarding to the IP address, I added an entry in my /etc/hosts file: 10.76.91.3 tunnel tunnel.lan gitea.tunnel.lan and modified the nginx conf with the new hostname:

```<code>server
{
    listen 80;
    server_name gitea.*;
    location /
    {
        proxy_pass http://gitea.tunnel.lan;
    }
}
</code>```

and that fixed everything.

Title: Getting 404 with Nginx reverse proxy

Body:
relatively new with nginx servers, and trying to do relatively tricky stuff. Go easy please.

I don't know what's wrong with my config. I'm trying to do a pretty basic reverse proxy. The first server block that does the SSL encryption definitely works. And if i uncomment the second server block, all my traffic is forwarded over to my main server, which works perfectly. The problem is, I only want certain subdomains exposed to the internet, like my gitea server. so I've commented out the second block and added the server block at the bottom, which only matches with the gitea subdomain. When I do that, all I get is a 404.

I'm also seeing some weird issues where if I go to the site without specifying a subdomain, I get a page from a site I'm no longer hosting, like it's been cached. I saw a stackoverflow post that recommended removing the sendfile option, which didn't seem to affect anything. Thought I'd ask you guys.

I should also mention that the address I'm forwarding through is on the other side of a wireguard tunnel. I don't think that's an issue since I've seen it work regardless, but it could be.

user www-data;
worker_processes auto;
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;

events {
    worker_connections 768;
    # multi_accept on;
}

stream
{
    server
    {
        listen      [::]:443 ssl ipv6only=on;
        listen      443 ssl;
        proxy_pass  127.0.0.1:80;

        ssl_certificate     /etc/letsencrypt/live/domain.com/fullchain.pem;
        ssl_certificate_key /etc/letsencrypt/live/domain.com/privkey.pem;
        include             /etc/letsencrypt/options-ssl-nginx.conf;
        ssl_dhparam         /etc/letsencrypt/ssl-dhparams.pem;
    }

#   server
#   {
#       listen 80;
#       proxy_pass 10.67.19.2:80;
#   }
}

http {

    ##
    # Basic Settings
    ##

#   sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;
    # server_tokens off;

    # server_names_hash_bucket_size 64;
    # server_name_in_redirect off;

    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    ##
    # SSL Settings
    ##

#   ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE
#   ssl_prefer_server_ciphers on;

    ##
    # Logging Settings
    ##

    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;

    ##
    # Gzip Settings
    ##

    gzip on;

    # gzip_vary on;
    # gzip_proxied any;
    # gzip_comp_level 6;
    # gzip_buffers 16 8k;
    # gzip_http_version 1.1;
    # gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

    ##
    # Virtual Host Configs
    ##

#   include /etc/nginx/conf.d/*.conf;
#   include /etc/nginx/sites-enabled/*.conf;
    server
    {
        listen 80;
        server_name gitea.*;
        location /
        {
            proxy_pass http://10.76.91.3:80;
        }
    }
}

Body:
If anyone else has this problem. I didn't realize that when you proxy a website with a url based on a subdomain, you have to include the subdomain on the proxied address.

So instead of forwarding to the IP address, I added an entry in my /etc/hosts file: 10.76.91.3 tunnel tunnel.lan gitea.tunnel.lan and modified the nginx conf with the new hostname:

server
{
    listen 80;
    server_name gitea.*;
    location /
    {
        proxy_pass http://gitea.tunnel.lan;
    }
}

and that fixed everything.


问:
Powershell getting values from CSV file
I have a CSV file which looks like this:

```<code>  OldEmailAddress,NewEmailAddress
  test@test.com,test2@test.com
</code>```

Power shell code to import the file:

```<code> $UserInput = Import-csv "C:\Powershell\UserList.txt" -Delimiter ",";
</code>```

I am going though a foreach loop and trying to write the values but it's print it out as an array in the powershell Window.

```<code>    foreach ($User in $UserInput)
    {
     Write-Host $User.OldEmailAddress;
    }
</code>```

The console doesn't display just that filed but the full array.

```<code>   @{OldEmailAddress=test@test.com; NewEmailAddress=test2@test.com}
</code>```

Why is this occurring?

答:
As for this...

```<code>"Testing $User.OldEmailAddress
</code>```

...to make it work, do it this way...

```<code> $UserInput = Import-Csv 'D:\temp\myemaildata.csv' -Delimiter ','

 ForEach($User in $UserInput)
{$User.OldEmailAddress}
<#
# Results

test@test.com
#>

ForEach($User in $UserInput)
{$User.NewEmailAddress}
<#
# Results

test2@test.com
#>

ForEach($User in $UserInput)
{"$User.OldEmailAddress"}
<#
# Results

@{OldEmailAddress=test@test.com; NewEmailAddress=test2@test.com}.OldEmailAddress
#>

ForEach($User in $UserInput){"$($User.OldEmailAddress)"}
<#
# Results

test@test.com
#>

ForEach($User in $UserInput){"$($User.NewEmailAddress)"}
<#
# Results

test2@test.com
#>
</code>```

... no Write-Host needed since output to the screen is the PowerShell default unless you tell it otherwise. ;-}

Yet, why use that extra loop at all, for example:

```<code>Import-Csv 'D:\temp\myemaildata.csv' -Delimiter ','
<#
# Results

OldEmailAddress NewEmailAddress
--------------- ---------------
test@test.com   test2@test.com
#>

Import-Csv 'D:\temp\myemaildata.csv' -Delimiter ',' |
ForEach{$PSItem}

OldEmailAddress NewEmailAddress
--------------- ---------------
test@test.com   test2@test.com

 Import-Csv 'D:\temp\myemaildata.csv' -Delimiter ',' |
ForEach{$PSItem.OldEmailAddress}
<#
# Results

test@test.com
#>

 Import-Csv 'D:\temp\myemaildata.csv' -Delimiter ',' |
ForEach{$PSItem.NewEmailAddress}

<#
# Results

test2@test.com
#>
</code>```

Title: Powershell getting values from CSV file

Body:
I have a CSV file which looks like this:

  OldEmailAddress,NewEmailAddress
  test@test.com,test2@test.com

Power shell code to import the file:

 $UserInput = Import-csv "C:\Powershell\UserList.txt" -Delimiter ",";

I am going though a foreach loop and trying to write the values but it's print it out as an array in the powershell Window.

    foreach ($User in $UserInput)
    {
     Write-Host $User.OldEmailAddress;
    }

The console doesn't display just that filed but the full array.

   @{OldEmailAddress=test@test.com; NewEmailAddress=test2@test.com}

Why is this occurring?

Body:
As for this...

"Testing $User.OldEmailAddress

...to make it work, do it this way...

 $UserInput = Import-Csv 'D:\temp\myemaildata.csv' -Delimiter ','

 ForEach($User in $UserInput)
{$User.OldEmailAddress}
<#
# Results

test@test.com
#>

ForEach($User in $UserInput)
{$User.NewEmailAddress}
<#
# Results

test2@test.com
#>

ForEach($User in $UserInput)
{"$User.OldEmailAddress"}
<#
# Results

@{OldEmailAddress=test@test.com; NewEmailAddress=test2@test.com}.OldEmailAddress
#>

ForEach($User in $UserInput){"$($User.OldEmailAddress)"}
<#
# Results

test@test.com
#>

ForEach($User in $UserInput){"$($User.NewEmailAddress)"}
<#
# Results

test2@test.com
#>

... no Write-Host needed since output to the screen is the PowerShell default unless you tell it otherwise. ;-}

Yet, why use that extra loop at all, for example:

Import-Csv 'D:\temp\myemaildata.csv' -Delimiter ','
<#
# Results

OldEmailAddress NewEmailAddress
--------------- ---------------
test@test.com   test2@test.com
#>

Import-Csv 'D:\temp\myemaildata.csv' -Delimiter ',' |
ForEach{$PSItem}

OldEmailAddress NewEmailAddress
--------------- ---------------
test@test.com   test2@test.com

 Import-Csv 'D:\temp\myemaildata.csv' -Delimiter ',' |
ForEach{$PSItem.OldEmailAddress}
<#
# Results

test@test.com
#>

 Import-Csv 'D:\temp\myemaildata.csv' -Delimiter ',' |
ForEach{$PSItem.NewEmailAddress}

<#
# Results

test2@test.com
#>


问:
Assembly reflection problem in Release mode
I'm facing some weird behavior trying to get the parent assembly in some logging class (only when it's compiled in Release mode).

In Debug mode this works like a charm:

```<code>StackFrame[] frames = new StackTrace().GetFrames();
var assemblies = (from f in frames
                  select f.GetMethod().ReflectedType.Assembly)
                  Distinct()
                  .Last();
</code>```

Example:
assembly A => assembly B => method

when I run the above script in debug mode I get assembly A (as expected) but when it runs in release mode I get: mscorlib instead.
but the most weird thing is that if a check for the whole assemblies stack there is not a single reference of assembly A. how is this possible? what can be happening?

PS: assembly A is a webapp project.

答:
I've created a sample console application with name of consoleA and a class library with name classB.

It return ConsoleA in both situation.
I think your problem is that your A application is a web app and when it has run by another service, which in this case is IIS, it return the running service which hosts your app(assembly A).

Body:
I'm facing some weird behavior trying to get the parent assembly in some logging class (only when it's compiled in Release mode).

In Debug mode this works like a charm:

StackFrame[] frames = new StackTrace().GetFrames();
var assemblies = (from f in frames
                  select f.GetMethod().ReflectedType.Assembly)
                  Distinct()
                  .Last();

Example:
assembly A => assembly B => method

when I run the above script in debug mode I get assembly A (as expected) but when it runs in release mode I get: mscorlib instead.
but the most weird thing is that if a check for the whole assemblies stack there is not a single reference of assembly A. how is this possible? what can be happening?

PS: assembly A is a webapp project.


问:
Best way to condense a list of option type down to only elements that are not none?
I'm unexpectedly having a bit of trouble with going from a list of 'a option down to a list containing only the elements that are Some.

My initial attempt was:

```<code>    let ga = List.filter (fun xx ->
        match xx with
        | Some(g) -> true
        | None -> false) gao
</code>```

But of course, this result type is still 'a option list. I don't know how to use List.map to condense this, because you have to handle all cases in a match statement. I have an ugly solution, but I'm wondering if there is something better.

Ugly:

```<code>    let rec gOptRemove gdec gacc =
        match gdec with
        | head :: tail ->
            match head with
            | Some(a) -> gOptRemove tail (a :: gacc)
            | None -> gOptRemove tail gacc
        | [] -> gacc
</code>```

I would prefer to find a non-recursive solution or find out what the standard way is for this kind of thing.

答:
Another way is to use the Option module functions to filter out the Options with values and then create a list of the values:</p>

```<code>let concreteTypeList =
    optionTypeList
    |> List.filter (fun v -> Option.isSome v)
    |> List.map (fun v -> Option.get v)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm unexpectedly having a bit of trouble with going from a list of 'a option down to a list containing only the elements that are Some.

My initial attempt was:

    let ga = List.filter (fun xx ->
        match xx with
        | Some(g) -> true
        | None -> false) gao

But of course, this result type is still 'a option list. I don't know how to use List.map to condense this, because you have to handle all cases in a match statement. I have an ugly solution, but I'm wondering if there is something better.

Ugly:

    let rec gOptRemove gdec gacc =
        match gdec with
        | head :: tail ->
            match head with
            | Some(a) -> gOptRemove tail (a :: gacc)
            | None -> gOptRemove tail gacc
        | [] -> gacc

I would prefer to find a non-recursive solution or find out what the standard way is for this kind of thing.

Body:
Another way is to use the Option module functions to filter out the Options with values and then create a list of the values:

let concreteTypeList =
    optionTypeList
    |> List.filter (fun v -> Option.isSome v)
    |> List.map (fun v -> Option.get v)


问:
Pytest-bdd giving an name error for variables defined in scenario outline
I am trying to run a test with ptest-bdd. I've used the scenario outline but the variable username is returning a name error saying that username is not defined. I would greatly appreciate a second pair of eyes on my code.

Here is the feature file:

```<code>@login

Feature: Valid Login
    As a employee,
    I want to login to my account
    So I can access the application

    Background:
        Given the login page is displayed

    Scenario Outline: Manager enters correct login credentials and Ok button
        When the user enters their <username> and <password> correctly
        And the user clicks OK
        Then the page redirects to the manager home page

        Examples: Manager
            |   username            |   password                |
            | fake_name             | 1234                      |
</code>```

And here is the test_login_steps.py code:

```<code>from pytest_bdd import scenarios, scenario, given, when, then, parsers
from pages.signin import QaSigninPage
from pages.managerHomepage import QaManagerHomepage
import pytest

CONVERTERS = {
    'username': str,
    'password': str,
}

scenarios('../features/login.feature', example_converters=CONVERTERS)

# Create Page Objects
@pytest.fixture(scope='session')
def pages(test_manager):
    pages={"signin_PAGE": QaSigninPage(test_manager.browser),
            "manager_home_PAGE": QaManagerHomepage(test_manager.browser)}
    return pages

# Given Steps
@given('the login page is displayed')
def login_visit(pages):
    pages["signin_PAGE"].load()

@when('the user enters their <username> and <password> correctly')
def enter_credentials(pages):
    pages["signin_PAGE"].enter_username(username)
    pages["signin_PAGE"].enter_password(password)
</code>```

答: I forgot to pass the variables into the function... I figured it out. </p>

Body:
I am trying to run a test with ptest-bdd. I've used the scenario outline but the variable username is returning a name error saying that username is not defined. I would greatly appreciate a second pair of eyes on my code.

Here is the feature file:

@login

Feature: Valid Login
    As a employee,
    I want to login to my account
    So I can access the application

    Background:
        Given the login page is displayed

    Scenario Outline: Manager enters correct login credentials and Ok button
        When the user enters their <username> and <password> correctly
        And the user clicks OK
        Then the page redirects to the manager home page

        Examples: Manager
            |   username            |   password                |
            | fake_name             | 1234                      |

And here is the test_login_steps.py code:

from pytest_bdd import scenarios, scenario, given, when, then, parsers
from pages.signin import QaSigninPage
from pages.managerHomepage import QaManagerHomepage
import pytest

CONVERTERS = {
    'username': str,
    'password': str,
}

scenarios('../features/login.feature', example_converters=CONVERTERS)

# Create Page Objects
@pytest.fixture(scope='session')
def pages(test_manager):
    pages={"signin_PAGE": QaSigninPage(test_manager.browser),
            "manager_home_PAGE": QaManagerHomepage(test_manager.browser)}
    return pages

# Given Steps
@given('the login page is displayed')
def login_visit(pages):
    pages["signin_PAGE"].load()

@when('the user enters their <username> and <password> correctly')
def enter_credentials(pages):
    pages["signin_PAGE"].enter_username(username)
    pages["signin_PAGE"].enter_password(password)


问:
Encoding Erlang Tuple as JSON
How do I convert a list with Tuples & Atoms & Binary strings in a list into JSON?
I see Erlang : Tuple List into JSON
and I found https://github.com/rustyio/BERT-JS

I want an API I can call like

erlang_json:convert([{a, b, {{c, d}}, 1}, {"a", "b", {{cat, dog}}, 2}

where the atoms would be converted to strings or some other standard way to process on the Javascript side.

I have complicated Erlang lists I need to send to my webpage.

答:
The library jsone is pretty good. It can translate between maps or tuples:
https://github.com/sile/jsone

I've used it extensively and it's lightning fast.

The only problem I've found is that a map that contains a list of maps throws an error. I hope this is fixed, but maybe I'm the only tart trying to do that.

Title: Encoding Erlang Tuple as JSON


问:
viewpager instantiateItem() method's error and not able to inflate layout in fragment
error:

and mainactivity code is empty and layout is:

```<code><?xml version="1.0" encoding="UTF-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<fragment
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:id="@+id/fragment"
  android:name="com.example.circularview.CarFragment"
  tools:layout="@layout/fragment_car" />
</RelativeLayout>
</code>```

fragment (carFragment) code:

```<code>     public class CarFragment extends Fragment {
      View rootView;
      ViewPager event_pager;
      private ArrayList<MyLocation> latLngsArrayList;

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

        event_pager = rootView.findViewById(R.id.event_pager);
        latLngsArrayList = new ArrayList<>();
        latLngsArrayList = GlobalUtils.getLatLongArray();
        MapViewPagerAdapter adapter = new MapViewPagerAdapter(getActivity(), latLngsArrayList);
        event_pager.setAdapter(adapter);
        return rootView;

  }
}
</code>```

and CarFragment layout code:

```<code> <?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  tools:context=".MainActivity">

  <TextView
    android:id="@+id/mapView"
    android:layout_width="0dp"
    android:layout_height="0dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintHorizontal_bias="1.0"
    app:layout_constraintVertical_bias="1.0"/>

  <androidx.constraintlayout.widget.Guideline
    android:id="@+id/guideline"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    app:layout_constraintGuide_percent="0.77"
    tools:layout_editor_absoluteX="0dp"
    tools:layout_editor_absoluteY="507dp"/>

  <androidx.viewpager.widget.ViewPager
    android:id="@+id/event_pager"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:layout_alignParentBottom="true"
    android:layout_marginTop="0dp"
    app:layout_constraintBottom_toBottomOf="@+id/mapView"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="@+id/guideline">

  </androidx.viewpager.widget.ViewPager>
</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

my Adapter:

```<code>    public class MapViewPagerAdapter extends PagerAdapter {
  View   itemView;
  ArrayList<MyLocation> arr_LocationList;
  Context context;

  public MapViewPagerAdapter(Context context, ArrayList<MyLocation> arr_ExploreList) {
    this.context = context;
    this.arr_LocationList = arr_ExploreList;
  }

  @Override
  public int getCount() {
    return arr_LocationList.size();
  }

  @Override
  public boolean isViewFromObject(View arg0, Object arg1) {
    return arg0 == arg1;
  }

  @Override
  public void destroyItem(ViewGroup container, int position, Object object) {
    container.removeView((View) object);
  }

  @NonNull
  @Override
  public View instantiateItem(ViewGroup container, int position) {
    LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    itemView = inflater.inflate(R.layout.recycler_mapview, null);

    container.addView(itemView);

    return itemView;
  }

}
</code>```

error is here in adapter:

```<code>  @NonNull
  @Override
  public View instantiateItem(ViewGroup container, int position) {
    LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    // error  error  error  error
    itemView = inflater.inflate(R.layout.recycler_mapview, null);

    container.addView(itemView);

    return itemView;
  }
</code>```

as i think it should be from my items layout ,here it is

ITEM's Layout:

```<code> <?xml version="1.0"?>

<RelativeLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:paddingBottom="15dp"
  android:paddingTop="15dp">

  <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="120dp"
    android:layout_marginLeft="35dp"
    android:layout_marginRight="45dp"
    android:background="@drawable/mapview"
    android:orientation="horizontal"
    android:layout_marginStart="35dp"
    android:layout_marginEnd="45dp">

    <com.makeramen.roundedimageview.RoundedImageView
      android:layout_width="0dp"
      android:layout_height="match_parent"
      android:layout_weight=".3"
      android:scaleType="fitXY"
      android:src="@mipmap/car"
      app:riv_corner_radius_bottom_left="20dp"
      app:riv_corner_radius_top_left="20dp"
      app:riv_mutate_background="true"
      app:srcCompat="@mipmap/car" />

    <LinearLayout
      android:layout_width="0dp"
      android:layout_height="match_parent"
      android:layout_weight="0.63"
      android:orientation="vertical">

      <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:gravity="center|left"
        android:text="Modern Era Car Servicing"
        android:textColor="#000"
        android:textSize="14dp"
        tools:ignore="RtlHardcoded" />

      <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:text="09388695027"
        android:layout_marginStart="10dp" />
    </LinearLayout>

  </LinearLayout>
</RelativeLayout>
</code>```

logcat:

```<code>    05-26 15:32:43.007 12447-12447/com.example.circularview E/dalvikvm: Could not find class 'androidx.core.view.ViewCompat$2', referenced from method androidx.core.view.ViewCompat.addOnUnhandledKeyEventListener
05-26 15:32:43.007 12447-12447/com.example.circularview E/dalvikvm: Could not find class 'android.view.WindowInsets', referenced from method androidx.core.view.ViewCompat.dispatchApplyWindowInsets
05-26 15:32:43.017 12447-12447/com.example.circularview E/dalvikvm: Could not find class 'android.view.WindowInsets', referenced from method androidx.core.view.ViewCompat.onApplyWindowInsets
05-26 15:32:43.017 12447-12447/com.example.circularview E/dalvikvm: Could not find class 'android.view.View$OnUnhandledKeyEventListener', referenced from method androidx.core.view.ViewCompat.removeOnUnhandledKeyEventListener
05-26 15:32:43.017 12447-12447/com.example.circularview E/dalvikvm: Could not find class 'androidx.core.view.ViewCompat$1', referenced from method androidx.core.view.ViewCompat.setOnApplyWindowInsetsListener
05-26 15:32:43.057 12447-12447/com.example.circularview E/dalvikvm: Could not find class 'android.graphics.drawable.RippleDrawable', referenced from method androidx.appcompat.widget.AppCompatImageHelper.hasOverlappingRendering
05-26 15:32:43.087 12447-12447/com.example.circularview E/dalvikvm: Could not find class 'android.view.textclassifier.TextClassificationManager', referenced from method androidx.appcompat.widget.AppCompatTextClassifierHelper.getTextClassifier
05-26 15:32:43.127 12447-12447/com.example.circularview E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.circularview, PID: 12447
    android.view.InflateException: Binary XML file line #12: Error inflating class <unknown>
        at android.view.LayoutInflater.createView(LayoutInflater.java:620)
        at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:56)
        at android.view.LayoutInflater.onCreateView(LayoutInflater.java:669)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:694)
        at android.view.LayoutInflater.rInflate(LayoutInflater.java:755)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
        at com.example.circularview.MapViewPagerAdapter.instantiateItem(MapViewPagerAdapter.java:43)
        at com.example.circularview.MapViewPagerAdapter.instantiateItem(MapViewPagerAdapter.java:13)
        at androidx.viewpager.widget.ViewPager.addNewItem(ViewPager.java:1010)
        at androidx.viewpager.widget.ViewPager.populate(ViewPager.java:1158)
        at androidx.viewpager.widget.ViewPager.populate(ViewPager.java:1092)
        at androidx.viewpager.widget.ViewPager.onMeasure(ViewPager.java:1622)
        at android.view.View.measure(View.java:16497)
        at androidx.constraintlayout.widget.ConstraintLayout.onMeasure(ConstraintLayout.java:1676)
        at android.view.View.measure(View.java:16497)
        at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:719)
        at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:455)
        at android.view.View.measure(View.java:16497)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
        at androidx.appcompat.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:143)
        at android.view.View.measure(View.java:16497)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
        at androidx.appcompat.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:403)
        at android.view.View.measure(View.java:16497)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
        at android.view.View.measure(View.java:16497)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
        at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404)
        at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)
        at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
        at android.view.View.measure(View.java:16497)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
        at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2291)
        at android.view.View.measure(View.java:16497)
        at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1940)
        at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1137)
        at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1319)
        at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1024)
        at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5694)
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:761)
        at android.view.Choreographer.doCallbacks(Choreographer.java:574)
        at android.view.Choreographer.doFrame(Choreographer.java:544)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:747)
        at android.os.Handler.handleCallback(Handler.java:733)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:136)
        at android.app.ActivityThread.main(ActivityThread.java:5019)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
        at dalvik.system.NativeStart.main(Native Method)
     Caused by: java.lang.reflec
</code>```

all of these codes are part of another app that i made before...it works there but not here...because in the other app it work with map and users location marker and have some atrributes like slide right or slide left that i didnt used here .
what is my codes problem?
it works in MAINACTIVITY but not in FRAGMENT

答:
finally i found out where  my problem is.in ITEM's LAYOUT under RelativeLayout is a Linear Layout that i set background : android:background="@drawable/mapview" and when i clean it it work perfectly.this drawable is a rounded corners view.

```<code>    <?xml version="1.0" encoding="utf-8"?>
<shape
       xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="rectangle">
  <corners
    android:radius="20dp"/>
  <gradient
    android:startColor="#ffffffff"
    android:centerColor="#ffffffff"
    android:endColor="#ffffffff"
    />
</shape>
</code>```

that its name is (drawable-v24) and i think my problem was related to (V24)

Body:
error:

and mainactivity code is empty and layout is:

<?xml version="1.0" encoding="UTF-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<fragment
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:id="@+id/fragment"
  android:name="com.example.circularview.CarFragment"
  tools:layout="@layout/fragment_car" />
</RelativeLayout>

fragment (carFragment) code:

     public class CarFragment extends Fragment {
      View rootView;
      ViewPager event_pager;
      private ArrayList<MyLocation> latLngsArrayList;

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

        event_pager = rootView.findViewById(R.id.event_pager);
        latLngsArrayList = new ArrayList<>();
        latLngsArrayList = GlobalUtils.getLatLongArray();
        MapViewPagerAdapter adapter = new MapViewPagerAdapter(getActivity(), latLngsArrayList);
        event_pager.setAdapter(adapter);
        return rootView;

  }
}

and CarFragment layout code:

 <?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  tools:context=".MainActivity">

  <TextView
    android:id="@+id/mapView"
    android:layout_width="0dp"
    android:layout_height="0dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintHorizontal_bias="1.0"
    app:layout_constraintVertical_bias="1.0"/>

  <androidx.constraintlayout.widget.Guideline
    android:id="@+id/guideline"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    app:layout_constraintGuide_percent="0.77"
    tools:layout_editor_absoluteX="0dp"
    tools:layout_editor_absoluteY="507dp"/>

  <androidx.viewpager.widget.ViewPager
    android:id="@+id/event_pager"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:layout_alignParentBottom="true"
    android:layout_marginTop="0dp"
    app:layout_constraintBottom_toBottomOf="@+id/mapView"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="@+id/guideline">

  </androidx.viewpager.widget.ViewPager>
</androidx.constraintlayout.widget.ConstraintLayout>

my Adapter:

    public class MapViewPagerAdapter extends PagerAdapter {
  View   itemView;
  ArrayList<MyLocation> arr_LocationList;
  Context context;

  public MapViewPagerAdapter(Context context, ArrayList<MyLocation> arr_ExploreList) {
    this.context = context;
    this.arr_LocationList = arr_ExploreList;
  }

  @Override
  public int getCount() {
    return arr_LocationList.size();
  }

  @Override
  public boolean isViewFromObject(View arg0, Object arg1) {
    return arg0 == arg1;
  }

  @Override
  public void destroyItem(ViewGroup container, int position, Object object) {
    container.removeView((View) object);
  }

  @NonNull
  @Override
  public View instantiateItem(ViewGroup container, int position) {
    LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    itemView = inflater.inflate(R.layout.recycler_mapview, null);

    container.addView(itemView);

    return itemView;
  }

}

error is here in adapter:

  @NonNull
  @Override
  public View instantiateItem(ViewGroup container, int position) {
    LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    // error  error  error  error
    itemView = inflater.inflate(R.layout.recycler_mapview, null);

    container.addView(itemView);

    return itemView;
  }

as i think it should be from my items layout ,here it is

ITEM's Layout:

 <?xml version="1.0"?>

<RelativeLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:paddingBottom="15dp"
  android:paddingTop="15dp">

  <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="120dp"
    android:layout_marginLeft="35dp"
    android:layout_marginRight="45dp"
    android:background="@drawable/mapview"
    android:orientation="horizontal"
    android:layout_marginStart="35dp"
    android:layout_marginEnd="45dp">

    <com.makeramen.roundedimageview.RoundedImageView
      android:layout_width="0dp"
      android:layout_height="match_parent"
      android:layout_weight=".3"
      android:scaleType="fitXY"
      android:src="@mipmap/car"
      app:riv_corner_radius_bottom_left="20dp"
      app:riv_corner_radius_top_left="20dp"
      app:riv_mutate_background="true"
      app:srcCompat="@mipmap/car" />

    <LinearLayout
      android:layout_width="0dp"
      android:layout_height="match_parent"
      android:layout_weight="0.63"
      android:orientation="vertical">

      <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:gravity="center|left"
        android:text="Modern Era Car Servicing"
        android:textColor="#000"
        android:textSize="14dp"
        tools:ignore="RtlHardcoded" />

      <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:text="09388695027"
        android:layout_marginStart="10dp" />
    </LinearLayout>

  </LinearLayout>
</RelativeLayout>

logcat:

    05-26 15:32:43.007 12447-12447/com.example.circularview E/dalvikvm: Could not find class 'androidx.core.view.ViewCompat$2', referenced from method androidx.core.view.ViewCompat.addOnUnhandledKeyEventListener
05-26 15:32:43.007 12447-12447/com.example.circularview E/dalvikvm: Could not find class 'android.view.WindowInsets', referenced from method androidx.core.view.ViewCompat.dispatchApplyWindowInsets
05-26 15:32:43.017 12447-12447/com.example.circularview E/dalvikvm: Could not find class 'android.view.WindowInsets', referenced from method androidx.core.view.ViewCompat.onApplyWindowInsets
05-26 15:32:43.017 12447-12447/com.example.circularview E/dalvikvm: Could not find class 'android.view.View$OnUnhandledKeyEventListener', referenced from method androidx.core.view.ViewCompat.removeOnUnhandledKeyEventListener
05-26 15:32:43.017 12447-12447/com.example.circularview E/dalvikvm: Could not find class 'androidx.core.view.ViewCompat$1', referenced from method androidx.core.view.ViewCompat.setOnApplyWindowInsetsListener
05-26 15:32:43.057 12447-12447/com.example.circularview E/dalvikvm: Could not find class 'android.graphics.drawable.RippleDrawable', referenced from method androidx.appcompat.widget.AppCompatImageHelper.hasOverlappingRendering
05-26 15:32:43.087 12447-12447/com.example.circularview E/dalvikvm: Could not find class 'android.view.textclassifier.TextClassificationManager', referenced from method androidx.appcompat.widget.AppCompatTextClassifierHelper.getTextClassifier
05-26 15:32:43.127 12447-12447/com.example.circularview E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.circularview, PID: 12447
    android.view.InflateException: Binary XML file line #12: Error inflating class <unknown>
        at android.view.LayoutInflater.createView(LayoutInflater.java:620)
        at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:56)
        at android.view.LayoutInflater.onCreateView(LayoutInflater.java:669)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:694)
        at android.view.LayoutInflater.rInflate(LayoutInflater.java:755)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
        at com.example.circularview.MapViewPagerAdapter.instantiateItem(MapViewPagerAdapter.java:43)
        at com.example.circularview.MapViewPagerAdapter.instantiateItem(MapViewPagerAdapter.java:13)
        at androidx.viewpager.widget.ViewPager.addNewItem(ViewPager.java:1010)
        at androidx.viewpager.widget.ViewPager.populate(ViewPager.java:1158)
        at androidx.viewpager.widget.ViewPager.populate(ViewPager.java:1092)
        at androidx.viewpager.widget.ViewPager.onMeasure(ViewPager.java:1622)
        at android.view.View.measure(View.java:16497)
        at androidx.constraintlayout.widget.ConstraintLayout.onMeasure(ConstraintLayout.java:1676)
        at android.view.View.measure(View.java:16497)
        at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:719)
        at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:455)
        at android.view.View.measure(View.java:16497)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
        at androidx.appcompat.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:143)
        at android.view.View.measure(View.java:16497)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
        at androidx.appcompat.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:403)
        at android.view.View.measure(View.java:16497)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
        at android.view.View.measure(View.java:16497)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
        at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404)
        at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)
        at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
        at android.view.View.measure(View.java:16497)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
        at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2291)
        at android.view.View.measure(View.java:16497)
        at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1940)
        at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1137)
        at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1319)
        at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1024)
        at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5694)
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:761)
        at android.view.Choreographer.doCallbacks(Choreographer.java:574)
        at android.view.Choreographer.doFrame(Choreographer.java:544)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:747)
        at android.os.Handler.handleCallback(Handler.java:733)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:136)
        at android.app.ActivityThread.main(ActivityThread.java:5019)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
        at dalvik.system.NativeStart.main(Native Method)
     Caused by: java.lang.reflec

all of these codes are part of another app that i made before...it works there but not here...because in the other app it work with map and users location marker and have some atrributes like slide right or slide left that i didnt used here .
what is my codes problem?
it works in MAINACTIVITY but not in FRAGMENT

Body:
finally i found out where  my problem is.in ITEM's LAYOUT under RelativeLayout is a Linear Layout that i set background : android:background="@drawable/mapview" and when i clean it it work perfectly.this drawable is a rounded corners view.

    <?xml version="1.0" encoding="utf-8"?>
<shape
       xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="rectangle">
  <corners
    android:radius="20dp"/>
  <gradient
    android:startColor="#ffffffff"
    android:centerColor="#ffffffff"
    android:endColor="#ffffffff"
    />
</shape>

that its name is (drawable-v24) and i think my problem was related to (V24)


问:
How to update an initial param when prop has changed its value in React Native Navigation
I have a prop that changes when I update the state. How do I update my initial params when passing data to a screen?

props.authMsg gets updated, but not the initial param

```<code><Stack.Screen initialParams={{authMsg: props.authMsg}} name="Login" component={Login} />
</code>```

The param value stays the same.

```<code><Text>{props.route.params.authMsg}</Text>
</code>```

答:
The initial params will never change after initialization. What you can do is create a context in the component where you have the state with the help of the useContext hook and pass the value down so it will be accessible to any children of that component.

https://reactjs.org/docs/hooks-reference.html#usecontext

Body:
I have a prop that changes when I update the state. How do I update my initial params when passing data to a screen?

props.authMsg gets updated, but not the initial param

<Stack.Screen initialParams={{authMsg: props.authMsg}} name="Login" component={Login} />

The param value stays the same.

<Text>{props.route.params.authMsg}</Text>


问:
How to round up a number if it's not an integer?
I want to calculate a simple number, and if the number is not an integer I want to round it up.

For instance, if after a calculation I get 1.2, I want to change it to 2. If the number is 3.7, I want to change it to 4 and so on.

答:
The ceil function is also directly accessible on the Double:

```<code>3.7.ceil.toInt // 4
</code>```

Body:
The ceil function is also directly accessible on the Double:

3.7.ceil.toInt // 4


问:
Remove specific section of string
Hi I have a file that contains several thousand file paths that I am looking to move to Wazhu. Problem is I need directories so what I have looks like
>/apples/oranges/test.ex< What I need is >/apples/oranges<
Not sure if Regex or just using str.replace() is better. As each line is different I would need to find the last / and remove it as well as everything up to <

Hopefully that makes sense.

答:
Try /[^/\r\n]*<$ replace this <

demo

Title: Remove specific section of string

Body:
Try /[^/\r\n]*<$ replace this <

demo


问:
SharePoint column default values - add 10 working days
In SharePoint MOSS 2007, I have created a custom content type that I will be applying to a document library.  One of the required fields is "Incoming Date" and another is the "Due Date".

The Due Date is always 10 working days from the Incoming Date.  The Incoming Date is when the mail room received the letter, not necessarily when the document is posted to the library.

From here:  http://msdn.microsoft.com/en-us/library/bb862071.aspx

```<code>=DATE(YEAR([Incoming Date]),MONTH([Incoming Date]),DAY([Incoming Date])+10)
</code>```

adds 10 days, but how can I add 10 working days?  I don't have the luxury of VS.NET either per the governance plan of our sharepoint rollout.

Assume a human is responsible for the data entry, but I would like to make it easier for them.

答:
I believe I've figured out a fairly bullet-proof method for calculating a 10 business day deadline that accounts for holidays and weekends. 1) Calculate whether the 2 week period is a Monday, and if so, add only 11 days (assuming the start day counts as Day1 of your 10-day period). Otherwise, you add 13 to account for the 10 working days plus two weekends (remember, the start date already counts as Day1; your variables would be 12 and 14 if you did NOT count the start date as Day1). 2) Create a unique calculated column for every holiday and return a value of 1 if the holiday falls in the range. 3) Determine your "gross date" by adding values (weekends and holidays) to your start date. 4) Determine whether your gross date falls on a Saturday or Sunday, and if so, return the appropriate number of days to push off until Monday. 5) Add all the weekend, holiday, and added Sat and Sun values to your start date, which gives you your due date.

NOTE: The only challenges I see here is if a holiday pushes the due date into the weekend, which then pushes the due date to a Monday that happens to be yet another holiday. This didn't happen in my holiday schedule, but it might in yours. In addition, you'll need to keep adding new holidays every year, thus requiring you to recreate the column arrays from scratch for a long-running list. Alternatively, you could start a new list every year.

```<code>C_Wknd  =IF(TEXT(WEEKDAY([Complaint Created On]),"ddd")="Mon",11,13)

C_NYDay =IF(AND([Complaint Created On]<=DATE(2009,1,1),([Complaint Created On])+C_Wknd>=DATE(2009,1,1)),"1","0")

C_MLKDay    =IF(AND([Complaint Created On]<=DATE(2009,1,19),([Complaint Created On])+C_Wknd>=DATE(2009,1,19)),"1","0")

C_MemDay    =IF(AND([Complaint Created On]<=DATE(2009,5,25),([Complaint Created On])+C_Wknd>=DATE(2009,5,25)),"1","0")

C_PresDay   =IF(AND([Complaint Created On]<=DATE(2009,2,16),([Complaint Created On])+C_Wknd>=DATE(2009,2,16)),"1","0")

C_IndDay    =IF(AND([Complaint Created On]<=DATE(2009,7,4),([Complaint Created On])+C_Wknd>=DATE(2009,7,4)),"1","0")

C_LabDay    =IF(AND([Complaint Created On]<=DATE(2009,9,7),([Complaint Created On])+C_Wknd>=DATE(2009,9,7)),"1","0")

C_ColDay    =IF(AND([Complaint Created On]<=DATE(2009,10,12),([Complaint Created On])+C_Wknd>=DATE(2009,10,12)),"1","0")

C_VetDay    =IF(AND([Complaint Created On]<=DATE(2009,11,11),([Complaint Created On])+C_Wknd>=DATE(2009,11,11)),"1","0")

C_ThxDay    =IF(AND([Complaint Created On]<=DATE(2009,11,26),([Complaint Created On])+C_Wknd>=DATE(2009,11,26)),"1","0")

C_XmsDay    =IF(AND([Complaint Created On]<=DATE(2009,12,25),([Complaint Created On])+C_Wknd>=DATE(2009,12,25)),"1","0")

C_GrossDte  =[Complaint Created On]+C_Wknd+C_NYDay+C_MLKDay+C_MemDay+C_PresDay+C_IndDay+C_LabDay+C_ColDay+C_VetDay+C_ThxDay+C_XmsDay

C_EndSat    =IF(TEXT(WEEKDAY(C_GrossDte),"ddd")="Sat",2,0)

C_EndSun    =IF(TEXT(WEEKDAY(C_GrossDte),"ddd")="Sun",1,0)

Resolution Due  =C_GrossDte+C_EndSat+C_EndSun
</code>```

OwnerDisplayName: MrChrister

ContentLicense: CC BY-SA 2.5

Body:
In SharePoint MOSS 2007, I have created a custom content type that I will be applying to a document library.  One of the required fields is "Incoming Date" and another is the "Due Date".

The Due Date is always 10 working days from the Incoming Date.  The Incoming Date is when the mail room received the letter, not necessarily when the document is posted to the library.

From here:  http://msdn.microsoft.com/en-us/library/bb862071.aspx

=DATE(YEAR([Incoming Date]),MONTH([Incoming Date]),DAY([Incoming Date])+10)

adds 10 days, but how can I add 10 working days?  I don't have the luxury of VS.NET either per the governance plan of our sharepoint rollout.

Assume a human is responsible for the data entry, but I would like to make it easier for them.

LastEditorDisplayName: Nathan DeWitt

Body:
I believe I've figured out a fairly bullet-proof method for calculating a 10 business day deadline that accounts for holidays and weekends. 1) Calculate whether the 2 week period is a Monday, and if so, add only 11 days (assuming the start day counts as Day1 of your 10-day period). Otherwise, you add 13 to account for the 10 working days plus two weekends (remember, the start date already counts as Day1; your variables would be 12 and 14 if you did NOT count the start date as Day1). 2) Create a unique calculated column for every holiday and return a value of 1 if the holiday falls in the range. 3) Determine your "gross date" by adding values (weekends and holidays) to your start date. 4) Determine whether your gross date falls on a Saturday or Sunday, and if so, return the appropriate number of days to push off until Monday. 5) Add all the weekend, holiday, and added Sat and Sun values to your start date, which gives you your due date.

NOTE: The only challenges I see here is if a holiday pushes the due date into the weekend, which then pushes the due date to a Monday that happens to be yet another holiday. This didn't happen in my holiday schedule, but it might in yours. In addition, you'll need to keep adding new holidays every year, thus requiring you to recreate the column arrays from scratch for a long-running list. Alternatively, you could start a new list every year.

C_Wknd  =IF(TEXT(WEEKDAY([Complaint Created On]),"ddd")="Mon",11,13)

C_NYDay =IF(AND([Complaint Created On]<=DATE(2009,1,1),([Complaint Created On])+C_Wknd>=DATE(2009,1,1)),"1","0")

C_MLKDay    =IF(AND([Complaint Created On]<=DATE(2009,1,19),([Complaint Created On])+C_Wknd>=DATE(2009,1,19)),"1","0")

C_MemDay    =IF(AND([Complaint Created On]<=DATE(2009,5,25),([Complaint Created On])+C_Wknd>=DATE(2009,5,25)),"1","0")

C_PresDay   =IF(AND([Complaint Created On]<=DATE(2009,2,16),([Complaint Created On])+C_Wknd>=DATE(2009,2,16)),"1","0")

C_IndDay    =IF(AND([Complaint Created On]<=DATE(2009,7,4),([Complaint Created On])+C_Wknd>=DATE(2009,7,4)),"1","0")

C_LabDay    =IF(AND([Complaint Created On]<=DATE(2009,9,7),([Complaint Created On])+C_Wknd>=DATE(2009,9,7)),"1","0")

C_ColDay    =IF(AND([Complaint Created On]<=DATE(2009,10,12),([Complaint Created On])+C_Wknd>=DATE(2009,10,12)),"1","0")

C_VetDay    =IF(AND([Complaint Created On]<=DATE(2009,11,11),([Complaint Created On])+C_Wknd>=DATE(2009,11,11)),"1","0")

C_ThxDay    =IF(AND([Complaint Created On]<=DATE(2009,11,26),([Complaint Created On])+C_Wknd>=DATE(2009,11,26)),"1","0")

C_XmsDay    =IF(AND([Complaint Created On]<=DATE(2009,12,25),([Complaint Created On])+C_Wknd>=DATE(2009,12,25)),"1","0")

C_GrossDte  =[Complaint Created On]+C_Wknd+C_NYDay+C_MLKDay+C_MemDay+C_PresDay+C_IndDay+C_LabDay+C_ColDay+C_VetDay+C_ThxDay+C_XmsDay

C_EndSat    =IF(TEXT(WEEKDAY(C_GrossDte),"ddd")="Sat",2,0)

C_EndSun    =IF(TEXT(WEEKDAY(C_GrossDte),"ddd")="Sun",1,0)

Resolution Due  =C_GrossDte+C_EndSat+C_EndSun

OwnerDisplayName: Bloggermark

LastEditorDisplayName: Jeff Atwood


问:
Unknown NSDate format
I have the following string to convert to NSDate:

2011-04-27 20:50:09.000002.

I have the following code for the dateformatter:

```<code>  [inputFormatter setDateFormat:@"YYYY-mm-dd HH:mm:ss"];
</code>```

but I'm unsure of what to put after the seconds.

Keep in mind, I have multiple of these strings, with different numbers at the back.

答:
Date format strings in OS 10.6 (and, I believe, in iOS4+) are based on the Unicode spec TR35-10 : have a look at their date formatting strings.

What you need in this case is fractional seconds: symbol S. Something like...

```<code>[inputFormatter setDateFormat:@"YYYY-mm-dd HH:mm:ss.SSSSSS"];
</code>```

Title: Unknown NSDate format

Body:
I have the following string to convert to NSDate:

2011-04-27 20:50:09.000002.

I have the following code for the dateformatter:

  [inputFormatter setDateFormat:@"YYYY-mm-dd HH:mm:ss"];

but I'm unsure of what to put after the seconds.

Keep in mind, I have multiple of these strings, with different numbers at the back.

Body:
Date format strings in OS 10.6 (and, I believe, in iOS4+) are based on the Unicode spec TR35-10 : have a look at their date formatting strings.

What you need in this case is fractional seconds: symbol S. Something like...

[inputFormatter setDateFormat:@"YYYY-mm-dd HH:mm:ss.SSSSSS"];


问:
Passing instance of a subclass as argument to other subclass
I am learning inheritance in python using you tube tutorial and I do not understand one concept:
I have made a class employee, subclass developer and manager.

```<code>class Employee:
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = first + '.' + last + '@gmail.com'
def fullname(self):
fullname = self.first + ' ' + self.last
return print(fullname)

class Developer(Employee):
def __init__(self,first, last, pay, prog_lang):
super().__init__(first,last,pay)
self.prog_lang = prog_lang

class Manager(Employee):
def __init__(self,first, last, pay, employees=None):
super().__init__(first, last, pay)
if employees is None:
self.employees=[]
else:
self.employees = employees
def add_employee(self, emp):
if emp not in self.employees:
self.employees.append(emp)
def remove_employee(self,emp):
if emp in self.employees:
self.employees.remove(emp)

dev1 = Developer('corey','Schafer',8000,'Python')
mngr1 = Manager('kay','sean',9000,[dev1])
</code>```

Now my confusion is, how are we able to give instance of a subclass as parameter to instance of other subclass? why [dev1] is returning name Corey Schafer? Corey Schafer is the value of fullname() when called....How instance dev1 is picking that up?
Could you please explain me?

答:
So when you're calling the constructor for Developer (create a new instance) the __init__(self,first, last, pay, prog_lang) function is called implicitly.

If we take a look at the constructor:

def __init__(self,first, last, pay, prog_lang):
    super().__init__(first,last,pay)
    self.prog_lang = prog_lang
```

<p>we can see that the constructor of the super class is called on the second line. This in turn sets the member variables for the instance which are later referred to when the full name is constructed:</p>

<pre class="lang-python prettyprint-override"><code>def fullname(self):
    fullname = self.first + ' ' + self.last
    return print(fullname)
</code>```

More broadly the language keeps track of which variables are attached to which class and python specifically gives the programmer pretty big freedom when it comes to scope and types. If you wanna read more on this topic i would recommend W3C's python tutorial and more specifically Type safety and Inheritance

Body:
I am learning inheritance in python using you tube tutorial and I do not understand one concept:
I have made a class employee, subclass developer and manager.

class Employee:
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = first + '.' + last + '@gmail.com'
def fullname(self):
fullname = self.first + ' ' + self.last
return print(fullname)

class Developer(Employee):
def __init__(self,first, last, pay, prog_lang):
super().__init__(first,last,pay)
self.prog_lang = prog_lang

class Manager(Employee):
def __init__(self,first, last, pay, employees=None):
super().__init__(first, last, pay)
if employees is None:
self.employees=[]
else:
self.employees = employees
def add_employee(self, emp):
if emp not in self.employees:
self.employees.append(emp)
def remove_employee(self,emp):
if emp in self.employees:
self.employees.remove(emp)

dev1 = Developer('corey','Schafer',8000,'Python')
mngr1 = Manager('kay','sean',9000,[dev1])

Now my confusion is, how are we able to give instance of a subclass as parameter to instance of other subclass? why [dev1] is returning name Corey Schafer? Corey Schafer is the value of fullname() when called....How instance dev1 is picking that up?
Could you please explain me?

Body:
So when you're calling the constructor for Developer (create a new instance) the __init__(self,first, last, pay, prog_lang) function is called implicitly.

If we take a look at the constructor:

def __init__(self,first, last, pay, prog_lang):
    super().__init__(first,last,pay)
    self.prog_lang = prog_lang

we can see that the constructor of the super class is called on the second line. This in turn sets the member variables for the instance which are later referred to when the full name is constructed:

def fullname(self):
    fullname = self.first + ' ' + self.last
    return print(fullname)

More broadly the language keeps track of which variables are attached to which class and python specifically gives the programmer pretty big freedom when it comes to scope and types. If you wanna read more on this topic i would recommend W3C's python tutorial and more specifically Type safety and Inheritance


问:
WinDbg extension not recognizing command
I am trying to write a WinDbg extension command and running into some problems. I started with this project and tried to modify it to supply a custom command in the debugger.

However when I run TestCommand I get the following error.

The command was: !TestCommand this is a test0:000> !TestCommand this is a test
No export TestCommand found

The full code I have is below. I have attempted adding the [Export] modifier to the TestCommand function however this has not rectified the situation. How would I get WinDbg to recognize the command?

Full extension code:

```<code>using System.ComponentModel.Composition;
using DbgX.Interfaces;
using DbgX.Interfaces.Enums;
using DbgX.Interfaces.Listeners;
using DbgX.Interfaces.Services;
using DbgX.Util;

namespace WinDbgExt.LoadSos
{
    [Export(typeof(IDbgCommandExecutionListener))]
    [Export(typeof(IDbgStartupListener))]

    public class ToggleSosViewModel : IDbgCommandExecutionListener, IDbgStartupListener
    {
        private bool _engineLoaded;

        [Import]
        private IDbgConsole _console;

        [Import]
        private IDbgEngineState _engineState;

        public void OnCommandExecuted(string command)
        {
            if (command.StartsWith("!TestCommand"))
            {
                TstCommand(command);

            }
        }

        public void TestCommand(string command)
        {
            _console.PrintTextToConsole("The command was: " + command);
        }

        public void OnStartup()
        {

        }
    }
}
</code>```

As a bonus question I need to get a handle for the process that WinDbg is attached to. Is there a simple way to add that to the above extension?

答:
I think there's a misunderstanding. OnCommandExecuted() is an event listener which invoked when you entered a command in WinDbg. The given UI extension you have compiled will first be notified about the command, then WinDbg will try and actually run the command. Since the command does not exist, it will respond with the same error message that you get when no UI extension is loaded.

If I understand correctly what you want, then you're trying to implement a WinDbg extension (not a UI extension) that implements the command !TestCommand. That's usually a totally different approach.

In the given source code, you find a "regular" WinDbg extension in the WinDbgScriptRunner.x64 and WinDbgScriptRunner.x86 projects. There you can see that you need

```<code>[DllExport("compileandrun")]
</code>```

on a method to make a method a !-command.

But, unfortunately, they fail with an exception:

```<code>0:000> !compileandrun
e0434352 Exception in C:\Users\T\AppData\Local\dbg\UIExtensions\CsharpScriptRunner-x64\WindbgScriptRunner.dll.compileandrun debugger extension.
      PC: 00007ff9`c183a799  VA: 00000000`00000000  R/W: 8013150c  Parameter: 00000000`00000000
</code>```

I've added that as issue #4 on their Github repository.

So, yes, I understand that implementing extensions is a bit tricky if you want to do it in C#. So, how could you misuse the given functionality and implement commands?

The only command which has no side effects is probably the comment command:

```<code>* this is a comment
</code>```

You could repurpose this to

```<code>*!TestCommand
</code>```

and the code for that is

```<code>if (command.StartsWith("*!TestCommand"))
{
  _console.PrintTextToConsole("My command was invoked! Yay!\r\n");
  return;
}
</code>```

The output is also a bit awkward, since your code is executed before the actual command is written into the window:

```<code>(4b34.1954): Break instruction exception - code 80000003 (first chance)
ntdll!LdrpDoDebuggerBreak+0x30:
00007ff9`c3dd119c cc              int     3
My command was invoked! Yay!
0:000> *!TestCommand
</code>```

I'm not familiar with writing UI extensions for WinDbg Preview, so I'm not sure how far you can get with this approach and whether you can fix the order of output.

Body:
I am trying to write a WinDbg extension command and running into some problems. I started with this project and tried to modify it to supply a custom command in the debugger.

However when I run TestCommand I get the following error.

The command was: !TestCommand this is a test0:000> !TestCommand this is a test
No export TestCommand found

The full code I have is below. I have attempted adding the [Export] modifier to the TestCommand function however this has not rectified the situation. How would I get WinDbg to recognize the command?

Full extension code:

using System.ComponentModel.Composition;
using DbgX.Interfaces;
using DbgX.Interfaces.Enums;
using DbgX.Interfaces.Listeners;
using DbgX.Interfaces.Services;
using DbgX.Util;

namespace WinDbgExt.LoadSos
{
    [Export(typeof(IDbgCommandExecutionListener))]
    [Export(typeof(IDbgStartupListener))]

    public class ToggleSosViewModel : IDbgCommandExecutionListener, IDbgStartupListener
    {
        private bool _engineLoaded;

        [Import]
        private IDbgConsole _console;

        [Import]
        private IDbgEngineState _engineState;

        public void OnCommandExecuted(string command)
        {
            if (command.StartsWith("!TestCommand"))
            {
                TstCommand(command);

            }
        }

        public void TestCommand(string command)
        {
            _console.PrintTextToConsole("The command was: " + command);
        }

        public void OnStartup()
        {

        }
    }
}

As a bonus question I need to get a handle for the process that WinDbg is attached to. Is there a simple way to add that to the above extension?

Body:
I think there's a misunderstanding. OnCommandExecuted() is an event listener which invoked when you entered a command in WinDbg. The given UI extension you have compiled will first be notified about the command, then WinDbg will try and actually run the command. Since the command does not exist, it will respond with the same error message that you get when no UI extension is loaded.

If I understand correctly what you want, then you're trying to implement a WinDbg extension (not a UI extension) that implements the command !TestCommand. That's usually a totally different approach.

In the given source code, you find a "regular" WinDbg extension in the WinDbgScriptRunner.x64 and WinDbgScriptRunner.x86 projects. There you can see that you need

[DllExport("compileandrun")]

on a method to make a method a !-command.

But, unfortunately, they fail with an exception:

0:000> !compileandrun
e0434352 Exception in C:\Users\T\AppData\Local\dbg\UIExtensions\CsharpScriptRunner-x64\WindbgScriptRunner.dll.compileandrun debugger extension.
      PC: 00007ff9`c183a799  VA: 00000000`00000000  R/W: 8013150c  Parameter: 00000000`00000000

I've added that as issue #4 on their Github repository.

So, yes, I understand that implementing extensions is a bit tricky if you want to do it in C#. So, how could you misuse the given functionality and implement commands?

The only command which has no side effects is probably the comment command:

* this is a comment

You could repurpose this to

*!TestCommand

and the code for that is

if (command.StartsWith("*!TestCommand"))
{
  _console.PrintTextToConsole("My command was invoked! Yay!\r\n");
  return;
}

The output is also a bit awkward, since your code is executed before the actual command is written into the window:

(4b34.1954): Break instruction exception - code 80000003 (first chance)
ntdll!LdrpDoDebuggerBreak+0x30:
00007ff9`c3dd119c cc              int     3
My command was invoked! Yay!
0:000> *!TestCommand

I'm not familiar with writing UI extensions for WinDbg Preview, so I'm not sure how far you can get with this approach and whether you can fix the order of output.


问:
R apply 2 differents functions in summarise_at
I have following modified mtcars:
mtcars2 <- mtcars ; mtcars2[1,2] <- mtcars2[1,2] <- NA ; mtcars2 <- mtcars2[,c("vs","cyl", "disp")]
I want to apply group_by "vs" by summing the first column without NA and apply length to the second column of mtcars2.

I try this:

mtcars3 <- mtcars2 %>% group_by(vs) %>% summarise_at(vars(names(mtcars2[-1])), list( Total = sum, n = length), na.rm=T)

it says that the parameter na.rm is also applying to length, which cause the problem.

the result I want is like :

```<code>mtcars3 <- mtcars3 <- mtcars2 %>% group_by(vs) %>%
                      summarise_at(vars(names(mtcars2[-1])), list( Total = sum, n = length))
mtcars3 [1,2] <- sum(mtcars2$cyl, na.rm = T)
res <- mtcars3 %>% mutate(n = cyl_n)%>% select(-disp_n, -cyl_n)
res

</code>```

do you have an idea?

Thanks!

答:
We can also use data.table

```<code>library(data.table)
as.data.table(mtcars2)[, c(lapply(.SD, sum, na.rm = TRUE), .(n = .N)) , vs]
</code>```

Body:
I have following modified mtcars:
mtcars2 <- mtcars ; mtcars2[1,2] <- mtcars2[1,2] <- NA ; mtcars2 <- mtcars2[,c("vs","cyl", "disp")]
I want to apply group_by "vs" by summing the first column without NA and apply length to the second column of mtcars2.

I try this:

mtcars3 <- mtcars2 %>% group_by(vs) %>% summarise_at(vars(names(mtcars2[-1])), list( Total = sum, n = length), na.rm=T)

it says that the parameter na.rm is also applying to length, which cause the problem.

the result I want is like :

mtcars3 <- mtcars3 <- mtcars2 %>% group_by(vs) %>%
                      summarise_at(vars(names(mtcars2[-1])), list( Total = sum, n = length))
mtcars3 [1,2] <- sum(mtcars2$cyl, na.rm = T)
res <- mtcars3 %>% mutate(n = cyl_n)%>% select(-disp_n, -cyl_n)
res

do you have an idea?

Thanks!

Body:
We can also use data.table

library(data.table)
as.data.table(mtcars2)[, c(lapply(.SD, sum, na.rm = TRUE), .(n = .N)) , vs]


问:
Web Application to know database update
My web application (ASP.NET 4) connects to a database (SQL Server 2005). For every new row inserted in a certain table, I want the web app can do some process (like send  an email to me with new data).

How do I implement the system? My first though is having web app check the table SN column, and have a variable lastProcessedSN. And keep polling every minute. Is it possible to have DB notify web app when there's a new row being inserted?

Please advise, thanks.

EDIT:
Sending an email is just an example, not the exact thing I want to do. So this question is focusing on how to implement the trigger on MSSQL table insert to call my program.

答:
You could modify the insert script or stored procedure to send yourself an email. If you're writing with stored procedures in SQL you can send email from there: Send Email from SQL

Otherwise if you're using EF/NHibernate/Linq2SQL you could write C# code to email yourself

Title: Web Application to know database update


问:
get userPackagerOpts.sourceExts is not iterable while runing the expo app
I am getting the following error while runing the expo app.</p>

```<code>   $ expo-cli start --tunnel
    [00:24:51] Starting project at C:\Users\DEMO\Desktop\worldsweets
    [00:24:51] Expo DevTools is running at http://localhost:19002
    [00:24:59] userPackagerOpts.sourceExts is not iterable
    [00:24:59] TypeError: userPackagerOpts.sourceExts is not iterable
        at startReactNativeServerAsync (C:\@expo\xdl@57.9.12\src\Project.ts:1788:80)
        at Object.startAsync (C:\@expo\xdl@57.9.12\src\Project.ts:2407:5)
        at action (C:\Users\DEMO\AppData\Roaming\npm\node_modules\expo-cli\src\commands\start.ts:181:3)
        at C:\Users\DEMO\AppData\Roaming\npm\node_modules\expo-cli\src\commands\start.ts:354:16
        at Command.<anonymous> (C:\Users\DEMO\AppData\Roaming\npm\node_modules\expo-cli\src\exp.ts:80:7)
</code>```

答:
Update the expo-cli version to 3.17.10.

This new version seems to fix this issue.

```<code>npm install expo-cli@3.17.10 --save
</code>```

Related question: https://forums.expo.io/t/userpackageropts-sourceexts-is-not-iterable/35271/4

Body:
I am getting the following error while runing the expo app.

   $ expo-cli start --tunnel
    [00:24:51] Starting project at C:\Users\DEMO\Desktop\worldsweets
    [00:24:51] Expo DevTools is running at http://localhost:19002
    [00:24:59] userPackagerOpts.sourceExts is not iterable
    [00:24:59] TypeError: userPackagerOpts.sourceExts is not iterable
        at startReactNativeServerAsync (C:\@expo\xdl@57.9.12\src\Project.ts:1788:80)
        at Object.startAsync (C:\@expo\xdl@57.9.12\src\Project.ts:2407:5)
        at action (C:\Users\DEMO\AppData\Roaming\npm\node_modules\expo-cli\src\commands\start.ts:181:3)
        at C:\Users\DEMO\AppData\Roaming\npm\node_modules\expo-cli\src\commands\start.ts:354:16
        at Command.<anonymous> (C:\Users\DEMO\AppData\Roaming\npm\node_modules\expo-cli\src\exp.ts:80:7)

Body:
Update the expo-cli version to 3.17.10.

This new version seems to fix this issue.

npm install expo-cli@3.17.10 --save

Related question: https://forums.expo.io/t/userpackageropts-sourceexts-is-not-iterable/35271/4


问:
python 3 open excel files in a directory
I'm new to programming and I'm trying to work on a script that will open an excel file in a folder. update the workbook with openpyxl. Save the file.  Open the next file in the directory and do the same.

I'm trying this without success:

```<code>import os.glob
folder_path = 'G:\\My Drive\\Reports\\'
for filename in glob.glob(os,path.join(folder_path, '*.xlsm')):
    with open(filename, 'r' as f:
        text = f.read()
        print (filename)
        print (len(text))
from openpyxl import Workbook
from openpyxl.styles import NamedStyle, Font, Border, Side, Alignment
wb=Workbook()
ws=wb.active
Update cells

wb.save(filename)
</code>```

答:
You have wrong indentations. You have to do it inside for-loop.

And you have to use function from module openpyxl to open and read Excel file.

Functions open(), read() are useful to read text files (or similar) or to read raw data but Excel uses more complex files (ie. it can use .zip file with many  .xml files) and you need module like openpyxl to read it.

```<code>import os
import glob
import openpyxl

folder_path = 'G:\\My Drive\\Reports\\'

for filename in glob.glob(os.path.join(folder_path, '*.xlsm')):

    print(filename)

    wb = openpyxl.open(filename)
    ws = wb.active

    #Update cells
    print('old value:', ws['A1'].value)
    ws['A1'] = 'Hello World'
    print('new value:', ws['A1'].value)

    wb.save(filename)
</code>```

BTW: always put all imports at the beginning to make code more readable.

See also: PEP 8 -- Style Guide for Python Code

Body:
I'm new to programming and I'm trying to work on a script that will open an excel file in a folder. update the workbook with openpyxl. Save the file.  Open the next file in the directory and do the same.

I'm trying this without success:

import os.glob
folder_path = 'G:\\My Drive\\Reports\\'
for filename in glob.glob(os,path.join(folder_path, '*.xlsm')):
    with open(filename, 'r' as f:
        text = f.read()
        print (filename)
        print (len(text))
from openpyxl import Workbook
from openpyxl.styles import NamedStyle, Font, Border, Side, Alignment
wb=Workbook()
ws=wb.active
Update cells

wb.save(filename)

Body:
You have wrong indentations. You have to do it inside for-loop.

And you have to use function from module openpyxl to open and read Excel file.

Functions open(), read() are useful to read text files (or similar) or to read raw data but Excel uses more complex files (ie. it can use .zip file with many  .xml files) and you need module like openpyxl to read it.

import os
import glob
import openpyxl

folder_path = 'G:\\My Drive\\Reports\\'

for filename in glob.glob(os.path.join(folder_path, '*.xlsm')):

    print(filename)

    wb = openpyxl.open(filename)
    ws = wb.active

    #Update cells
    print('old value:', ws['A1'].value)
    ws['A1'] = 'Hello World'
    print('new value:', ws['A1'].value)

    wb.save(filename)

BTW: always put all imports at the beginning to make code more readable.

See also: PEP 8 -- Style Guide for Python Code


问:
How can I count the documents from a firestore query in swift?
The answer must be staring at me but I can't see it. I am trying to query firestore and to get the number of documents it identifies so that I may feed that into my TableView (number of rows) function. Somehow the counter works inside the for loop and I would expect the variable to hold that incremented value but it reverts back to zero when I pass it back. Is it a scope issue ? What am I missing ? here is my code:</p>

```<code>func runQueryForNumberOfGames() -> Int {
    var counter = 0
    // query the games for the user who is logged into app
    let currentUid = Auth.auth().currentUser!.uid

    db.collection("games").whereField("userTrackingGame", isEqualTo: currentUid).getDocuments { (querySnapshot, err) in
               if let err = err {
                print("error getting documents: \(err)")
                return
               }
               else {

                    for document
                        in querySnapshot!.documents {
                        print(document)
                        counter += 1
                        print("the counter is: \(counter)")
                    }
                }

    }
    print("the counter outside of the for loop is \(counter)")
    return (counter)
}
</code>```

答:
Its async function so you need to return completion handler

```<code>func runQueryForNumberOfGames(completion: @escaping (Int?)-> Void) {
    var counter = 0
    // query the games for the user who is logged into app
    let currentUid = Auth.auth().currentUser!.uid

    db.collection("games").whereField("userTrackingGame", isEqualTo: currentUid).getDocuments { (querySnapshot, err) in
               if let err = err {
                print("error getting documents: \(err)")
                completion(nil)
                return
               }
               else {

                    for document
                        in querySnapshot!.documents {
                        print(document)
                        counter += 1
                        print("the counter is: \(counter)")
                    }

                completion(counter)
                }

    }

}
</code>```

How to use

```<code>runQueryForNumberOfGames {[weak self] (counter) in
    if let count = counter  {
        print(count)
    }
}
</code>```

Body:
The answer must be staring at me but I can't see it. I am trying to query firestore and to get the number of documents it identifies so that I may feed that into my TableView (number of rows) function. Somehow the counter works inside the for loop and I would expect the variable to hold that incremented value but it reverts back to zero when I pass it back. Is it a scope issue ? What am I missing ? here is my code:

func runQueryForNumberOfGames() -> Int {
    var counter = 0
    // query the games for the user who is logged into app
    let currentUid = Auth.auth().currentUser!.uid

    db.collection("games").whereField("userTrackingGame", isEqualTo: currentUid).getDocuments { (querySnapshot, err) in
               if let err = err {
                print("error getting documents: \(err)")
                return
               }
               else {

                    for document
                        in querySnapshot!.documents {
                        print(document)
                        counter += 1
                        print("the counter is: \(counter)")
                    }
                }

    }
    print("the counter outside of the for loop is \(counter)")
    return (counter)
}

Body:
Its async function so you need to return completion handler

func runQueryForNumberOfGames(completion: @escaping (Int?)-> Void) {
    var counter = 0
    // query the games for the user who is logged into app
    let currentUid = Auth.auth().currentUser!.uid

    db.collection("games").whereField("userTrackingGame", isEqualTo: currentUid).getDocuments { (querySnapshot, err) in
               if let err = err {
                print("error getting documents: \(err)")
                completion(nil)
                return
               }
               else {

                    for document
                        in querySnapshot!.documents {
                        print(document)
                        counter += 1
                        print("the counter is: \(counter)")
                    }

                completion(counter)
                }

    }

}

How to use

runQueryForNumberOfGames {[weak self] (counter) in
    if let count = counter  {
        print(count)
    }
}