问:
How do i remove .0 from the result if the resultant number is a full number in a calculator
I am making an android calculator in android studio. But, in my calculator when the result is a full number, the number appears with decimal 0.
For example, if i add 9 and 11 the result is appearing as 20.0

So, how do i remove .0 from the result for a full number(ex:- 10,24).

This is my MainActivity.java

```<code> package com.example.calculator;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.faendir.rhino_android.RhinoAndroidHelper;

import org.mozilla.javascript.Context;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.ast.Scope;

public class MainActivity extends AppCompatActivity {

    Button btn0,btn1,btn2,btn3,btn4,btn5,btn6,btn7,btn8,btn9,btnPercent,btnPlus,btnMinus,btnMultiply,btnDivision,btnEqual,btnClear,btnDot,btnBracket,btnBackspace;
    TextView tvInput,tvOutput;
    String process;
    boolean checkBracket = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btn0 = findViewById(R.id.btn0);
        btn1 = findViewById(R.id.btn1);
        btn2 = findViewById(R.id.btn2);
        btn3 = findViewById(R.id.btn3);
        btn4 = findViewById(R.id.btn4);
        btn5 = findViewById(R.id.btn5);
        btn6 = findViewById(R.id.btn6);
        btn7 = findViewById(R.id.btn7);
        btn8 = findViewById(R.id.btn8);
        btn9 = findViewById(R.id.btn9);

        btnPlus = findViewById(R.id.btnPlus);
        btnMinus = findViewById(R.id.btnMinus);
        btnDivision = findViewById(R.id.btnDivision);
        btnMultiply = findViewById(R.id.btnMultiply);

        btnEqual = findViewById(R.id.btnEqual);

        btnClear = findViewById(R.id.btnClear);
        btnDot = findViewById(R.id.btnDot);
        btnPercent = findViewById(R.id.btnPercent);
        btnBracket = findViewById(R.id.btnBracket);
        btnBackspace = findViewById(R.id.btnBackspace);

        tvInput = findViewById(R.id.tvInput);
        tvOutput = findViewById(R.id.tvOutput);

        btnClear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tvInput.setText("");
                tvOutput.setText("");
            }
        });

        btn0.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                process = tvInput.getText().toString();
                tvInput.setText(process + "0");
            }
        });

        btn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                process = tvInput.getText().toString();
                tvInput.setText(process + "1");
            }
        });

        btn2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                process = tvInput.getText().toString();
                tvInput.setText(process + "2");
            }
        });

        btn3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                process = tvInput.getText().toString();
                tvInput.setText(process + "3");
            }
        });

        btn4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                process = tvInput.getText().toString();
                tvInput.setText(process + "4");
            }
        });

        btn5.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                process = tvInput.getText().toString();
                tvInput.setText(process + "5");
            }
        });

        btn6.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                process = tvInput.getText().toString();
                tvInput.setText(process + "6");
            }
        });

        btn6.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                process = tvInput.getText().toString();
                tvInput.setText(process + "6");
            }
        });

        btn7.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                process = tvInput.getText().toString();
                tvInput.setText(process + "7");
            }
        });

        btn8.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                process = tvInput.getText().toString();
                tvInput.setText(process + "8");
            }
        });

        btn9.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                process = tvInput.getText().toString();
                tvInput.setText(process + "9");
            }
        });

        btnPlus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                process = tvInput.getText().toString();
                tvInput.setText(process + "+");
            }
        });

        btnMinus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                process = tvInput.getText().toString();
                tvInput.setText(process + "-");
            }
        });

        btnMultiply.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                process = tvInput.getText().toString();
                tvInput.setText(process + "×");
            }
        });

        btnDivision.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                process = tvInput.getText().toString();
                tvInput.setText(process + "÷");
            }
        });

        btnDot.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                process = tvInput.getText().toString();
                tvInput.setText(process + ".");
            }
        });

        btnPercent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                process = tvInput.getText().toString();
                tvInput.setText(process + "%");
            }
        });

        btnBracket.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (checkBracket){
                    process = tvInput.getText().toString();
                    tvInput.setText(process + ")");
                    checkBracket = false;
                }else{
                    process = tvInput.getText().toString();
                    tvInput.setText(process + "(");
                    checkBracket = true;
                }

            }
        });

        btnBackspace.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                String str=tvInput.getText().toString();
                if (str.length() >=1 ) {
                    str = str.substring(0, str.length() - 1);
                    tvInput.setText(str);
                } else if (str.length() <=1 ) {
                    tvInput.setText("0");
                }
            }
        });

        btnEqual.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                process = tvInput.getText().toString();

                process = process.replaceAll("×","*");
                process = process.replaceAll("%","/100");
                process = process.replaceAll("÷","/");

                Context rhino = Context.enter();

                rhino.setOptimizationLevel(-1);

                String finalResult = "";

                try {
                    Scriptable scriptable = rhino.initStandardObjects();
                    finalResult = rhino.evaluateString(scriptable,process,"javascript",1,null).toString();
                }catch (Exception e){
                    finalResult="0";
                }

                tvOutput.setText(finalResult);
            }
        });

    }
}
</code>```

Any help would be appreciated.

Thank you.

答:
There could be other solutions to your problem. I am proposing this one.
Put an if() condition to check if the answer is whole number or not.</p>

```<code>if(result == (int)result){
    DecimalFormat df = new DecimalFormat("0")
    return df.format(result);
}
return result;
</code>```

Body:
I am making an android calculator in android studio. But, in my calculator when the result is a full number, the number appears with decimal 0.
For example, if i add 9 and 11 the result is appearing as 20.0

So, how do i remove .0 from the result for a full number(ex:- 10,24).

This is my MainActivity.java

 package com.example.calculator;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.faendir.rhino_android.RhinoAndroidHelper;

import org.mozilla.javascript.Context;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.ast.Scope;

public class MainActivity extends AppCompatActivity {

    Button btn0,btn1,btn2,btn3,btn4,btn5,btn6,btn7,btn8,btn9,btnPercent,btnPlus,btnMinus,btnMultiply,btnDivision,btnEqual,btnClear,btnDot,btnBracket,btnBackspace;
    TextView tvInput,tvOutput;
    String process;
    boolean checkBracket = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btn0 = findViewById(R.id.btn0);
        btn1 = findViewById(R.id.btn1);
        btn2 = findViewById(R.id.btn2);
        btn3 = findViewById(R.id.btn3);
        btn4 = findViewById(R.id.btn4);
        btn5 = findViewById(R.id.btn5);
        btn6 = findViewById(R.id.btn6);
        btn7 = findViewById(R.id.btn7);
        btn8 = findViewById(R.id.btn8);
        btn9 = findViewById(R.id.btn9);

        btnPlus = findViewById(R.id.btnPlus);
        btnMinus = findViewById(R.id.btnMinus);
        btnDivision = findViewById(R.id.btnDivision);
        btnMultiply = findViewById(R.id.btnMultiply);

        btnEqual = findViewById(R.id.btnEqual);

        btnClear = findViewById(R.id.btnClear);
        btnDot = findViewById(R.id.btnDot);
        btnPercent = findViewById(R.id.btnPercent);
        btnBracket = findViewById(R.id.btnBracket);
        btnBackspace = findViewById(R.id.btnBackspace);

        tvInput = findViewById(R.id.tvInput);
        tvOutput = findViewById(R.id.tvOutput);

        btnClear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tvInput.setText("");
                tvOutput.setText("");
            }
        });

        btn0.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                process = tvInput.getText().toString();
                tvInput.setText(process + "0");
            }
        });

        btn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                process = tvInput.getText().toString();
                tvInput.setText(process + "1");
            }
        });

        btn2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                process = tvInput.getText().toString();
                tvInput.setText(process + "2");
            }
        });

        btn3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                process = tvInput.getText().toString();
                tvInput.setText(process + "3");
            }
        });

        btn4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                process = tvInput.getText().toString();
                tvInput.setText(process + "4");
            }
        });

        btn5.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                process = tvInput.getText().toString();
                tvInput.setText(process + "5");
            }
        });

        btn6.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                process = tvInput.getText().toString();
                tvInput.setText(process + "6");
            }
        });

        btn6.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                process = tvInput.getText().toString();
                tvInput.setText(process + "6");
            }
        });

        btn7.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                process = tvInput.getText().toString();
                tvInput.setText(process + "7");
            }
        });

        btn8.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                process = tvInput.getText().toString();
                tvInput.setText(process + "8");
            }
        });

        btn9.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                process = tvInput.getText().toString();
                tvInput.setText(process + "9");
            }
        });

        btnPlus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                process = tvInput.getText().toString();
                tvInput.setText(process + "+");
            }
        });

        btnMinus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                process = tvInput.getText().toString();
                tvInput.setText(process + "-");
            }
        });

        btnMultiply.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                process = tvInput.getText().toString();
                tvInput.setText(process + "×");
            }
        });

        btnDivision.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                process = tvInput.getText().toString();
                tvInput.setText(process + "÷");
            }
        });

        btnDot.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                process = tvInput.getText().toString();
                tvInput.setText(process + ".");
            }
        });

        btnPercent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                process = tvInput.getText().toString();
                tvInput.setText(process + "%");
            }
        });

        btnBracket.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (checkBracket){
                    process = tvInput.getText().toString();
                    tvInput.setText(process + ")");
                    checkBracket = false;
                }else{
                    process = tvInput.getText().toString();
                    tvInput.setText(process + "(");
                    checkBracket = true;
                }

            }
        });

        btnBackspace.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                String str=tvInput.getText().toString();
                if (str.length() >=1 ) {
                    str = str.substring(0, str.length() - 1);
                    tvInput.setText(str);
                } else if (str.length() <=1 ) {
                    tvInput.setText("0");
                }
            }
        });

        btnEqual.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                process = tvInput.getText().toString();

                process = process.replaceAll("×","*");
                process = process.replaceAll("%","/100");
                process = process.replaceAll("÷","/");

                Context rhino = Context.enter();

                rhino.setOptimizationLevel(-1);

                String finalResult = "";

                try {
                    Scriptable scriptable = rhino.initStandardObjects();
                    finalResult = rhino.evaluateString(scriptable,process,"javascript",1,null).toString();
                }catch (Exception e){
                    finalResult="0";
                }

                tvOutput.setText(finalResult);
            }
        });

    }
}

Any help would be appreciated.

Thank you.

Body:
There could be other solutions to your problem. I am proposing this one.
Put an if() condition to check if the answer is whole number or not.

if(result == (int)result){
    DecimalFormat df = new DecimalFormat("0")
    return df.format(result);
}
return result;


来源: stackexchange

问:
Why does .NET Core DI container not inject ILogger?
I am trying to get logging up and running in my C# console app based on .NET Core 2.1.

I added the following code to my DI declaration:

```<code>var sc = new ServiceCollection();

sc.AddLogging(builder =>
{
    builder.AddFilter("Microsoft", LogLevel.Warning);
    builder.AddFilter("System", LogLevel.Warning);
    builder.AddFilter("Program", LogLevel.Warning);
    builder.AddConsole();
    builder.AddEventLog();
});
</code>```

I am trying to inject the service by using the Interface Microsoft.Extensions.Logging.ILogger in the constructor of the services, but I am getting the following error:

Unhandled Exception: System.InvalidOperationException: Unable to resolve service for type 'Microsoft.Extensions.Logging.ILogger' while attempting to activate 'MyService'.

```<code>    at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateArgumentCallSites(Type serviceType, Type implementationType, CallSiteChain callSiteChain, ParameterInfo[] parameters, Boolean throwIfCallSiteNotFound)
    at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateConstructorCallSite(ResultCache lifetime, Type serviceType, Type implementationType, CallSiteChain callSiteChain)
    at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateExact(ServiceDescriptor descriptor, Type serviceType, CallSiteChain callSiteChain, Int32 slot)
    at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateExact(Type serviceType, CallSiteChain callSiteChain)
    at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateCallSite(Type serviceType, CallSiteChain callSiteChain)
    at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory)
    at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateArgumentCallSites(Type serviceType, Type implementationType, CallSiteChain callSiteChain, ParameterInfo[] parameters, Boolean throwIfCallSiteNotFound)
    at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateConstructorCallSite(ResultCache lifetime, Type serviceType, Type implementationType, CallSiteChain callSiteChain)
    at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateExact(ServiceDescriptor descriptor, Type serviceType, CallSiteChain callSiteChain, Int32 slot)
    at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateEnumerable(Type serviceType, CallSiteChain callSiteChain)
    at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateCallSite(Type serviceType, CallSiteChain callSiteChain)
    at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory)
    at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.CreateServiceAccessor(Type serviceType)
    at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory)
    at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope)
    at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
    at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider)
    at Program.Main(String[] args) in Program.cs:line 27
</code>```

Did I misunderstand something here? Shouldn't the AddLogging method be enough to expose the Service in the DI Container?

答:
In order for MS.DI to be able to do a mapping from ILogger to ILogger<T> where the T becomes the consumer, it must support context-based injection. This means that when building an application using MS.DI, you will have to let your classes depend on ILogger<T>.

There are multiple reasons why MS.DI lacks this feature. I think the two most important reasons are:

MS.DI only implements features that are required for framework components itself. Remember: MS.DI was built and designed especially for the ASP.NET Core framework, its components, and its third-parties. Much less to be a fully fledged DI Container

MS.DI tries to be a lowest common denominator (LCD) where it tries to only support features that all other DI Containers support as well to allow you to replace this built-in container with a more mature, feature-rich DI Container.

I understand your annoyance. It would be great to see MS.DI support context-based injection, because it makes a lot of sense to depend on ILogger instead for your application components, because this makes your code simpler, easier to test, and less error prone.

Unfortunately, because of MS.DI's design and its LCD philosophy, it's unlikely that it ever gets such feature. Every time Microsoft adds behavior, a long and complex discussion is started with maintainers of most DI Containers to see how such feature can be supported in a way that is compatible with all other libraries (I've been parted of many of these discussions myself). This is a daunting task, and already proved to be impossible in some cases.

Instead, it makes sense to select a more mature and feature-rich DI Container that contains such feature, and many other features. For Simple Injector, for instance, we  added integration for injecting ILogger. But there are other DI Containers that allow you to inject ILogger.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to get logging up and running in my C# console app based on .NET Core 2.1.

I added the following code to my DI declaration:

var sc = new ServiceCollection();

sc.AddLogging(builder =>
{
    builder.AddFilter("Microsoft", LogLevel.Warning);
    builder.AddFilter("System", LogLevel.Warning);
    builder.AddFilter("Program", LogLevel.Warning);
    builder.AddConsole();
    builder.AddEventLog();
});

I am trying to inject the service by using the Interface Microsoft.Extensions.Logging.ILogger in the constructor of the services, but I am getting the following error:

Unhandled Exception: System.InvalidOperationException: Unable to resolve service for type 'Microsoft.Extensions.Logging.ILogger' while attempting to activate 'MyService'.

    at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateArgumentCallSites(Type serviceType, Type implementationType, CallSiteChain callSiteChain, ParameterInfo[] parameters, Boolean throwIfCallSiteNotFound)
    at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateConstructorCallSite(ResultCache lifetime, Type serviceType, Type implementationType, CallSiteChain callSiteChain)
    at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateExact(ServiceDescriptor descriptor, Type serviceType, CallSiteChain callSiteChain, Int32 slot)
    at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateExact(Type serviceType, CallSiteChain callSiteChain)
    at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateCallSite(Type serviceType, CallSiteChain callSiteChain)
    at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory)
    at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateArgumentCallSites(Type serviceType, Type implementationType, CallSiteChain callSiteChain, ParameterInfo[] parameters, Boolean throwIfCallSiteNotFound)
    at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateConstructorCallSite(ResultCache lifetime, Type serviceType, Type implementationType, CallSiteChain callSiteChain)
    at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateExact(ServiceDescriptor descriptor, Type serviceType, CallSiteChain callSiteChain, Int32 slot)
    at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateEnumerable(Type serviceType, CallSiteChain callSiteChain)
    at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateCallSite(Type serviceType, CallSiteChain callSiteChain)
    at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory)
    at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.CreateServiceAccessor(Type serviceType)
    at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory)
    at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope)
    at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
    at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider)
    at Program.Main(String[] args) in Program.cs:line 27

Did I misunderstand something here? Shouldn't the AddLogging method be enough to expose the Service in the DI Container?


问:
AttributeError: module 'dateutil.tz' has no attribute 'UTC' on Zappa Deploy
On trying to deploy my AWS Lambda function get this error on my Stacktrace</p>

```<code>(python-dateutil 2.8.1 (/Users/supratik/.local/share/virtualenvs/api_sourcer-sM-JSZy3-/Users/supratik/.pyenv/shims/python/lib/python3.6/site-packages), Requirement.parse('python-dateutil<2.7.0'), {'zappa'})
Calling deploy for stage development..
Oh no! An error occurred! :(

==============

Traceback (most recent call last):
  File "/Users/supratik/.local/share/virtualenvs/api_sourcer-sM-JSZy3-/Users/supratik/.pyenv/shims/python/lib/python3.6/site-packages/zappa/cli.py", line 2778, in handle
    sys.exit(cli.handle())
  File "/Users/supratik/.local/share/virtualenvs/api_sourcer-sM-JSZy3-/Users/supratik/.pyenv/shims/python/lib/python3.6/site-packages/zappa/cli.py", line 512, in handle
    self.dispatch_command(self.command, stage)
  File "/Users/supratik/.local/share/virtualenvs/api_sourcer-sM-JSZy3-/Users/supratik/.pyenv/shims/python/lib/python3.6/site-packages/zappa/cli.py", line 549, in dispatch_command
    self.deploy(self.vargs['zip'])
  File "/Users/supratik/.local/share/virtualenvs/api_sourcer-sM-JSZy3-/Users/supratik/.pyenv/shims/python/lib/python3.6/site-packages/zappa/cli.py", line 709, in deploy
    self.zappa.create_iam_roles()
  File "/Users/supratik/.local/share/virtualenvs/api_sourcer-sM-JSZy3-/Users/supratik/.pyenv/shims/python/lib/python3.6/site-packages/zappa/core.py", line 2557, in create_iam_roles
    role, credentials_arn = self.get_credentials_arn()
  File "/Users/supratik/.local/share/virtualenvs/api_sourcer-sM-JSZy3-/Users/supratik/.pyenv/shims/python/lib/python3.6/site-packages/zappa/core.py", line 2536, in get_credentials_arn
    self.credentials_arn = role.arn
  File "/Users/supratik/.local/share/virtualenvs/api_sourcer-sM-JSZy3-/Users/supratik/.pyenv/shims/python/lib/python3.6/site-packages/boto3/resources/factory.py", line 339, in property_loader
    self.load()
  File "/Users/supratik/.local/share/virtualenvs/api_sourcer-sM-JSZy3-/Users/supratik/.pyenv/shims/python/lib/python3.6/site-packages/boto3/resources/factory.py", line 505, in do_action
    response = action(self, *args, **kwargs)
  File "/Users/supratik/.local/share/virtualenvs/api_sourcer-sM-JSZy3-/Users/supratik/.pyenv/shims/python/lib/python3.6/site-packages/boto3/resources/action.py", line 83, in __call__
    response = getattr(parent.meta.client, operation_name)(**params)
  File "/Users/supratik/.local/share/virtualenvs/api_sourcer-sM-JSZy3-/Users/supratik/.pyenv/shims/python/lib/python3.6/site-packages/botocore/client.py", line 316, in _api_call
    return self._make_api_call(operation_name, kwargs)
  File "/Users/supratik/.local/share/virtualenvs/api_sourcer-sM-JSZy3-/Users/supratik/.pyenv/shims/python/lib/python3.6/site-packages/botocore/client.py", line 613, in _make_api_call
    operation_model, request_dict, request_context)
  File "/Users/supratik/.local/share/virtualenvs/api_sourcer-sM-JSZy3-/Users/supratik/.pyenv/shims/python/lib/python3.6/site-packages/botocore/client.py", line 632, in _make_request
    return self._endpoint.make_request(operation_model, request_dict)
  File "/Users/supratik/.local/share/virtualenvs/api_sourcer-sM-JSZy3-/Users/supratik/.pyenv/shims/python/lib/python3.6/site-packages/botocore/endpoint.py", line 102, in make_request
    return self._send_request(request_dict, operation_model)
  File "/Users/supratik/.local/share/virtualenvs/api_sourcer-sM-JSZy3-/Users/supratik/.pyenv/shims/python/lib/python3.6/site-packages/botocore/endpoint.py", line 135, in _send_request
    request, operation_model, context)
  File "/Users/supratik/.local/share/virtualenvs/api_sourcer-sM-JSZy3-/Users/supratik/.pyenv/shims/python/lib/python3.6/site-packages/botocore/endpoint.py", line 167, in _get_response
    request, operation_model)
  File "/Users/supratik/.local/share/virtualenvs/api_sourcer-sM-JSZy3-/Users/supratik/.pyenv/shims/python/lib/python3.6/site-packages/botocore/endpoint.py", line 218, in _do_get_response
    response_dict, operation_model.output_shape)
  File "/Users/supratik/.local/share/virtualenvs/api_sourcer-sM-JSZy3-/Users/supratik/.pyenv/shims/python/lib/python3.6/site-packages/botocore/parsers.py", line 242, in parse
    parsed = self._do_parse(response, shape)
  File "/Users/supratik/.local/share/virtualenvs/api_sourcer-sM-JSZy3-/Users/supratik/.pyenv/shims/python/lib/python3.6/site-packages/botocore/parsers.py", line 509, in _do_parse
    parsed = self._parse_shape(shape, start)
  File "/Users/supratik/.local/share/virtualenvs/api_sourcer-sM-JSZy3-/Users/supratik/.pyenv/shims/python/lib/python3.6/site-packages/botocore/parsers.py", line 302, in _parse_shape
    return handler(shape, node)
  File "/Users/supratik/.local/share/virtualenvs/api_sourcer-sM-JSZy3-/Users/supratik/.pyenv/shims/python/lib/python3.6/site-packages/botocore/parsers.py", line 377, in _handle_structure
    member_shape, member_node)
  File "/Users/supratik/.local/share/virtualenvs/api_sourcer-sM-JSZy3-/Users/supratik/.pyenv/shims/python/lib/python3.6/site-packages/botocore/parsers.py", line 302, in _parse_shape
    return handler(shape, node)
  File "/Users/supratik/.local/share/virtualenvs/api_sourcer-sM-JSZy3-/Users/supratik/.pyenv/shims/python/lib/python3.6/site-packages/botocore/parsers.py", line 377, in _handle_structure
    member_shape, member_node)
  File "/Users/supratik/.local/share/virtualenvs/api_sourcer-sM-JSZy3-/Users/supratik/.pyenv/shims/python/lib/python3.6/site-packages/botocore/parsers.py", line 302, in _parse_shape
    return handler(shape, node)
  File "/Users/supratik/.local/share/virtualenvs/api_sourcer-sM-JSZy3-/Users/supratik/.pyenv/shims/python/lib/python3.6/site-packages/botocore/parsers.py", line 175, in _get_text_content
    return func(self, shape, text)
  File "/Users/supratik/.local/share/virtualenvs/api_sourcer-sM-JSZy3-/Users/supratik/.pyenv/shims/python/lib/python3.6/site-packages/botocore/parsers.py", line 462, in _handle_timestamp
    return self._timestamp_parser(text)
  File "/Users/supratik/.local/share/virtualenvs/api_sourcer-sM-JSZy3-/Users/supratik/.pyenv/shims/python/lib/python3.6/site-packages/botocore/utils.py", line 626, in parse_timestamp
    return _parse_timestamp_with_tzinfo(value, tzinfo)
  File "/Users/supratik/.local/share/virtualenvs/api_sourcer-sM-JSZy3-/Users/supratik/.pyenv/shims/python/lib/python3.6/site-packages/botocore/utils.py", line 607, in _parse_timestamp_with_tzinfo
    return dateutil.parser.parse(value, tzinfos={'GMT': tzutc()})
  File "/Users/supratik/.local/share/virtualenvs/api_sourcer-sM-JSZy3-/Users/supratik/.pyenv/shims/python/lib/python3.6/site-packages/dateutil/parser/_parser.py", line 1374, in parse
    return DEFAULTPARSER.parse(timestr, **kwargs)
  File "/Users/supratik/.local/share/virtualenvs/api_sourcer-sM-JSZy3-/Users/supratik/.pyenv/shims/python/lib/python3.6/site-packages/dateutil/parser/_parser.py", line 660, in parse
    ret = self._build_tzaware(ret, res, tzinfos)
  File "/Users/supratik/.local/share/virtualenvs/api_sourcer-sM-JSZy3-/Users/supratik/.pyenv/shims/python/lib/python3.6/site-packages/dateutil/parser/_parser.py", line 1201, in _build_tzaware
    aware = naive.replace(tzinfo=tz.UTC)
AttributeError: module 'dateutil.tz' has no attribute 'UTC'

==============```
</code>```

答:
python -m pip install --upgrade python-dateutil

Upgrading python-dateutil solve the problem for me. On my machine, 2.5.3 to 2.8.1.

Skimming the source code, I found out that UTC variable is added in 2.7.0. So, I think any version >= 2.7.0 will solve the issue.

```<code>#: Convenience constant providing a :class:`tzutc()` instance
#:
#: .. versionadded:: 2.7.0
UTC = tzutc()
</code>```

Body:
On trying to deploy my AWS Lambda function get this error on my Stacktrace

(python-dateutil 2.8.1 (/Users/supratik/.local/share/virtualenvs/api_sourcer-sM-JSZy3-/Users/supratik/.pyenv/shims/python/lib/python3.6/site-packages), Requirement.parse('python-dateutil<2.7.0'), {'zappa'})
Calling deploy for stage development..
Oh no! An error occurred! :(

==============

Traceback (most recent call last):
  File "/Users/supratik/.local/share/virtualenvs/api_sourcer-sM-JSZy3-/Users/supratik/.pyenv/shims/python/lib/python3.6/site-packages/zappa/cli.py", line 2778, in handle
    sys.exit(cli.handle())
  File "/Users/supratik/.local/share/virtualenvs/api_sourcer-sM-JSZy3-/Users/supratik/.pyenv/shims/python/lib/python3.6/site-packages/zappa/cli.py", line 512, in handle
    self.dispatch_command(self.command, stage)
  File "/Users/supratik/.local/share/virtualenvs/api_sourcer-sM-JSZy3-/Users/supratik/.pyenv/shims/python/lib/python3.6/site-packages/zappa/cli.py", line 549, in dispatch_command
    self.deploy(self.vargs['zip'])
  File "/Users/supratik/.local/share/virtualenvs/api_sourcer-sM-JSZy3-/Users/supratik/.pyenv/shims/python/lib/python3.6/site-packages/zappa/cli.py", line 709, in deploy
    self.zappa.create_iam_roles()
  File "/Users/supratik/.local/share/virtualenvs/api_sourcer-sM-JSZy3-/Users/supratik/.pyenv/shims/python/lib/python3.6/site-packages/zappa/core.py", line 2557, in create_iam_roles
    role, credentials_arn = self.get_credentials_arn()
  File "/Users/supratik/.local/share/virtualenvs/api_sourcer-sM-JSZy3-/Users/supratik/.pyenv/shims/python/lib/python3.6/site-packages/zappa/core.py", line 2536, in get_credentials_arn
    self.credentials_arn = role.arn
  File "/Users/supratik/.local/share/virtualenvs/api_sourcer-sM-JSZy3-/Users/supratik/.pyenv/shims/python/lib/python3.6/site-packages/boto3/resources/factory.py", line 339, in property_loader
    self.load()
  File "/Users/supratik/.local/share/virtualenvs/api_sourcer-sM-JSZy3-/Users/supratik/.pyenv/shims/python/lib/python3.6/site-packages/boto3/resources/factory.py", line 505, in do_action
    response = action(self, *args, **kwargs)
  File "/Users/supratik/.local/share/virtualenvs/api_sourcer-sM-JSZy3-/Users/supratik/.pyenv/shims/python/lib/python3.6/site-packages/boto3/resources/action.py", line 83, in __call__
    response = getattr(parent.meta.client, operation_name)(**params)
  File "/Users/supratik/.local/share/virtualenvs/api_sourcer-sM-JSZy3-/Users/supratik/.pyenv/shims/python/lib/python3.6/site-packages/botocore/client.py", line 316, in _api_call
    return self._make_api_call(operation_name, kwargs)
  File "/Users/supratik/.local/share/virtualenvs/api_sourcer-sM-JSZy3-/Users/supratik/.pyenv/shims/python/lib/python3.6/site-packages/botocore/client.py", line 613, in _make_api_call
    operation_model, request_dict, request_context)
  File "/Users/supratik/.local/share/virtualenvs/api_sourcer-sM-JSZy3-/Users/supratik/.pyenv/shims/python/lib/python3.6/site-packages/botocore/client.py", line 632, in _make_request
    return self._endpoint.make_request(operation_model, request_dict)
  File "/Users/supratik/.local/share/virtualenvs/api_sourcer-sM-JSZy3-/Users/supratik/.pyenv/shims/python/lib/python3.6/site-packages/botocore/endpoint.py", line 102, in make_request
    return self._send_request(request_dict, operation_model)
  File "/Users/supratik/.local/share/virtualenvs/api_sourcer-sM-JSZy3-/Users/supratik/.pyenv/shims/python/lib/python3.6/site-packages/botocore/endpoint.py", line 135, in _send_request
    request, operation_model, context)
  File "/Users/supratik/.local/share/virtualenvs/api_sourcer-sM-JSZy3-/Users/supratik/.pyenv/shims/python/lib/python3.6/site-packages/botocore/endpoint.py", line 167, in _get_response
    request, operation_model)
  File "/Users/supratik/.local/share/virtualenvs/api_sourcer-sM-JSZy3-/Users/supratik/.pyenv/shims/python/lib/python3.6/site-packages/botocore/endpoint.py", line 218, in _do_get_response
    response_dict, operation_model.output_shape)
  File "/Users/supratik/.local/share/virtualenvs/api_sourcer-sM-JSZy3-/Users/supratik/.pyenv/shims/python/lib/python3.6/site-packages/botocore/parsers.py", line 242, in parse
    parsed = self._do_parse(response, shape)
  File "/Users/supratik/.local/share/virtualenvs/api_sourcer-sM-JSZy3-/Users/supratik/.pyenv/shims/python/lib/python3.6/site-packages/botocore/parsers.py", line 509, in _do_parse
    parsed = self._parse_shape(shape, start)
  File "/Users/supratik/.local/share/virtualenvs/api_sourcer-sM-JSZy3-/Users/supratik/.pyenv/shims/python/lib/python3.6/site-packages/botocore/parsers.py", line 302, in _parse_shape
    return handler(shape, node)
  File "/Users/supratik/.local/share/virtualenvs/api_sourcer-sM-JSZy3-/Users/supratik/.pyenv/shims/python/lib/python3.6/site-packages/botocore/parsers.py", line 377, in _handle_structure
    member_shape, member_node)
  File "/Users/supratik/.local/share/virtualenvs/api_sourcer-sM-JSZy3-/Users/supratik/.pyenv/shims/python/lib/python3.6/site-packages/botocore/parsers.py", line 302, in _parse_shape
    return handler(shape, node)
  File "/Users/supratik/.local/share/virtualenvs/api_sourcer-sM-JSZy3-/Users/supratik/.pyenv/shims/python/lib/python3.6/site-packages/botocore/parsers.py", line 377, in _handle_structure
    member_shape, member_node)
  File "/Users/supratik/.local/share/virtualenvs/api_sourcer-sM-JSZy3-/Users/supratik/.pyenv/shims/python/lib/python3.6/site-packages/botocore/parsers.py", line 302, in _parse_shape
    return handler(shape, node)
  File "/Users/supratik/.local/share/virtualenvs/api_sourcer-sM-JSZy3-/Users/supratik/.pyenv/shims/python/lib/python3.6/site-packages/botocore/parsers.py", line 175, in _get_text_content
    return func(self, shape, text)
  File "/Users/supratik/.local/share/virtualenvs/api_sourcer-sM-JSZy3-/Users/supratik/.pyenv/shims/python/lib/python3.6/site-packages/botocore/parsers.py", line 462, in _handle_timestamp
    return self._timestamp_parser(text)
  File "/Users/supratik/.local/share/virtualenvs/api_sourcer-sM-JSZy3-/Users/supratik/.pyenv/shims/python/lib/python3.6/site-packages/botocore/utils.py", line 626, in parse_timestamp
    return _parse_timestamp_with_tzinfo(value, tzinfo)
  File "/Users/supratik/.local/share/virtualenvs/api_sourcer-sM-JSZy3-/Users/supratik/.pyenv/shims/python/lib/python3.6/site-packages/botocore/utils.py", line 607, in _parse_timestamp_with_tzinfo
    return dateutil.parser.parse(value, tzinfos={'GMT': tzutc()})
  File "/Users/supratik/.local/share/virtualenvs/api_sourcer-sM-JSZy3-/Users/supratik/.pyenv/shims/python/lib/python3.6/site-packages/dateutil/parser/_parser.py", line 1374, in parse
    return DEFAULTPARSER.parse(timestr, **kwargs)
  File "/Users/supratik/.local/share/virtualenvs/api_sourcer-sM-JSZy3-/Users/supratik/.pyenv/shims/python/lib/python3.6/site-packages/dateutil/parser/_parser.py", line 660, in parse
    ret = self._build_tzaware(ret, res, tzinfos)
  File "/Users/supratik/.local/share/virtualenvs/api_sourcer-sM-JSZy3-/Users/supratik/.pyenv/shims/python/lib/python3.6/site-packages/dateutil/parser/_parser.py", line 1201, in _build_tzaware
    aware = naive.replace(tzinfo=tz.UTC)
AttributeError: module 'dateutil.tz' has no attribute 'UTC'

==============```

Body:
python -m pip install --upgrade python-dateutil

Upgrading python-dateutil solve the problem for me. On my machine, 2.5.3 to 2.8.1.

Skimming the source code, I found out that UTC variable is added in 2.7.0. So, I think any version >= 2.7.0 will solve the issue.

#: Convenience constant providing a :class:`tzutc()` instance
#:
#: .. versionadded:: 2.7.0
UTC = tzutc()


问:
Facebook API Access token
Hello I am reading the Facebook API docs but I need a simple Help.

```<code>$token_url = "https://graph.facebook.com/oauth/access_token?"
       . "client_id=" . $app_id . "&redirect_uri=" . urlencode($my_url)
       . "&client_secret=" . $app_secret . "&code=" . $code;
</code>```

I do understand all the variables...

But I do NOT understand what is $code

What is that variable?

I just need to get the last status of the user from the Facebook Feed.

I need to generate the Access Token, but I do not really know what that $code means??

Please help.

答:
This is explained thoroughly in Facebook Developers Documentation here.

If the user presses Allow, your app is
  authorized. The OAuth Dialog will
  redirect (via HTTP 302) the user's
  browser to the URL you passed in the
  redirect_uri parameter with an
  authorization code:

http://YOUR_URL?code=A_CODE_GENERATED_BY_SERVER

After you recieve this code you can use it to get an access token:

In order to authenticate your app, you
  must pass the authorization code and
  your app secret to the Graph API token
  endpoint at
  https://graph.facebook.com/oauth/access_token.
  The app secret is available from the
  Developer App and should not be shared
  with anyone or embedded in any code
  that you will distribute (you should
  use the client-side flow for these
  scenarios).

```<code> https://graph.facebook.com/oauth/access_token?
      client_id=YOUR_APP_ID&redirect_uri=YOUR_URL&
      client_secret=YOUR_APP_SECRET&code=THE_CODE_FROM_ABOVE
</code>```

ContentLicense: CC BY-SA 3.0

Title: Facebook API Access token

Body:
Hello I am reading the Facebook API docs but I need a simple Help.

$token_url = "https://graph.facebook.com/oauth/access_token?"
       . "client_id=" . $app_id . "&redirect_uri=" . urlencode($my_url)
       . "&client_secret=" . $app_secret . "&code=" . $code;

I do understand all the variables...

But I do NOT understand what is $code

What is that variable?

I just need to get the last status of the user from the Facebook Feed.

I need to generate the Access Token, but I do not really know what that $code means??

Please help.

Body:
This is explained thoroughly in Facebook Developers Documentation here.

If the user presses Allow, your app is
  authorized. The OAuth Dialog will
  redirect (via HTTP 302) the user's
  browser to the URL you passed in the
  redirect_uri parameter with an
  authorization code:

http://YOUR_URL?code=A_CODE_GENERATED_BY_SERVER

After you recieve this code you can use it to get an access token:

In order to authenticate your app, you
  must pass the authorization code and
  your app secret to the Graph API token
  endpoint at
  https://graph.facebook.com/oauth/access_token.
  The app secret is available from the
  Developer App and should not be shared
  with anyone or embedded in any code
  that you will distribute (you should
  use the client-side flow for these
  scenarios).

 https://graph.facebook.com/oauth/access_token?
      client_id=YOUR_APP_ID&redirect_uri=YOUR_URL&
      client_secret=YOUR_APP_SECRET&code=THE_CODE_FROM_ABOVE


问:
How to add a table on Wordpress page without using shortcode
I created a table using ninja table plugin. I am able to add that table on my page using short code of that table.Now I want to add a table on my page without short code like if I created a new page than I get an option of table customization like add a table, add a row & column delete a row and column etc.

I already used ninja and tablepress plugin

Note: Biggest task is to add a table without using short code .

答:
Your ultimate goal is to add a table on a page without using any plugin.
The new Gutenberg editor that was launched with WordPress 5.0 allows you to add tables in WordPress easily.

You can follow the steps on this instructions page.


问:
Making app service work invisible in background
i have an app that runs a background service infinitely while also hiding the app icon and hiding it from the backstack so it wont be visible to the user while running using:

```<code>       val componentName = ComponentName(this, FullscreenActivity::class.java)
       p.setComponentEnabledSetting(
           componentName,
           PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
           PackageManager.DONT_KILL_APP
       )
</code>```

this is how i launch the service from my fragment :

```<code>parentFragment?.activity?.startService(
                    Intent(
                        requireParentFragment().requireActivity().applicationContext,
                        RescueService::class.java
                    ).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                )
</code>```

which successfully hides the icon and the app from backstack and the service keep running, also when i press the square button on my phone to show the backstack apps running i dont see the app there which is what i want, but if i click the "X" button to clear all backstack apps it also kills my app and my service dies even though the app does not appear there as i mentioned.

Any ideas what makes the service die after doing it? because it did not happen to couple of days ago before i did some changes in my app..

One of the changes i made is turnning my Service into LifecycleService because i needed my service to observe a livedata which needs a LifecycleOwner.Can it be the cause of my service to die when clearing the backstack?

All suggestions will be welcomed !

EDIT1 - here is my TestService  that performs voice recording uses WorkManager.I call hideApp() to hide the icon from the phone and make the app invisible from the backstack :

```<code>class RecordingWork(
    context: Context,
    params: WorkerParameters
) : CoroutineWorker(context, params) {

    override val coroutineContext = Dispatchers.Main
    override suspend fun doWork(): Result {

        mSpeechRecognizer.startListening(mSpeechRecognizerIntent)
        return Result.success()
    }
}

private lateinit var mSpeechRecognizer: SpeechRecognizer
private val mSpeechRecognizerIntent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH)

class TestService : Service() {

    private lateinit var workManager: WorkManager

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        Log.d("TestService", "onStartCommand called")
        hideApp()
        prepareVoiceRecording()
        workManager = WorkManager.getInstance(applicationContext)
        workManager.enqueue(OneTimeWorkRequestBuilder<RecordingWork>().build())

        return START_REDELIVER_INTENT
    }

    override fun onBind(intent: Intent?): IBinder? {
        return null
    }

    fun prepareVoiceRecording() {
        mSpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(applicationContext)
        mSpeechRecognizerIntent.putExtra(
            RecognizerIntent.EXTRA_LANGUAGE_MODEL,
            RecognizerIntent.LANGUAGE_MODEL_FREE_FORM
        )
        mSpeechRecognizerIntent.putExtra(
            RecognizerIntent.EXTRA_LANGUAGE,
            Locale.getDefault()
        )
        mSpeechRecognizer.setRecognitionListener(
            object : RecognitionListener {

                @RequiresApi(Build.VERSION_CODES.M)
                override fun onError(i: Int) {
                    Log.d(TAG, "onErrorCalled error is $i")
                    if (i == SpeechRecognizer.ERROR_NETWORK || i == SpeechRecognizer.ERROR_SPEECH_TIMEOUT || i == SpeechRecognizer.ERROR_NO_MATCH) {
                        Log.d(TAG, "error triggered")
                        mSpeechRecognizer.destroy()
                        prepareVoiceRecording()
                        workManager.enqueue(OneTimeWorkRequestBuilder<RecordingWork>().build())

                    }
                }

                @RequiresApi(Build.VERSION_CODES.M)
                override fun onResults(bundle: Bundle) {
                    Log.d(TAG, "onResults Called")
                    //getting all the matches
                    val matches = bundle
                        .getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION)!!
                    workManager.enqueue(OneTimeWorkRequestBuilder<RecordingWork>().build())
                }

 private fun hideApp() {
        val componentName = ComponentName(
            this,
            WelcomeScreenActivity::class.java
        )
        packageManager.setComponentEnabledSetting(
            componentName,
            PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
            PackageManager.DONT_KILL_APP
        )
    }
</code>```

this service does work to repeatedly record voice by rescheduling the Worker every time. but this service also dies when clearing backstack (even though the app does not appear there because of hideApp())

答: Use workManager for long running background task (some device like Mi phone you need to white list the app for battery saver if you don't do that the OS will kill your app) and hiding of app icon not work in android X (only system apps can hide their icon)</p>

Body:
i have an app that runs a background service infinitely while also hiding the app icon and hiding it from the backstack so it wont be visible to the user while running using:

       val componentName = ComponentName(this, FullscreenActivity::class.java)
       p.setComponentEnabledSetting(
           componentName,
           PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
           PackageManager.DONT_KILL_APP
       )

this is how i launch the service from my fragment :

parentFragment?.activity?.startService(
                    Intent(
                        requireParentFragment().requireActivity().applicationContext,
                        RescueService::class.java
                    ).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                )

which successfully hides the icon and the app from backstack and the service keep running, also when i press the square button on my phone to show the backstack apps running i dont see the app there which is what i want, but if i click the "X" button to clear all backstack apps it also kills my app and my service dies even though the app does not appear there as i mentioned.

Any ideas what makes the service die after doing it? because it did not happen to couple of days ago before i did some changes in my app..

One of the changes i made is turnning my Service into LifecycleService because i needed my service to observe a livedata which needs a LifecycleOwner.Can it be the cause of my service to die when clearing the backstack?

All suggestions will be welcomed !

EDIT1 - here is my TestService  that performs voice recording uses WorkManager.I call hideApp() to hide the icon from the phone and make the app invisible from the backstack :

class RecordingWork(
    context: Context,
    params: WorkerParameters
) : CoroutineWorker(context, params) {

    override val coroutineContext = Dispatchers.Main
    override suspend fun doWork(): Result {

        mSpeechRecognizer.startListening(mSpeechRecognizerIntent)
        return Result.success()
    }
}

private lateinit var mSpeechRecognizer: SpeechRecognizer
private val mSpeechRecognizerIntent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH)

class TestService : Service() {

    private lateinit var workManager: WorkManager

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        Log.d("TestService", "onStartCommand called")
        hideApp()
        prepareVoiceRecording()
        workManager = WorkManager.getInstance(applicationContext)
        workManager.enqueue(OneTimeWorkRequestBuilder<RecordingWork>().build())

        return START_REDELIVER_INTENT
    }

    override fun onBind(intent: Intent?): IBinder? {
        return null
    }

    fun prepareVoiceRecording() {
        mSpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(applicationContext)
        mSpeechRecognizerIntent.putExtra(
            RecognizerIntent.EXTRA_LANGUAGE_MODEL,
            RecognizerIntent.LANGUAGE_MODEL_FREE_FORM
        )
        mSpeechRecognizerIntent.putExtra(
            RecognizerIntent.EXTRA_LANGUAGE,
            Locale.getDefault()
        )
        mSpeechRecognizer.setRecognitionListener(
            object : RecognitionListener {

                @RequiresApi(Build.VERSION_CODES.M)
                override fun onError(i: Int) {
                    Log.d(TAG, "onErrorCalled error is $i")
                    if (i == SpeechRecognizer.ERROR_NETWORK || i == SpeechRecognizer.ERROR_SPEECH_TIMEOUT || i == SpeechRecognizer.ERROR_NO_MATCH) {
                        Log.d(TAG, "error triggered")
                        mSpeechRecognizer.destroy()
                        prepareVoiceRecording()
                        workManager.enqueue(OneTimeWorkRequestBuilder<RecordingWork>().build())

                    }
                }

                @RequiresApi(Build.VERSION_CODES.M)
                override fun onResults(bundle: Bundle) {
                    Log.d(TAG, "onResults Called")
                    //getting all the matches
                    val matches = bundle
                        .getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION)!!
                    workManager.enqueue(OneTimeWorkRequestBuilder<RecordingWork>().build())
                }

 private fun hideApp() {
        val componentName = ComponentName(
            this,
            WelcomeScreenActivity::class.java
        )
        packageManager.setComponentEnabledSetting(
            componentName,
            PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
            PackageManager.DONT_KILL_APP
        )
    }

this service does work to repeatedly record voice by rescheduling the Worker every time. but this service also dies when clearing backstack (even though the app does not appear there because of hideApp())


问:
How to extract href link title with selenium?
I am having issues figuring out how to extract all 100 of the link titles on the page with selenium. I have the code to extract only the links but how would I go about doing the same but for the link titles? Any help would be appreciated, thanks!

What I have:

```<code>from selenium import webdriver
driver = webdriver.Chrome('/Users/wwds/Downloads/chromedriver')
driver.get('https://www150.statcan.gc.ca/n1/en/type/data?count=100')

elems = driver.find_elements_by_css_selector(".ndm-result-title [href]")
links = [elem.get_attribute('href') for elem in elems]
</code>```

答:
To get the title from all 100 links on a page.You need to induce WebDriverWait() and wait for visibility_of_all_elements_located() and the following css selector.

```<code>driver.get('https://www150.statcan.gc.ca/n1/en/type/data?count=100')
elements = WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "#all a[target='_self']")))
linkTitles = [title.text for title in elements]
print(len(linkTitles))
print(linkTitles)
</code>```

You need to import following libraries.

```<code>from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
</code>```

Output Console:

```<code>100
['Capital markets activities, gross new issues, retirements and net new issues, par value, Bank of Canada', 'Funds advanced, outstanding balances, and interest rates for new and existing lending, Bank of Canada', 'Funds advanced, outstanding balances, and interest rates for new and existing lending, dollars, Bank of Canada', 'Net new issues of bonds and equities by corporations and federal government enterprises: Industrial classification, Bank of Canada', 'Bank of Canada, assets and liabilities, average of Wednesdays', 'Chartered banks, assets and liabilities, monthly average, Bank of Canada', 'Currency outside banks and chartered bank deposits, monthly average, Bank of Canada', 'Selected credit measures, monthly average or average of month-ends, unadjusted unless otherwise noted, Bank of Canada', 'Chartered bank assets and liabilities and monetary aggregates, monthly average, seasonally adjusted, Bank of Canada', 'Consumer credit, outstanding balances of selected holders, Bank of Canada', 'Credit measures, Bank of Canada', 'Corporate short-term paper outstanding, Bank of Canada, monthly', 'Toronto Stock Exchange statistics', 'Residential mortgage credit, outstanding balances of major private institutional lenders, Bank of Canada', 'Bonds outstanding, shown at par value, by currency of payments and issuers, Bank of Canada', 'Bank of Canada, assets and liabilities, Wednesdays', 'Bank of Canada, money market and other interest rates', 'Positions of members of the Canadian Payments Association and Bank of Canada operations, Bank of Canada, weekly', 'Chartered banks, classification of non-mortgage loans, at end of period, Bank of Canada', 'Tobacco, sales and inventories, monthly production', 'Historical (real-time) releases of Consumer Price Index (CPI) statistics, measures of core inflation - Bank of Canada definitions', 'Historical (real-time) releases of wholesale sales, price and volume, seasonally adjusted', 'Historical (real-time) releases of wholesale trade, sales', 'Historical (real-time) releases of wholesale trade, inventories', 'Historical (real-time) releases of retail trade, sales', 'Historical (real-time) releases of retail sales, price, and volume', 'Capital expenditures, oil and gas extraction industries, Canada', 'Daily average foreign exchange rates in Canadian dollars, Bank of Canada', 'Investment in Building Construction', 'Gross domestic product (GDP) at basic prices, by industry, provinces and territories, percentage share', 'Gross domestic product (GDP) at basic prices, by industry, provinces and territories', 'Gross domestic product (GDP) at basic prices, by industry, provinces and territories, growth rates', 'Canadian Economic Dashboard and COVID-19', 'Statistics Canada - Data Visualization Products', 'Financial market statistics, last Wednesday unless otherwise stated, Bank of Canada', 'Selected United States dollar interest rates, Wednesdays, Bank of Canada', 'Fisher commodity price index, United States dollar terms, Bank of Canada, Fisher commodity price index, United States dollar terms, Bank of Canada, weekly', 'Financial market statistics, as at Wednesday, Bank of Canada', 'Exports and imports of goods and services, quarterly, Canada, (NAPCS 2017)', 'Contributions to annual percent change in real exports and imports of goods and services, Canada, annual, (NAPCS 2017)', 'Industrial product price index, by major product group, monthly', 'Industrial product price index, by major product group, percentage change, monthly', 'Industrial product price index, by product, monthly', 'Industrial product price index, by product, percentage change, monthly', 'Industrial product price index, for selected products, by region, monthly', 'Industrial product price index, for selected products, by region, percentage change, monthly', 'Industrial product price index, by industry, monthly', 'Industrial product price index, by industry, percentage change, monthly', 'Raw materials price index, monthly', 'Raw materials price index, percentage change, monthly', 'Commercial software price index, monthly', 'Commercial software price index, percentage change, monthly', 'Couriers and messengers services price index, monthly', 'Couriers and messengers services price index, percentage change, monthly', 'Computer price index, by type of purchaser, monthly', 'Computer price index, by type of purchaser, percentage change, monthly', 'Computer peripheral price index, monthly', 'Computer peripheral price index, percentage change, monthly', 'Smart phone price index, monthly', 'Smart phone price index, percentage change, monthly', 'Civil aviation operating statistics, by type of service, Canadian air carriers, Levels I and II, quarterly', 'Civil aviation operating statistics, by sector, Canadian air carriers, Levels I and II, quarterly', 'Civil aviation financial statistics, Canadian air carriers, Levels I and II, quarterly', 'Civil aviation financial performance indicators, Canadian air carriers, Levels I and II, quarterly', 'Civil aviation productivity measures, Canadian air carriers, Levels I and II, quarterly', 'Weekly rail terminal performance indicator, Transport Canada', 'Weekly performance indicators of grain transportation by rail, Transport Canada', 'Weekly rail system performance indicators, by commodities, Transport Canada', 'Weekly rail system performance indicator, by type of rail car, Transport Canada', 'Flows and stocks of fixed non-residential and residential capital, by sector and asset, provincial and territorial', 'Gross domestic product, income-based, quarterly', 'Gross domestic product, expenditure-based, Canada, quarterly', 'Gross national income and gross domestic income, indexes and related statistics, quarterly', 'Gross domestic product price indexes, quarterly', 'Household final consumption expenditure, quarterly, Canada', 'Gross fixed capital formation, quarterly, Canada', 'Investment in inventories, quarterly, Canada', 'Current and capital accounts - National, Canada, quarterly', 'Current and capital accounts - Households, Canada, quarterly', 'Compensation of employees, Canada, quarterly', 'Current and capital accounts - Non-profit institutions serving households, Canada, quarterly', 'Current and capital accounts - Corporations, Canada, quarterly', 'Undistributed corporation profits', 'Current and capital accounts - General governments, Canada, quarterly', 'Current and capital accounts - Non-residents, Canada, quarterly', 'Gross domestic income, gross national income and net national income, Canada, quarterly', 'Gross domestic product, expenditure-based, at 2012 constant prices, quarterly', 'Detailed household final consumption expenditure, Canada, quarterly', 'Corporation profits before taxes, on an original-cost-basis, excluding government business enterprises, Canada, quarterly', 'Property income of households, Canada', 'General governments final consumption expenditure, Canada, quarterly', 'Contributions to annual percent change in real expenditure-based gross domestic product, Canada, annual', 'Gross national income and gross domestic income, indexes and related statistics, annual', 'Gross domestic product price indexes, annual (2012=100)', 'Contributions to annual percent change in real household final consumption expenditure, Canada, annual', 'Contributions to annual percent change in real gross fixed capital formation, Canada, annual', 'Contributions to annual percent change in real general governments final consumption expenditure, Canada, annual', "Wages, salaries and employers' social contributions", 'Gross domestic product, expenditure-based, at 2012 constant prices, annual', 'Gross domestic product (GDP) at basic prices, by industry, monthly']
</code>```

Body:
I am having issues figuring out how to extract all 100 of the link titles on the page with selenium. I have the code to extract only the links but how would I go about doing the same but for the link titles? Any help would be appreciated, thanks!

What I have:

from selenium import webdriver
driver = webdriver.Chrome('/Users/wwds/Downloads/chromedriver')
driver.get('https://www150.statcan.gc.ca/n1/en/type/data?count=100')

elems = driver.find_elements_by_css_selector(".ndm-result-title [href]")
links = [elem.get_attribute('href') for elem in elems]

Body:
To get the title from all 100 links on a page.You need to induce WebDriverWait() and wait for visibility_of_all_elements_located() and the following css selector.

driver.get('https://www150.statcan.gc.ca/n1/en/type/data?count=100')
elements = WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "#all a[target='_self']")))
linkTitles = [title.text for title in elements]
print(len(linkTitles))
print(linkTitles)

You need to import following libraries.

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

Output Console:

100
['Capital markets activities, gross new issues, retirements and net new issues, par value, Bank of Canada', 'Funds advanced, outstanding balances, and interest rates for new and existing lending, Bank of Canada', 'Funds advanced, outstanding balances, and interest rates for new and existing lending, dollars, Bank of Canada', 'Net new issues of bonds and equities by corporations and federal government enterprises: Industrial classification, Bank of Canada', 'Bank of Canada, assets and liabilities, average of Wednesdays', 'Chartered banks, assets and liabilities, monthly average, Bank of Canada', 'Currency outside banks and chartered bank deposits, monthly average, Bank of Canada', 'Selected credit measures, monthly average or average of month-ends, unadjusted unless otherwise noted, Bank of Canada', 'Chartered bank assets and liabilities and monetary aggregates, monthly average, seasonally adjusted, Bank of Canada', 'Consumer credit, outstanding balances of selected holders, Bank of Canada', 'Credit measures, Bank of Canada', 'Corporate short-term paper outstanding, Bank of Canada, monthly', 'Toronto Stock Exchange statistics', 'Residential mortgage credit, outstanding balances of major private institutional lenders, Bank of Canada', 'Bonds outstanding, shown at par value, by currency of payments and issuers, Bank of Canada', 'Bank of Canada, assets and liabilities, Wednesdays', 'Bank of Canada, money market and other interest rates', 'Positions of members of the Canadian Payments Association and Bank of Canada operations, Bank of Canada, weekly', 'Chartered banks, classification of non-mortgage loans, at end of period, Bank of Canada', 'Tobacco, sales and inventories, monthly production', 'Historical (real-time) releases of Consumer Price Index (CPI) statistics, measures of core inflation - Bank of Canada definitions', 'Historical (real-time) releases of wholesale sales, price and volume, seasonally adjusted', 'Historical (real-time) releases of wholesale trade, sales', 'Historical (real-time) releases of wholesale trade, inventories', 'Historical (real-time) releases of retail trade, sales', 'Historical (real-time) releases of retail sales, price, and volume', 'Capital expenditures, oil and gas extraction industries, Canada', 'Daily average foreign exchange rates in Canadian dollars, Bank of Canada', 'Investment in Building Construction', 'Gross domestic product (GDP) at basic prices, by industry, provinces and territories, percentage share', 'Gross domestic product (GDP) at basic prices, by industry, provinces and territories', 'Gross domestic product (GDP) at basic prices, by industry, provinces and territories, growth rates', 'Canadian Economic Dashboard and COVID-19', 'Statistics Canada - Data Visualization Products', 'Financial market statistics, last Wednesday unless otherwise stated, Bank of Canada', 'Selected United States dollar interest rates, Wednesdays, Bank of Canada', 'Fisher commodity price index, United States dollar terms, Bank of Canada, Fisher commodity price index, United States dollar terms, Bank of Canada, weekly', 'Financial market statistics, as at Wednesday, Bank of Canada', 'Exports and imports of goods and services, quarterly, Canada, (NAPCS 2017)', 'Contributions to annual percent change in real exports and imports of goods and services, Canada, annual, (NAPCS 2017)', 'Industrial product price index, by major product group, monthly', 'Industrial product price index, by major product group, percentage change, monthly', 'Industrial product price index, by product, monthly', 'Industrial product price index, by product, percentage change, monthly', 'Industrial product price index, for selected products, by region, monthly', 'Industrial product price index, for selected products, by region, percentage change, monthly', 'Industrial product price index, by industry, monthly', 'Industrial product price index, by industry, percentage change, monthly', 'Raw materials price index, monthly', 'Raw materials price index, percentage change, monthly', 'Commercial software price index, monthly', 'Commercial software price index, percentage change, monthly', 'Couriers and messengers services price index, monthly', 'Couriers and messengers services price index, percentage change, monthly', 'Computer price index, by type of purchaser, monthly', 'Computer price index, by type of purchaser, percentage change, monthly', 'Computer peripheral price index, monthly', 'Computer peripheral price index, percentage change, monthly', 'Smart phone price index, monthly', 'Smart phone price index, percentage change, monthly', 'Civil aviation operating statistics, by type of service, Canadian air carriers, Levels I and II, quarterly', 'Civil aviation operating statistics, by sector, Canadian air carriers, Levels I and II, quarterly', 'Civil aviation financial statistics, Canadian air carriers, Levels I and II, quarterly', 'Civil aviation financial performance indicators, Canadian air carriers, Levels I and II, quarterly', 'Civil aviation productivity measures, Canadian air carriers, Levels I and II, quarterly', 'Weekly rail terminal performance indicator, Transport Canada', 'Weekly performance indicators of grain transportation by rail, Transport Canada', 'Weekly rail system performance indicators, by commodities, Transport Canada', 'Weekly rail system performance indicator, by type of rail car, Transport Canada', 'Flows and stocks of fixed non-residential and residential capital, by sector and asset, provincial and territorial', 'Gross domestic product, income-based, quarterly', 'Gross domestic product, expenditure-based, Canada, quarterly', 'Gross national income and gross domestic income, indexes and related statistics, quarterly', 'Gross domestic product price indexes, quarterly', 'Household final consumption expenditure, quarterly, Canada', 'Gross fixed capital formation, quarterly, Canada', 'Investment in inventories, quarterly, Canada', 'Current and capital accounts - National, Canada, quarterly', 'Current and capital accounts - Households, Canada, quarterly', 'Compensation of employees, Canada, quarterly', 'Current and capital accounts - Non-profit institutions serving households, Canada, quarterly', 'Current and capital accounts - Corporations, Canada, quarterly', 'Undistributed corporation profits', 'Current and capital accounts - General governments, Canada, quarterly', 'Current and capital accounts - Non-residents, Canada, quarterly', 'Gross domestic income, gross national income and net national income, Canada, quarterly', 'Gross domestic product, expenditure-based, at 2012 constant prices, quarterly', 'Detailed household final consumption expenditure, Canada, quarterly', 'Corporation profits before taxes, on an original-cost-basis, excluding government business enterprises, Canada, quarterly', 'Property income of households, Canada', 'General governments final consumption expenditure, Canada, quarterly', 'Contributions to annual percent change in real expenditure-based gross domestic product, Canada, annual', 'Gross national income and gross domestic income, indexes and related statistics, annual', 'Gross domestic product price indexes, annual (2012=100)', 'Contributions to annual percent change in real household final consumption expenditure, Canada, annual', 'Contributions to annual percent change in real gross fixed capital formation, Canada, annual', 'Contributions to annual percent change in real general governments final consumption expenditure, Canada, annual', "Wages, salaries and employers' social contributions", 'Gross domestic product, expenditure-based, at 2012 constant prices, annual', 'Gross domestic product (GDP) at basic prices, by industry, monthly']


问:
Unable to Delete File while starting Browser session while using maven selenium plugin

pom.xml looks like

```<code><build>
    <plugins>
        <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>selenium-maven-plugin</artifactId>
                <version>1.0</version>
                <executions>
                    <execution>
                        <phase>pre-integration-test</phase>
                        <goals>
                            <goal>start-server</goal>
                        </goals>
                        <configuration>
                            <background>true</background>
                            <logOutput>true</logOutput>
                            <browserSessionReuse>true</browserSessionReuse>
                        </configuration>
                </execution>
            </executions>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <configuration>
                <!-- Skip the normal tests, we'll run them in the integration-test phase -->
                <skip>true</skip>
            </configuration>

            <executions>
                  <execution>
                    <id>integration-tests</id>
                    <phase>integration-test</phase>
                    <goals>
                        <goal>test</goal>
                    </goals>
                    <configuration>
                        <skip>false</skip>
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>
</code>```

JUnit TestCase

```<code>@Before
public void setUp() throws Exception {

    selenium = new DefaultSelenium("localhost", 4444, "*firefox", "http://www.google.co.in/");
    selenium.start();
}

@Test
public void testUntitled() throws Exception {
    selenium.open("/");
    selenium.type("q", "Selenium Sucks");
}

@After
public void tearDown() throws Exception {
    selenium.stop();
}
</code>```

I get this error message while executing goal 'mvn integration-test' I have simple testcase which opens firefox browser and search for sometext in Googe search Bar.

As of now i also have reinstalled firefox browser but it again fails .

Exception :
    java.lang.RuntimeException: Could not start Selenium session: Failed to start new browser session: Unable to delete file C:\DOCUME~1\ADMINI~1\LOCALS~1\Temp\customProfileDirb66b3e06cba84cc1b55eb72a418a5c61\parent.lock
        at com.thoughtworks.selenium.DefaultSelenium.start(DefaultSelenium.java:89)
        at org.argus.selenium.timepass.TestSelenium.setUp(TestSelenium.java:16)

Am i missing something in configuration or while running the mvn goal.

答:
Guys Funny and Weird....
just make change to pom.xml

```<code><plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>selenium-maven-plugin</artifactId>
            <version>1.0</version>
            <executions>
                <execution>
                    <phase>pre-integration-test</phase>
                    <goals>
                        <goal>start-server</goal>
                    </goals>
                    <configuration>
                        <background>true</background>
                        <logOutput>true</logOutput>
                        <browserSessionReuse>true</browserSessionReuse>
                    </configuration>
            </execution>
        </executions>
    </plugin>
</code>```

Change the version number to 1.0.1
It should look like

```<code><plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>selenium-maven-plugin</artifactId>
            <version>1.0.1</version>
            <executions>
                <execution>
                    <phase>pre-integration-test</phase>
                    <goals>
                        <goal>start-server</goal>
                    </goals>
                    <configuration>
                        <background>true</background>
                        <logOutput>true</logOutput>
                        <browserSessionReuse>true</browserSessionReuse>
                    </configuration>
            </execution>
        </executions>
    </plugin>
</code>```

This should work.

Thanks everyone :)

Body:
pom.xml looks like

<build>
    <plugins>
        <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>selenium-maven-plugin</artifactId>
                <version>1.0</version>
                <executions>
                    <execution>
                        <phase>pre-integration-test</phase>
                        <goals>
                            <goal>start-server</goal>
                        </goals>
                        <configuration>
                            <background>true</background>
                            <logOutput>true</logOutput>
                            <browserSessionReuse>true</browserSessionReuse>
                        </configuration>
                </execution>
            </executions>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <configuration>

                <skip>true</skip>
            </configuration>

            <executions>
                  <execution>
                    <id>integration-tests</id>
                    <phase>integration-test</phase>
                    <goals>
                        <goal>test</goal>
                    </goals>
                    <configuration>
                        <skip>false</skip>
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

JUnit TestCase

@Before
public void setUp() throws Exception {

    selenium = new DefaultSelenium("localhost", 4444, "*firefox", "http://www.google.co.in/");
    selenium.start();
}

@Test
public void testUntitled() throws Exception {
    selenium.open("/");
    selenium.type("q", "Selenium Sucks");
}

@After
public void tearDown() throws Exception {
    selenium.stop();
}

I get this error message while executing goal 'mvn integration-test' I have simple testcase which opens firefox browser and search for sometext in Googe search Bar.

As of now i also have reinstalled firefox browser but it again fails .

Exception :
    java.lang.RuntimeException: Could not start Selenium session: Failed to start new browser session: Unable to delete file C:\DOCUME~1\ADMINI~1\LOCALS~1\Temp\customProfileDirb66b3e06cba84cc1b55eb72a418a5c61\parent.lock
        at com.thoughtworks.selenium.DefaultSelenium.start(DefaultSelenium.java:89)
        at org.argus.selenium.timepass.TestSelenium.setUp(TestSelenium.java:16)

Am i missing something in configuration or while running the mvn goal.

Body:
Guys Funny and Weird....
just make change to pom.xml

<plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>selenium-maven-plugin</artifactId>
            <version>1.0</version>
            <executions>
                <execution>
                    <phase>pre-integration-test</phase>
                    <goals>
                        <goal>start-server</goal>
                    </goals>
                    <configuration>
                        <background>true</background>
                        <logOutput>true</logOutput>
                        <browserSessionReuse>true</browserSessionReuse>
                    </configuration>
            </execution>
        </executions>
    </plugin>

Change the version number to 1.0.1
It should look like

<plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>selenium-maven-plugin</artifactId>
            <version>1.0.1</version>
            <executions>
                <execution>
                    <phase>pre-integration-test</phase>
                    <goals>
                        <goal>start-server</goal>
                    </goals>
                    <configuration>
                        <background>true</background>
                        <logOutput>true</logOutput>
                        <browserSessionReuse>true</browserSessionReuse>
                    </configuration>
            </execution>
        </executions>
    </plugin>

This should work.

Thanks everyone :)


问:
AWS throttling for Code Commit
I am getting below error when I'm doing git operations on a Code Commit repository. The number of operations is in the range of tens in few minutes - adding/removing/pulling files.

Is this because of AWS throttling or something else?
If so, what's the limit and how do I increase it in AWS?

"interim_desc": "RequestId: 12e27770db854bf0a6034cd6f851717d. 'git fetch origin --depth 20' returned with exit code 128.
error: RPC failed; HTTP 429 curl 22 The requested URL returned error: 429 Too Many Requests: The remote end hung up unexpectedly'"

答:
Here is the manual how to handle 429 error while accessing CodeCommit:

Access error: “Rate Exceeded” or “429” message when connecting to a CodeCommit repository
https://docs.aws.amazon.com/codecommit/latest/userguide/troubleshooting-ae.html#troubleshooting-ae3

I would copy here the most noteable part:

Implement jitter in requests, particularly in periodic polling requests.
If you have an application that is polling CodeCommit periodically and this application is running on multiple Amazon EC2 instances, introduce jitter (a random amount of delay) so that different Amazon EC2 instances do not poll at the same second. We recommend a random number from 0 to 59 seconds to evenly distribute polling mechanisms across a one-minute timeframe.

......

Request a CodeCommit service quota increase in the AWS Support Center.
To receive a service limit increase, you must confirm that you have already followed the suggestions offered here, including implementation of error retries or exponential backoff methods. In your request, you must also provide the AWS Region, AWS account, and timeframe affected by the throttling issues.

Title: AWS throttling for Code Commit


问:
CSS: Is there a way to apply inherited padding as negative margin?
Context

I'm using React and  must be clickable with <Link> of react-router-dom. Padding of  changes when I resize browser window because it uses css framework named Carbon. I have to <Link> =  tag to fit width/height of . It means that when I click , hyperlink has to work as expected.

Problem

It can bo solved by negative margin, and it should be same with padding. But, padding is dynamic. Therefore, I want to use inherited padding as negative margin.

     link

```

<pre class="lang-css prettyprint-override"><code>a {
  padding: inherit;
  margin: <negative of inherited padding>
}
</code>```

I cannot know padding of parent because it is dynamic. Actually, my real code is from https://react.carbondesignsystem.com/?path=/story/datatable--default which is framework I'm using.

How can I solve it?

答:
Use CSS variables to define the padding:

.box {
  --p:20px;
  padding:var(--p);
  display:inline-block;
  border:1px solid;
}

.box > a {
  margin:calc(-1*var(--p));
  padding:inherit;
  display:block;
  background:red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="box"> link</div>
<div class="box" style="--p:30px;"> link</div>
<div class="box" style="--p:10px;"> link</div></code>```

Body:
Context

I'm using React and  must be clickable with <Link> of react-router-dom. Padding of  changes when I resize browser window because it uses css framework named Carbon. I have to <Link> =  tag to fit width/height of . It means that when I click , hyperlink has to work as expected.

Problem

It can bo solved by negative margin, and it should be same with padding. But, padding is dynamic. Therefore, I want to use inherited padding as negative margin.

     link

a {
  padding: inherit;
  margin: <negative of inherited padding>
}

I cannot know padding of parent because it is dynamic. Actually, my real code is from https://react.carbondesignsystem.com/?path=/story/datatable--default which is framework I'm using.

How can I solve it?

Body:
Use CSS variables to define the padding:

.box {
  --p:20px;
  padding:var(--p);
  display:inline-block;
  border:1px solid;
}

.box > a {
  margin:calc(-1*var(--p));
  padding:inherit;
  display:block;
  background:red;
}

<div class="box"><a href=""> link</a></div>
<div class="box" style="--p:30px;"><a href=""> link</a></div>
<div class="box" style="--p:10px;"><a href=""> link</a></div>