问:
Broadcast receiver and Service don't work when applicaton close (android)
Sory everyone. Firstly my receiver doesnt work when application is closed on my devices because of AUTO START MANAGER. I feel stupid... And I learned very important things when I was trying to solve it.

Firstly Android 6.0 Permission Request
Broadcast Receivers not working in Android 6.0 Marshmallow

Secondly: Android - duplicated phone state broadcast on Lollipop

http://www.skoumal.net/en/android-duplicated-phone-state-broadcast-on-lollipop/

Thanks...

I'm new on Android and I want to learn BroadcastReceiver&Service. This codes BroadcastReceiver listen offhook and idle state my phone and send intent Service do something. While application running everything normal. After close application BroadcastReceiver and Service don't work.

Update: Also I notice while application run and everythng normal, sevice were started twice and stopped twice.

I see this messages while service is starting:

Toast.makeText(context, "" +phoneState +" " +record, Toast.LENGTH_SHORT).show();

Toast.makeText(getApplicationContext(), "service work", Toast.LENGTH_SHORT).show();

again 1. Toast.makeText(context, "" +phoneState +" " +record, Toast.LENGTH_SHORT).show();

again 2. Toast.makeText(getApplicationContext(), "service work", Toast.LENGTH_SHORT).show()

I see this messages while service is stoping:

Toast.makeText(context, "" +phoneState +" " +record, Toast.LENGTH_SHORT).show();

Toast.makeText(getApplicationContext(), "service will be stopped.", Toast.LENGTH_SHORT).show();

again 1. Toast.makeText(context, "" +phoneState +" " +record, Toast.LENGTH_SHORT).show();

again 2.  Toast.makeText(getApplicationContext(), "service will be stopped.", Toast.LENGTH_SHORT).show();

Everything repeat.

Manifest:

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="devapp.deneme">

    <uses-permission android:name="android.permission.READ_PHONE_STATE"/>
    <uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:enabled="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <service
            android:name=".MyService"
            android:enabled="true"
            android:exported="true" />

        <receiver
            android:name="devapp.deneme.MyReceiver"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.NEW_OUTGOING_CALL"/>
                <action android:name="android.intent.action.PHONE_STATE"/>
            </intent-filter>
        </receiver>
    </application>

</manifest>
</code>```

Broadcast Receiver

```<code>package devapp.deneme;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.widget.Toast;

public class MyReceiver extends BroadcastReceiver {

    public MyReceiver(){

    }

    Intent service = null;
    Bundle bundle = null;
    String phoneState = null;
    boolean record = false;

    @Override
    public void onReceive(Context context, Intent intent) {

        service = new Intent(context, MyService.class);
        bundle = intent.getExtras();
        phoneState = bundle.getString(TelephonyManager.EXTRA_STATE);

        if (phoneState!=null){
            if ((phoneState.equals(TelephonyManager.EXTRA_STATE_OFFHOOK))||(phoneState.equals(TelephonyManager.EXTRA_STATE_IDLE))){
                service.putExtra("durum", phoneState);
                if (phoneState.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)) {
                    record = true;
                }
                else {
                    record = false;
                }
            }
            service.putExtra("record",record);
            Toast.makeText(context, "" +phoneState +" " +record, Toast.LENGTH_SHORT).show();
            context.startService(service);
        }
    }
}
</code>```

Service

```<code>package devapp.deneme;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;

public class MyService extends Service {
    public MyService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    public int onStartCommand (Intent intent, int flags, int startId){

        boolean record = intent.getBooleanExtra("record", false);
        if (record) {
            Toast.makeText(getApplicationContext(), "service work", Toast.LENGTH_SHORT).show();
        }
        else {
            Toast.makeText(getApplicationContext(), "service will be stopped.", Toast.LENGTH_SHORT).show();
            stopSelf();
        }
        return super.onStartCommand(intent, flags, startId);
    }
}
</code>```

答:
You have to add the following in service class</p>

```<code>    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

           // your business logic

        return START_STICKY;
}
</code>```

Body:
Sory everyone. Firstly my receiver doesnt work when application is closed on my devices because of AUTO START MANAGER. I feel stupid... And I learned very important things when I was trying to solve it.

Firstly Android 6.0 Permission Request
Broadcast Receivers not working in Android 6.0 Marshmallow

Secondly: Android - duplicated phone state broadcast on Lollipop

http://www.skoumal.net/en/android-duplicated-phone-state-broadcast-on-lollipop/

Thanks...

I'm new on Android and I want to learn BroadcastReceiver&Service. This codes BroadcastReceiver listen offhook and idle state my phone and send intent Service do something. While application running everything normal. After close application BroadcastReceiver and Service don't work.

Update: Also I notice while application run and everythng normal, sevice were started twice and stopped twice.

I see this messages while service is starting:

Toast.makeText(context, "" +phoneState +" " +record, Toast.LENGTH_SHORT).show();

Toast.makeText(getApplicationContext(), "service work", Toast.LENGTH_SHORT).show();

again 1. Toast.makeText(context, "" +phoneState +" " +record, Toast.LENGTH_SHORT).show();

again 2. Toast.makeText(getApplicationContext(), "service work", Toast.LENGTH_SHORT).show()

I see this messages while service is stoping:

Toast.makeText(context, "" +phoneState +" " +record, Toast.LENGTH_SHORT).show();

Toast.makeText(getApplicationContext(), "service will be stopped.", Toast.LENGTH_SHORT).show();

again 1. Toast.makeText(context, "" +phoneState +" " +record, Toast.LENGTH_SHORT).show();

again 2.  Toast.makeText(getApplicationContext(), "service will be stopped.", Toast.LENGTH_SHORT).show();

Everything repeat.

Manifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="devapp.deneme">

    <uses-permission android:name="android.permission.READ_PHONE_STATE"/>
    <uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:enabled="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <service
            android:name=".MyService"
            android:enabled="true"
            android:exported="true" />

        <receiver
            android:name="devapp.deneme.MyReceiver"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.NEW_OUTGOING_CALL"/>
                <action android:name="android.intent.action.PHONE_STATE"/>
            </intent-filter>
        </receiver>
    </application>

</manifest>

Broadcast Receiver

package devapp.deneme;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.widget.Toast;

public class MyReceiver extends BroadcastReceiver {

    public MyReceiver(){

    }

    Intent service = null;
    Bundle bundle = null;
    String phoneState = null;
    boolean record = false;

    @Override
    public void onReceive(Context context, Intent intent) {

        service = new Intent(context, MyService.class);
        bundle = intent.getExtras();
        phoneState = bundle.getString(TelephonyManager.EXTRA_STATE);

        if (phoneState!=null){
            if ((phoneState.equals(TelephonyManager.EXTRA_STATE_OFFHOOK))||(phoneState.equals(TelephonyManager.EXTRA_STATE_IDLE))){
                service.putExtra("durum", phoneState);
                if (phoneState.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)) {
                    record = true;
                }
                else {
                    record = false;
                }
            }
            service.putExtra("record",record);
            Toast.makeText(context, "" +phoneState +" " +record, Toast.LENGTH_SHORT).show();
            context.startService(service);
        }
    }
}

Service

package devapp.deneme;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;

public class MyService extends Service {
    public MyService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    public int onStartCommand (Intent intent, int flags, int startId){

        boolean record = intent.getBooleanExtra("record", false);
        if (record) {
            Toast.makeText(getApplicationContext(), "service work", Toast.LENGTH_SHORT).show();
        }
        else {
            Toast.makeText(getApplicationContext(), "service will be stopped.", Toast.LENGTH_SHORT).show();
            stopSelf();
        }
        return super.onStartCommand(intent, flags, startId);
    }
}

Body:
You have to add the following in service class

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

           // your business logic

        return START_STICKY;
}

ContentLicense: CC BY-SA 4.0


来源: stackexchange

问:
CSS3 support on browsers
Should I fully learn CSS3 from the W3 "CSS specifications" or is CSS3 not fully supported on browsers yet?

All in the title :)

答:
It is worth to learn. Even if will take some time until all browser supports the same things most browsers gives the possibility to user browser-based properties for css3 support. IE is the biggest problem is this field, but using scripts like css3pie then you can support css3 for internet explorer also. Some good sites offer you cross browser css3 are the following:

http://css3please.com/

http://css3generator.com/

Also visit http://www.css3.info to keep in touch with all news about css3. In any case worth.

ContentLicense: CC BY-SA 2.5

Title: CSS3 support on browsers


问:
How to inject FacesContext with JSF 2.3 and TomEE?
I've been trying to use JSF 2.3 with TomEE server and I'm having problems using the @Inject annotation with the FacesContext object.

When I use it, i get the following exception while starting my TomEE server:

```<code>SEVERE: CDI Beans module deployment failed
org.apache.webbeans.exception.WebBeansDeploymentException: javax.enterprise.inject.UnsatisfiedResolutionException: Api type [javax.faces.context.FacesContext] is not found with the qualifiers
Qualifiers: [@javax.enterprise.inject.Default()]
</code>```

Am I missing something?
Thanks.

答:
Seems like some JSF2.3 features must be activated by setting the used JSF version.

Try setting JSF version by adding this empty class:

```<code>    import javax.faces.annotation.FacesConfig;

/**
 * The presence of the @FacesConfig annotation on a managed bean deployed within an application enables version specific
 * features. In this case, it enables JSF CDI injection and EL resolution using CDI.
 *
 */
@FacesConfig(version = FacesConfig.Version.JSF_2_3)
public class ConfigurationBean {
}
</code>```

from https://github.com/javaee/glassfish/issues/22094

ContentLicense: CC BY-SA 3.0

Body:
I've been trying to use JSF 2.3 with TomEE server and I'm having problems using the @Inject annotation with the FacesContext object.

When I use it, i get the following exception while starting my TomEE server:

SEVERE: CDI Beans module deployment failed
org.apache.webbeans.exception.WebBeansDeploymentException: javax.enterprise.inject.UnsatisfiedResolutionException: Api type [javax.faces.context.FacesContext] is not found with the qualifiers
Qualifiers: [@javax.enterprise.inject.Default()]

Am I missing something?
Thanks.

Body:
Seems like some JSF2.3 features must be activated by setting the used JSF version.

Try setting JSF version by adding this empty class:

    import javax.faces.annotation.FacesConfig;

/**
 * The presence of the @FacesConfig annotation on a managed bean deployed within an application enables version specific
 * features. In this case, it enables JSF CDI injection and EL resolution using CDI.
 *
 */
@FacesConfig(version = FacesConfig.Version.JSF_2_3)
public class ConfigurationBean {
}

from https://github.com/javaee/glassfish/issues/22094


问:
How to read the JSON file in Angular 4 scripts
I need to read the JSON file which we have stored locally in the project workspace, because I need to read the component.ts file.

Are there any basic steps?

答:
It's simple. You can do directly in a component or using a service. It's better create a service to separate the logic of the application. (If in a future you'll want change the way to access to the data you only must to change the service)

Your service

```<code>@Injectable()
export class DataService {
    constructor(private http: HttpClient) { } //<-- inject HttpClient
    getData() {
        return this.http.get('../assets/data.json')
    }).catch(
        (error: Response) => {
        return Observable.throw(error);
    });
}
</code>```

Your Component

```<code>@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  constructor(private dataService:DataService){} //<--inject the service

  data:any //<--a variable
  ngOnInit(){
    this.dataService.getData().subscribe((data)=>
    {
         this.data=data
    }
}
</code>```

Remember, in your app.module declare the service

```<code>@NgModule({
   ...
   providers: [DataService,..]
}
</code>```

Of course you can do all in the component, but it's disapproved

Body:
It's simple. You can do directly in a component or using a service. It's better create a service to separate the logic of the application. (If in a future you'll want change the way to access to the data you only must to change the service)

Your service

@Injectable()
export class DataService {
    constructor(private http: HttpClient) { } //<-- inject HttpClient
    getData() {
        return this.http.get('../assets/data.json')
    }).catch(
        (error: Response) => {
        return Observable.throw(error);
    });
}

Your Component

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  constructor(private dataService:DataService){} //<--inject the service

  data:any //<--a variable
  ngOnInit(){
    this.dataService.getData().subscribe((data)=>
    {
         this.data=data
    }
}

Remember, in your app.module declare the service

@NgModule({
   ...
   providers: [DataService,..]
}

Of course you can do all in the component, but it's disapproved


问:
Split string by ". " except when after a number
I want to split strings, by phrases, and to do that I'm doing this:

```<code>string.Split(new[] { ". ", "? ", "! " }, StringSplitOptions.None);
</code>```

The thing is my string sometimes catch that after a number, when it has different points, and I want to separate by before the number, and not after, if it is possible.

original:

Com um processo de agendamento de não mais que 60 segundos, um
  pagamento seguro, garantia de qualidade, a Wegho torna-se o meio mais
  simples e conveniente de poder agendar serviços para o seu lar.
  Entenda-se lar como a simbiose perfeita do ativo físico “casa” e do
  ativo “emocional” família. Preparado para ter um parceiro de
  excelência nos serviços que precisa para o seu lar? 1.    Explore os
  nossos serviços em Wegho.om 2.    Selecione o serviço que pretende.
  Através do código postal verificaremos se estamos presentes na área
  que pretende 3.   Escolha uma hora

result:

Com um processo de agendamento de não mais que 60 segundos, um
  pagamento seguro, garantia de qualidade, a Wegho torna-se o meio mais
  simples e conveniente de poder agendar serviços para o seu lar.

Entenda-se lar como a simbiose perfeita do ativo físico “casa” e do
  ativo “emocional” família.

Preparado para ter um parceiro de excelência nos serviços que precisa
  para o seu lar?

Explore os nossos serviços em Wegho.om

Selecione o serviço que pretende. Através do código postal verificaremos se estamos presentes na área que pretende

Escolha uma hora

And also, is it possible to keep the caught separating characters from which the string was split in the strings?

答:
One approach is to split strings the way you do currently, and then go through the resultant list again, re-combining number-only strings with strings that immediately follow them:

```<code>var tokens = string.Split(new[] { ". ", "? ", "! " }, StringSplitOptions.None);
var res = new List<string>();
for (int i = 0 ; i < tokens.Length ; i++) {
    var tok = tokens[i];
    int ignore;
    if (i != tokens.Length-1 && int.TryParse(tok, out ignore)) {
        tok += ". "+tokens[++i];
    }
    res.Add(tok);
}
</code>```

Note that your overall approach is fragile, because it is not possible to tell if a numeric part is a "bullet number" or not without some user mark-up to help you identify numbered bullets.

Body:
I want to split strings, by phrases, and to do that I'm doing this:

string.Split(new[] { ". ", "? ", "! " }, StringSplitOptions.None);

The thing is my string sometimes catch that after a number, when it has different points, and I want to separate by before the number, and not after, if it is possible.

original:

Com um processo de agendamento de não mais que 60 segundos, um
  pagamento seguro, garantia de qualidade, a Wegho torna-se o meio mais
  simples e conveniente de poder agendar serviços para o seu lar.
  Entenda-se lar como a simbiose perfeita do ativo físico “casa” e do
  ativo “emocional” família. Preparado para ter um parceiro de
  excelência nos serviços que precisa para o seu lar? 1.    Explore os
  nossos serviços em Wegho.om 2.    Selecione o serviço que pretende.
  Através do código postal verificaremos se estamos presentes na área
  que pretende 3.   Escolha uma hora

result:

Com um processo de agendamento de não mais que 60 segundos, um
  pagamento seguro, garantia de qualidade, a Wegho torna-se o meio mais
  simples e conveniente de poder agendar serviços para o seu lar.

Entenda-se lar como a simbiose perfeita do ativo físico “casa” e do
  ativo “emocional” família.

Preparado para ter um parceiro de excelência nos serviços que precisa
  para o seu lar?

Explore os nossos serviços em Wegho.om

Selecione o serviço que pretende. Através do código postal verificaremos se estamos presentes na área que pretende

Escolha uma hora

And also, is it possible to keep the caught separating characters from which the string was split in the strings?

Body:
One approach is to split strings the way you do currently, and then go through the resultant list again, re-combining number-only strings with strings that immediately follow them:

var tokens = string.Split(new[] { ". ", "? ", "! " }, StringSplitOptions.None);
var res = new List<string>();
for (int i = 0 ; i < tokens.Length ; i++) {
    var tok = tokens[i];
    int ignore;
    if (i != tokens.Length-1 && int.TryParse(tok, out ignore)) {
        tok += ". "+tokens[++i];
    }
    res.Add(tok);
}

Note that your overall approach is fragile, because it is not possible to tell if a numeric part is a "bullet number" or not without some user mark-up to help you identify numbered bullets.


问:
rawQuery() of sqlite throw IllegalArgumentException
My Query is :

```<code>Cursor cursor = dbReader.rawQuery("SELECT CategoryID FROM categories WHERE CategoryTitle = ?", new String[]{categoryTitle});
</code>```

this result error:

```<code><expr> expected, got '?'
</code>```

I changed it to :

```<code> Cursor cursor = dbReader.rawQuery("SELECT CategoryID FROM categories WHERE CategoryTitle = '?'", new String[]{categoryTitle});
</code>```

result exception:

```<code>java.lang.IllegalArgumentException: Cannot bind argument at index 1 because the index is out of range.  The statement has 0 parameters.
</code>```

but when changed to :

```<code>Cursor cursor = dbReader.rawQuery("SELECT CategoryID FROM categories WHERE CategoryTitle = '"+ categoryTitle+ "'", new String[]{});
</code>```

it work with me....
What is the wrong in the two above query?

This screenshot for first query

答:
"SELECT CategoryID FROM categories WHERE CategoryTitle = ?" is a valid query.

Android Studio is not validating it as plain SQL but as Room SQL.

Room uses different placeholders and the query would look like this:

"SELECT CategoryID FROM categories WHERE CategoryTitle = :title"

You are not using room, so do not change it.

Also see this bug report.

Body:
My Query is :

Cursor cursor = dbReader.rawQuery("SELECT CategoryID FROM categories WHERE CategoryTitle = ?", new String[]{categoryTitle});

this result error:

<expr> expected, got '?'

I changed it to :

 Cursor cursor = dbReader.rawQuery("SELECT CategoryID FROM categories WHERE CategoryTitle = '?'", new String[]{categoryTitle});

result exception:

java.lang.IllegalArgumentException: Cannot bind argument at index 1 because the index is out of range.  The statement has 0 parameters.

but when changed to :

Cursor cursor = dbReader.rawQuery("SELECT CategoryID FROM categories WHERE CategoryTitle = '"+ categoryTitle+ "'", new String[]{});

it work with me....
What is the wrong in the two above query?

This screenshot for first query


问:
Running ASP.NET core web app from .net core console app
Let's say I've created a solution with 2 projects: ASP.NET Core Web Application and .NET Core Console App.

Is there a way to reference and run web application from console app?

Specifically:

How do I publish a .Net Core console app to a web server running IIS?

答:
ASP.NET Core apps are console apps. Run the following in the command prompt in the project directory:

```<code>dotnet publish -o publish-output
</code>```

This will generate the shared publish files in a publish-output directory. You may now run it with:

```<code>dotnet project-name.dll
</code>```

Once you run it, it will accept requests on a configured port. IIS (or any other server) can now be configured to work as a reverse proxy. You'd typically create a website in IIS, and move the files from the publish-output to the website's IIS directory and configure IIS to act as a reverse proxy to it.

Follow the instructions at Microsoft Docs here.

Body:
ASP.NET Core apps are console apps. Run the following in the command prompt in the project directory:

dotnet publish -o publish-output

This will generate the shared publish files in a publish-output directory. You may now run it with:

dotnet project-name.dll

Once you run it, it will accept requests on a configured port. IIS (or any other server) can now be configured to work as a reverse proxy. You'd typically create a website in IIS, and move the files from the publish-output to the website's IIS directory and configure IIS to act as a reverse proxy to it.

Follow the instructions at Microsoft Docs here.


问:
If the DB connection fails, how can I tell PHP to pause a second and try again?
Every once in awhile, for about a second or two, my PHP script fails to authenticate and create a connection to MySQL server. Is there any way to tell PHP to, upon failure to create a MySQL connection, wait another second or two and then try again?

Do I need to limit the number of re-tries, or will the PHP script automatically quit after the HTTP connection is closed?

Thanks for your help!

答:
With something like this:</p>

```<code><?php
$maxret = 10;
$db = false;
do
{
  $db = mysql_connect(....);
  if ($db !== false) break;

  sleep(2);
}while($maxret-- > 0);

if ($db === false){
   //Handle db error here. For instance you can redirect the browser to a courtesy page
   header("Location:/dbdown.php");
   exit;
}
?>
</code>```

Body:
With something like this:

<?php
$maxret = 10;
$db = false;
do
{
  $db = mysql_connect(....);
  if ($db !== false) break;

  sleep(2);
}while($maxret-- > 0);

if ($db === false){
   //Handle db error here. For instance you can redirect the browser to a courtesy page
   header("Location:/dbdown.php");
   exit;
}
?>


问:
Executing query with parameters
I want to execute a .sql script from C#. Basically the script inserts a row into few different tables.

The point is I have values in C# code that I need to pass to the .sql query. These values will be collected during program execution.

Here is the query that I want to execute from C# code:

```<code>INSERT INTO [DB].[dbo].[User]
           ([Id]
           ,[AccountId]
           ,[FirstName]
           ,[LastName]
           ,[JobTitle]
           ,[PhoneNumber]
          )
     VALUES
           ('00A640BD-1A0D-499D-9155-BA2B626D7B68'
           ,'DCBA241B-2B06-48D7-9AC1-6E277FBB1C2A'
           ,'Mark'
           ,'Wahlberg'
           ,'Actor'
           ,'9889898989'])
GO
</code>```

The values will vary from time to time i.e., they are captured in C# code and need to be passed.

Can anyone please help me do this..I am learning both C# and SQL. Thanks a lot.

答:
Frankly, ADO.NET makes it hard to do things like this correctly. Tools like Dapper exist to make that easier:

```<code>dbConn.Execute(
     @"insert into [DB].[dbo].[User] ( [Id], [AccountId], [FirstName], [LastName],
                                       [JobTitle], [PhoneNumber] )
       values ( @id, @accountId, @firstName, @lastName, @jobTitle, @phoneNumber )",
       new { id, accountId, firstName, lastName, jobTitle, phoneNumber });
</code>```

This will deal with all the parameterization for you, efficiently, effectively, and safely.

There are similar APIs for executing queries and populating objects.

Title: Executing query with parameters

Body:
I want to execute a .sql script from C#. Basically the script inserts a row into few different tables.

The point is I have values in C# code that I need to pass to the .sql query. These values will be collected during program execution.

Here is the query that I want to execute from C# code:

INSERT INTO [DB].[dbo].[User]
           ([Id]
           ,[AccountId]
           ,[FirstName]
           ,[LastName]
           ,[JobTitle]
           ,[PhoneNumber]
          )
     VALUES
           ('00A640BD-1A0D-499D-9155-BA2B626D7B68'
           ,'DCBA241B-2B06-48D7-9AC1-6E277FBB1C2A'
           ,'Mark'
           ,'Wahlberg'
           ,'Actor'
           ,'9889898989'])
GO

The values will vary from time to time i.e., they are captured in C# code and need to be passed.

Can anyone please help me do this..I am learning both C# and SQL. Thanks a lot.

Body:
Frankly, ADO.NET makes it hard to do things like this correctly. Tools like Dapper exist to make that easier:

dbConn.Execute(
     @"insert into [DB].[dbo].[User] ( [Id], [AccountId], [FirstName], [LastName],
                                       [JobTitle], [PhoneNumber] )
       values ( @id, @accountId, @firstName, @lastName, @jobTitle, @phoneNumber )",
       new { id, accountId, firstName, lastName, jobTitle, phoneNumber });

This will deal with all the parameterization for you, efficiently, effectively, and safely.

There are similar APIs for executing queries and populating objects.


问:
How to get pointer to child from method returning pointer to parent

Context

The context is composed by three classes:

abstract parent (e.g. Player)

child (e.g. TapePlayer)

a holder (e.g. MyMachine)

The holder has a member variable that is a shared_ptr<...> to the parent class and a setter for it accepts shared_ptr<...>s of children classes.

My getter looks something like this

```<code>shared_ptr<Parent>  getChildPtr() {
    return parentPtr;
  };
</code>```

but it returns a pointer to the parent, and cannot access child methods.

If I want to do something like the following

```<code>holder.getChildPtr()->childMethod();
// ERROR! No member named 'childMethod' in 'Parent'
</code>```

How should I implement the getter to get the pointer to the child instead of the parent class?

Code

The whole code looks something like this:

```<code>class Player {
public:
  Player(){};
  virtual ~Player{};

  virtual void play() = 0;
}

class TapePlayer : public Player {
public:
  TapePlayer(){};
  virtual ~TapePlayer{};

  void play() { ... };
  void rewind() { ... };
}

class MyMachine {
public:
  MyMachine(); //
  ~MyMachine();

  void setPlayer(shared_ptr<Player> p) {
    playerPtr = p;
  }

  shared_ptr<Player>  getPlayer() {
    return playerPtr;
  };

private:
  shared_ptr<Player>  playerPtr;
}

MyMachine machine; // the holder

shared_ptr<TapePlayer> tapePtr(new TapePlayer()); // pointer to child

machine.setPlayer(tapePtr); // set holder with pointer to child

machine.getPlayer()->rewind(); // -- ERROR! No member named 'rewind' in 'Player'
// if I want to get the player of that machine to rewind I need
// to dynamic_cast<TapePlayer>() ...
</code>```

I'm pretty sure there's a better way of doing this than casting to children types.  Any ideas?

EDIT

This was a very simplified example.  What I'm actually trying to do is this:

My holder class is named Clip.  A clip plays something, be it an
  image, a video, a sequence of images, some kind of processing with
  OpenCv, a vector shape...  anything that can be displayed.

All these types of things are Players.

I don't care what type of player the  clip holds.  I just want it to show it to me.  But, some players need tweaking at runtime, like the OpenCv one, that needs tweaking parameters for optimal processing.  I cannot implement all methods of all subclasses in the parent class, that would make no sense to me. Why does a video need to have the methods for tweaking OpenCv parameters?

All I need is that both have 'playable' methods, and be able to store them in a map<string, PlayerPtr> to access them at any time or change the player the clip is holding.

答:
The point is that this kind of ruins the polymorphism - even with dynamic_cast, you still need to check that the result is not 0 (i.e. check the actual type) and as you might already know, dynamic_cast is famous for being very slow (and requiring RTTI information built in the executable).

Is there any reason you couldn't add a pure virtual rewind() method to your Player interface? Then you'd just call it and the inherited class could do whatever it decides in that case. Other subclasses might implement it as empty (or it can be even empty by default in the Player itself, so that the subclasses do not have to implement it if they don't need to). Perhaps even some more "generic" virtual function like reset(), restart() etc. which would just call rewind() for the TapePlayer under the hood.

You can of course go even more fancy with more complex solutions like visitor/observer (TapePlayer being RewindObserver and observing a rewind event) etc.

EDIT:

So to address the edit comments - if the different types need tweaking, then again, you can just have a single virtual method tweak() (pure or with default empty impl) and do whatever tweaking is needed. Otherwise you'd anyway end up with a long list of ifs and call tweak methods depending on the actual type.

If the tweaking requires some special parameters, then the situation can be difficult ... one option could be to have a tweaking parameters interface (and call the tweak method with that), but if the params can't be unified you'd need a dynamic cast in the tweak method anyway to cast to the correct params type (this basically leads to double dispatch which in C++ requires casting at some point) ... but anyway that would still require to create different param classes in the calling site which is not that nice.

It also depends when you actually need to setup the tweaking parameters - if it is enough to setup everything when creating the instance (and the tweaking params do not change afterwards), or if it is needed to change them later on. If only needed to setup at startup, then you can have factory classes for the different object types and the factory can setup the params.

(technically you could handle even the necessity of changing the params a similar way, by keeping the setting object types for various player types, the players would keep reference to them as well, assigned when the objects are created, and once they need to be changed, you'd change the settings and call tweak() or update() or similar func to inform the objects that some setting changed and needs to be re-applied)

Body:
Context

The context is composed by three classes:

abstract parent (e.g. Player)

child (e.g. TapePlayer)

a holder (e.g. MyMachine)

The holder has a member variable that is a shared_ptr<...> to the parent class and a setter for it accepts shared_ptr<...>s of children classes.

My getter looks something like this

shared_ptr<Parent>  getChildPtr() {
    return parentPtr;
  };

but it returns a pointer to the parent, and cannot access child methods.

If I want to do something like the following

holder.getChildPtr()->childMethod();
// ERROR! No member named 'childMethod' in 'Parent'

How should I implement the getter to get the pointer to the child instead of the parent class?

Code

The whole code looks something like this:

class Player {
public:
  Player(){};
  virtual ~Player{};

  virtual void play() = 0;
}

class TapePlayer : public Player {
public:
  TapePlayer(){};
  virtual ~TapePlayer{};

  void play() { ... };
  void rewind() { ... };
}

class MyMachine {
public:
  MyMachine(); //
  ~MyMachine();

  void setPlayer(shared_ptr<Player> p) {
    playerPtr = p;
  }

  shared_ptr<Player>  getPlayer() {
    return playerPtr;
  };

private:
  shared_ptr<Player>  playerPtr;
}

MyMachine machine; // the holder

shared_ptr<TapePlayer> tapePtr(new TapePlayer()); // pointer to child

machine.setPlayer(tapePtr); // set holder with pointer to child

machine.getPlayer()->rewind(); // -- ERROR! No member named 'rewind' in 'Player'
// if I want to get the player of that machine to rewind I need
// to dynamic_cast<TapePlayer>() ...

I'm pretty sure there's a better way of doing this than casting to children types.  Any ideas?

EDIT

This was a very simplified example.  What I'm actually trying to do is this:

My holder class is named Clip.  A clip plays something, be it an
  image, a video, a sequence of images, some kind of processing with
  OpenCv, a vector shape...  anything that can be displayed.

All these types of things are Players.

I don't care what type of player the  clip holds.  I just want it to show it to me.  But, some players need tweaking at runtime, like the OpenCv one, that needs tweaking parameters for optimal processing.  I cannot implement all methods of all subclasses in the parent class, that would make no sense to me. Why does a video need to have the methods for tweaking OpenCv parameters?

All I need is that both have 'playable' methods, and be able to store them in a map<string, PlayerPtr> to access them at any time or change the player the clip is holding.


问:
Find elements in group by result use SQL
I have a table contain event log, schema:

```<code>userid, event, timestamp
</code>```

I want group by userid and find that user have specific event

ex.

```<code>userid, events
A, "open, click, remove, restart"
</code>```

so I want make group by result as a string / array

is there any way can do this?

thanks!

答:
You can achieve this with the group_concat function in BigQuery.

```<code>select userid, group_concat(event, ', ') as events
from EventLog
group by userid;
</code>```

You also briefly mention that you would like to find users that have specific events, you can add that in as part of the where clause, but as you did not give any example of how you are looking to narrow it down, I have omitted that portion. If you can give a more specific case example of what you are looking for, I can update my answer to reflect that.

Body:
I have a table contain event log, schema:

userid, event, timestamp

I want group by userid and find that user have specific event

ex.

userid, events
A, "open, click, remove, restart"

so I want make group by result as a string / array

is there any way can do this?

thanks!

Body:
You can achieve this with the group_concat function in BigQuery.

select userid, group_concat(event, ', ') as events
from EventLog
group by userid;

You also briefly mention that you would like to find users that have specific events, you can add that in as part of the where clause, but as you did not give any example of how you are looking to narrow it down, I have omitted that portion. If you can give a more specific case example of what you are looking for, I can update my answer to reflect that.


问:
How Can make this JSX compact?
```<code>{
  this.state.isLoadingInputDropDown &&
  <option value="-1" disabled >Loading...</option >
}

{/* TODO : was not able to combine below statements */}
{
  !this.state.isLoadingInputDropDown
  && <option value="-1" >--Select a Accessorial Charge first --</option>
}
{
  !this.state.isLoadingInputDropDown
  && this.state.allInputs.length > 0
  && this.state.allInputs.map(
    (input) => (<option value={input.id} key={input.id}>{input.name}</option>)
  )
}
</code>```

trying to make this JSX one-liner or something compact.
I tried every possible (which I can think of) structure

答:
You could do something like this;</p>

```<code>return (
    <select>
        {this.state.isLoadingInputDropDown
            ? <option value="-1" disabled >Loading...</option>
            : [{ id: -1, name: '--Select a Accessorial Charge first --'}, ...this.state.allInputs].map(
                (input) => (<option value={input.id} key={input.id}>{input.name}</option>)
            )}
    </select>
)
</code>```

Title: How Can make this JSX compact?

Body:
{
  this.state.isLoadingInputDropDown &&
  <option value="-1" disabled >Loading...</option >
}

{/* TODO : was not able to combine below statements */}
{
  !this.state.isLoadingInputDropDown
  && <option value="-1" >--Select a Accessorial Charge first --</option>
}
{
  !this.state.isLoadingInputDropDown
  && this.state.allInputs.length > 0
  && this.state.allInputs.map(
    (input) => (<option value={input.id} key={input.id}>{input.name}</option>)
  )
}

trying to make this JSX one-liner or something compact.
I tried every possible (which I can think of) structure

Body:
You could do something like this;

return (
    <select>
        {this.state.isLoadingInputDropDown
            ? <option value="-1" disabled >Loading...</option>
            : [{ id: -1, name: '--Select a Accessorial Charge first --'}, ...this.state.allInputs].map(
                (input) => (<option value={input.id} key={input.id}>{input.name}</option>)
            )}
    </select>
)


问:
ActiveMerchant: How to authorise cards when using gateways that do not support the void operation?
I am working on the billing component of a Ruby on Rails application using ActiveMerchant. The payment gateway we have chosen is PaymentExpress.

Code examples I am seeing such as the one below, use authorize() and void() to test the validity of a card:

```<code>def test_card!
  auth_response = gateway.authorize(100, card)
  gateway.void(auth_response.authorization) if auth_response.success?
  raise AuthorizationFailed.new(auth_response) unless auth_response.success?
end
</code>```

However, PaymentExpress does not support the void action. Is there an alternate way to perform this authorisation action, or is it OK to leave out the void action, considering gateways such as PaymentExpress expire the authorisation request after 7 days?

I can find no mention of voiding an authorisation in the documentation or Google, nor can I find any indication of how important it is.

Some help?

答:
Some card processors will flag a transaction like this as potential fraud. They don't like to see small test transactions followed by larger transactions. American Express in particular is somewhat aggressive in this regard as they will tend to decline the transaction when you go back and try for the real amount.

If you plan on charging a customer for amount x, then you should authorize it for amount x to validate the card. Then you can use the previous authorization and do a capture or force-post to finalize the charge. This way, the customer will only ever see the right amount pending & settled on their statement.

OwnerDisplayName: bjeanes

Body:
I am working on the billing component of a Ruby on Rails application using ActiveMerchant. The payment gateway we have chosen is PaymentExpress.

Code examples I am seeing such as the one below, use authorize() and void() to test the validity of a card:

def test_card!
  auth_response = gateway.authorize(100, card)
  gateway.void(auth_response.authorization) if auth_response.success?
  raise AuthorizationFailed.new(auth_response) unless auth_response.success?
end

However, PaymentExpress does not support the void action. Is there an alternate way to perform this authorisation action, or is it OK to leave out the void action, considering gateways such as PaymentExpress expire the authorisation request after 7 days?

I can find no mention of voiding an authorisation in the documentation or Google, nor can I find any indication of how important it is.

Some help?

OwnerDisplayName: Matt Haley


问:
Offline Android Dev Guide
I was wondering if there exists/anyone has compiled a download of the Android Dev Guide and/or the class reference pages

The pages I'm referring to are:

(the dev guide)
http://developer.android.com/guide/basics/what-is-android.html

(the class reference)
http://developer.android.com/reference/android/package-summary.html

Would be quite helpful!

Thanks

答: yeah,it is at this path adnroid_sdk/docs,i found it</p>

Title: Offline Android Dev Guide


问:
using python commenting xml tags
for the below xml file , how can i comment(in xml) the heading tag including its children using python ? i am new to python , tried using lxml but only able to add a new comment, not able to comment existing tags. please do help , thanks in advance

```<code><note>
<to>Tove</to>
<from>Jani</from>
<heading> Reminder
    <security>level  1</security>
</heading>
<body>Don't forget me this weekend!</body>
</note>
</code>```

i would want the output to be like

```<code><note>
<to>Tove</to>
<from>Jani</from>
<!--  <heading> Reminder
    <security>level  1</security>
</heading> -->
<body>Don't forget me this weekend!</body>
</note>
</code>```

答:
Comments in Python start with the hash character, #, and extend to
  the end of the physical line. A comment may appear at the start of a
  line or following whitespace or code, but not within a string literal.
  A hash character within a string literal is just a hash character.
  Since comments are to clarify code and are not interpreted by Python,
  they may be omitted when typing in examples.

```<code><note>
<to>Tove</to>
<from>Jani</from>
#<heading> Reminder
#    <security>level  1</security>
#</heading>
<body>Don't forget me this weekend!</body>
</note>
</code>```

Here is a link to An Informal Introduction to Python.

In case I'm am missing something in your question, here is some information about How to ask a question as well as How to create a Minimal, Complete, and Verifiable example plus the tour in case you haven't seen it yet.

Good Luck!

Title: using python commenting xml tags

Body:
for the below xml file , how can i comment(in xml) the heading tag including its children using python ? i am new to python , tried using lxml but only able to add a new comment, not able to comment existing tags. please do help , thanks in advance

<note>
<to>Tove</to>
<from>Jani</from>
<heading> Reminder
    <security>level  1</security>
</heading>
Don't forget me this weekend!
</note>

i would want the output to be like

<note>
<to>Tove</to>
<from>Jani</from>

Don't forget me this weekend!
</note>

Body:
Comments in Python start with the hash character, #, and extend to
  the end of the physical line. A comment may appear at the start of a
  line or following whitespace or code, but not within a string literal.
  A hash character within a string literal is just a hash character.
  Since comments are to clarify code and are not interpreted by Python,
  they may be omitted when typing in examples.

<note>
<to>Tove</to>
<from>Jani</from>
#<heading> Reminder
#    <security>level  1</security>
#</heading>
<body>Don't forget me this weekend!</body>
</note>

Here is a link to An Informal Introduction to Python.

In case I'm am missing something in your question, here is some information about How to ask a question as well as How to create a Minimal, Complete, and Verifiable example plus the tour in case you haven't seen it yet.

Good Luck!


问:
Jfrog Search & Delete Not Working
I am trying to search for all files that are in my repo on Artifactory. I have Go installed, and am using Jfrog to query the search using:

```<code>jfrog rt s https://URL/artifactory/generic-sgca/
</code>```

Which returns:

```<code>[Info] Searching artifacts...
[Info] Found 0 artifacts.
[]
</code>```

Why is it not returning all folders in this repo? I believe my config is setup correctly too.

答:
You are not supposed to be specifying the https://url/artifactory when using search function in the CLI.

you can check the CLI's search help using jfrog rt s -h and you'll see that the usage is:

```<code>jfrog rt s [command options] <search pattern>
</code>```

where search pattern should:

```<code>Specifies the search path in Artifactory, in the following format: <repository name>/<repository path>
</code>```

The URL is actually a command option --url=http://myurl:myport/artifactory  which you can leave out if you use jfrog rt config to set the Artifactory server details before you run the search command.

You can read more and find some snippet example here

Title: Jfrog Search & Delete Not Working

Body:
I am trying to search for all files that are in my repo on Artifactory. I have Go installed, and am using Jfrog to query the search using:

jfrog rt s https://URL/artifactory/generic-sgca/

Which returns:

[Info] Searching artifacts...
[Info] Found 0 artifacts.
[]

Why is it not returning all folders in this repo? I believe my config is setup correctly too.

Body:
You are not supposed to be specifying the https://url/artifactory when using search function in the CLI.

you can check the CLI's search help using jfrog rt s -h and you'll see that the usage is:

jfrog rt s [command options] <search pattern>

where search pattern should:

Specifies the search path in Artifactory, in the following format: <repository name>/<repository path>

The URL is actually a command option --url=http://myurl:myport/artifactory  which you can leave out if you use jfrog rt config to set the Artifactory server details before you run the search command.

You can read more and find some snippet example here


问:
NetBeans profiler - time is lost somewere?
I tried to profile my application using built-in NetBeans profiler. Result completely make sense, instead of one thing - sum of time for sub-methods and self-time of method is not equal to the value, which is displayed for method. I.e. self-time is 257ms, sub-methods - 110ms, and value for method is 1022. 1022 - 257 - 110 = 655ms. Can you tell me where this time is lost?</p>

答:
Is dynamic CPU frequency switching turned on? Try disabling it, rerun the profiler calibration and re-profile the project.

In case it doesn't help I would recommend filing an issue for profiler at http://netbeans.org/bugzilla/

Don't forget to attach the sample project (if possible).


问:
Codeigniter how to set form action url using form_open helper function
I am using Codeigniter with Bootstrap. This is my view code:

```<code><?php echo form_open('con_login/loginUser'); ?>
    <div class="bs-example">
        <div class="col-md-2">
            <label class="sr-only" for="username">Username</label>
            <input type="text" class="form-control" name="username" placeholder="Username" value="">
        </div>
        <div class="col-md-2">
            <label class="sr-only" for="password">Password</label>
            <input type="password" class="form-control" name="password" placeholder="Password" value="">
        </div>
        <button type="submit" class="btn btn-default" name="login" value="login">Sign in</button>
    </div>
    <?php echo form_close(); ?>
</code>```

The code for the called function which is in the controller is:

```<code>public function loginUser() {
    $username = $this->mod_login->getUsername();

    $inUser = $this->input->post('username');
    $inPass = $this->input->post('password');

    if (in_array($inUser, $username)) {
        $password = $this->mod_login->getPassword($inUser);
        if ($password === $inPass) {
            $this->load->view('Alt_home');
        }
    }
}
</code>```

But I get the error

The requested URL /SEP/con_login/loginUser was not found on this server.

Why is this? Is there anything to do with Routing?

答:
You will need to pass complete url to the form_open function like this

```<code><form action='http://localhost/folder/controller/method'>
</code>```

There are two method to do this

1: Using base_url()

Step 1: Open the config.php file under application\config folder

step 2: Set the value of $config['base_url'] to your website path

```<code>$config['base_url'] = "http://localhost/foldername/index.php";
</code>```

How to use

Load the url helper in controller

```<code>$this->load->helper('url);
</code>```

Now in the view file you can use like this

```<code> echo form_open(base_url()."/controllername/mehod");
</code>```

2: Manually

```<code>form_open("http://localhost/foldername/index.php/controller/method");
</code>```

Body:
I am using Codeigniter with Bootstrap. This is my view code:

<?php echo form_open('con_login/loginUser'); ?>

            Username
            <input type="text" class="form-control" name="username" placeholder="Username" value="">

            Password
            <input type="password" class="form-control" name="password" placeholder="Password" value="">

        <button type="submit" class="btn btn-default" name="login" value="login">Sign in</button>

    <?php echo form_close(); ?>

The code for the called function which is in the controller is:

public function loginUser() {
    $username = $this->mod_login->getUsername();

    $inUser = $this->input->post('username');
    $inPass = $this->input->post('password');

    if (in_array($inUser, $username)) {
        $password = $this->mod_login->getPassword($inUser);
        if ($password === $inPass) {
            $this->load->view('Alt_home');
        }
    }
}

But I get the error

The requested URL /SEP/con_login/loginUser was not found on this server.

Why is this? Is there anything to do with Routing?

Body:
You will need to pass complete url to the form_open function like this

<form action='http://localhost/folder/controller/method'>

There are two method to do this

1: Using base_url()

Step 1: Open the config.php file under application\config folder

step 2: Set the value of $config['base_url'] to your website path

$config['base_url'] = "http://localhost/foldername/index.php";

How to use

Load the url helper in controller

$this->load->helper('url);

Now in the view file you can use like this

 echo form_open(base_url()."/controllername/mehod");

2: Manually

form_open("http://localhost/foldername/index.php/controller/method");


问:
Angular 5 - Remove a child component from parent view on user delete
I have 2 component a Moment(post/thread) and a Comment, each moment can have multiple comments.

Inside the moment-details.component i insert a moment-comment.component. The comment component shows all comments associate with the moment.

moments-detail.component.html

...

            <app-moment-comment [moment]="moment" [auth]="auth" [comment]="comment" class="comment" *ngFor="let comment of moment?.comments; let i=index">
            </app-moment-comment>

```

<p><strong>moment-detail.component.ts</strong></p>

<pre class="lang-js prettyprint-override"><code>@Component({
    selector: 'app-moment-detail',
    templateUrl: './moment-detail.component.html',
    styleUrls: ['./moment-detail.component.scss']
})
export class MomentDetailComponent implements OnInit {

    moment: Moment;

    constructor(private router: Router,
        private route: ActivatedRoute,
        private momentService: MomentService,
        private authService: AuthService,
        private commentService: CommentService) { }

    ngOnInit() {

        this.route.params.switchMap((params) => {
            let moment_id = params['id'];
            return this.momentService.get(moment_id);
        }).subscribe((res) => {
            console.log(res);
            this.moment = res;
            this.user = res.author;
        });

        this.authService.getAuthenticatedUser().subscribe((res) => {
            this.auth = res;
        });

    }
}
</code>```

The moment-comment loops through all the comments and creates a new instance of the moment-comment component.

Now within the moment-comment.component.ts a user can trigger a deletion of their comment.

@Component({
    selector: 'app-moment-comment',
    templateUrl: './moment-comment.component.html',
    styleUrls: ['./moment-comment.component.scss']
})
export class MomentCommentComponent implements OnInit {

    @Input() comment: Comment;
    @Input() auth: any;
    @Input() moment: any;
    showReply: any;
    reply: any;
    showReplies: boolean;
    inEdit = false;
    editComment: any;

    constructor(private commentService: CommentService) { }

...
    delete() {

        this.commentService.delete(this.moment._id, this.comment._id).subscribe((res) => {
            console.log(res);
        }, (err) => {
            console.log(err);
        });

    }
...
}
```

Sure enough when delete() function is triggered by the user the backend updates my database to show the comment is removed from the moment.

My question is, how can i reflect this change in frontend i.e the parent (moment-details) view?

答:
You need to emit an event from comment component to it's parent i.e detail component and remove the comment
from array in detail component like this:

moments-detail.component.html

...
        <app-moment-comment (onDelete)="removeComment(i)" [index]="i"
            [moment]="moment" [auth]="auth" [comment]="comment" class="comment"
            *ngFor="let comment of moment?.comments; let i=index">
        </app-moment-comment>

```

<p>moments-detail.component.ts</p>

<pre class="lang-js prettyprint-override"><code>removeComment(index: number) {
    this.moment.comments.splice(index, 1);
}
</code>```

moment-comment.component.ts

...
@Output() public onDelete: EventEmitter<any> = new EventEmitter();
@Input() comment: Comment;
...

delete() {
    this.commentService.delete(this.moment._id, this.comment._id).subscribe((res) => {
        console.log(res);
        this.onDelete.emit();
    }, (err) => {
        console.log(err);
    });

}
```

Body:
I have 2 component a Moment(post/thread) and a Comment, each moment can have multiple comments.

Inside the moment-details.component i insert a moment-comment.component. The comment component shows all comments associate with the moment.

moments-detail.component.html

...

            <app-moment-comment [moment]="moment" [auth]="auth" [comment]="comment" class="comment" *ngFor="let comment of moment?.comments; let i=index">
            </app-moment-comment>

moment-detail.component.ts

@Component({
    selector: 'app-moment-detail',
    templateUrl: './moment-detail.component.html',
    styleUrls: ['./moment-detail.component.scss']
})
export class MomentDetailComponent implements OnInit {

    moment: Moment;

    constructor(private router: Router,
        private route: ActivatedRoute,
        private momentService: MomentService,
        private authService: AuthService,
        private commentService: CommentService) { }

    ngOnInit() {

        this.route.params.switchMap((params) => {
            let moment_id = params['id'];
            return this.momentService.get(moment_id);
        }).subscribe((res) => {
            console.log(res);
            this.moment = res;
            this.user = res.author;
        });

        this.authService.getAuthenticatedUser().subscribe((res) => {
            this.auth = res;
        });

    }
}

The moment-comment loops through all the comments and creates a new instance of the moment-comment component.

Now within the moment-comment.component.ts a user can trigger a deletion of their comment.

@Component({
    selector: 'app-moment-comment',
    templateUrl: './moment-comment.component.html',
    styleUrls: ['./moment-comment.component.scss']
})
export class MomentCommentComponent implements OnInit {

    @Input() comment: Comment;
    @Input() auth: any;
    @Input() moment: any;
    showReply: any;
    reply: any;
    showReplies: boolean;
    inEdit = false;
    editComment: any;

    constructor(private commentService: CommentService) { }

...
    delete() {

        this.commentService.delete(this.moment._id, this.comment._id).subscribe((res) => {
            console.log(res);
        }, (err) => {
            console.log(err);
        });

    }
...
}

Sure enough when delete() function is triggered by the user the backend updates my database to show the comment is removed from the moment.

My question is, how can i reflect this change in frontend i.e the parent (moment-details) view?

Body:
You need to emit an event from comment component to it's parent i.e detail component and remove the comment
from array in detail component like this:

moments-detail.component.html

<div id="moment">

...
        <app-moment-comment (onDelete)="removeComment(i)" [index]="i"
            [moment]="moment" [auth]="auth" [comment]="comment" class="comment"
            *ngFor="let comment of moment?.comments; let i=index">
        </app-moment-comment>

        </div>
    </div>
</div>

moments-detail.component.ts

removeComment(index: number) {
    this.moment.comments.splice(index, 1);
}

moment-comment.component.ts

...
@Output() public onDelete: EventEmitter<any> = new EventEmitter();
@Input() comment: Comment;
...

delete() {
    this.commentService.delete(this.moment._id, this.comment._id).subscribe((res) => {
        console.log(res);
        this.onDelete.emit();
    }, (err) => {
        console.log(err);
    });

}


问:
Google Calendar API with Java - Service Account
Referenced Google Calendar API with PHP – Service Account and tried the following steps:

Created a project in Google API console and enabled Google Calendar API on this project

Created a service account under the project, downloaded the JWT format key

Tried to share my personal calendar with the service account email, not sure whether it's UI bug or not allowed, there's no error, after refreshing the page, the service account email is gone. I had to use my company's Google account calendar and the service account can be added.

Wrote Java code to use the JWT key from step 2, to get the Calendar list.

```<code>HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
// Build service account credential.

GoogleCredential credential = GoogleCredential          .fromStream(this.getClass().getClassLoader().getResourceAsStream("makoto-c14c149ef994.json")).createScoped(Collections.singleton(CalendarScopes.CALENDAR));

Calendar calendar = new Calendar.Builder(httpTransport, jsonFactory, credential).setApplicationName("makoto").build();

return calendar.calendarList().list();
</code>```

The problems/questions are:

nothing listed from

calendar.calendarList().list()

which returned [], no error as well. did I miss anything?

why can't I share my personal calendar with the service account. Is this only available to enterprise google account?

答:
For #1, try to do the suggestion here in the SO post.

Regardless of language used, try to share the existing calendar with the service account.

```<code><paste-your-account-here>@developer.gserviceaccount.com
</code>```

To have an insight of #2, try to follow the accepted answer in this SO post.

Go to the Google calendar website add the service account email
  address as a user of your calendar. Then the service account will be
  able to access it. If you want you can programmatically insert it into
  calendar.list if you really need it to be there.

Body:
Referenced Google Calendar API with PHP – Service Account and tried the following steps:

Created a project in Google API console and enabled Google Calendar API on this project

Created a service account under the project, downloaded the JWT format key

Tried to share my personal calendar with the service account email, not sure whether it's UI bug or not allowed, there's no error, after refreshing the page, the service account email is gone. I had to use my company's Google account calendar and the service account can be added.

Wrote Java code to use the JWT key from step 2, to get the Calendar list.

HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
// Build service account credential.

GoogleCredential credential = GoogleCredential          .fromStream(this.getClass().getClassLoader().getResourceAsStream("makoto-c14c149ef994.json")).createScoped(Collections.singleton(CalendarScopes.CALENDAR));

Calendar calendar = new Calendar.Builder(httpTransport, jsonFactory, credential).setApplicationName("makoto").build();

return calendar.calendarList().list();

The problems/questions are:

nothing listed from

calendar.calendarList().list()

which returned [], no error as well. did I miss anything?

why can't I share my personal calendar with the service account. Is this only available to enterprise google account?

Body:
For #1, try to do the suggestion here in the SO post.

Regardless of language used, try to share the existing calendar with the service account.

<paste-your-account-here>@developer.gserviceaccount.com

To have an insight of #2, try to follow the accepted answer in this SO post.

Go to the Google calendar website add the service account email
  address as a user of your calendar. Then the service account will be
  able to access it. If you want you can programmatically insert it into
  calendar.list if you really need it to be there.


问:
sed replace spaces in directory names
I'm trying to replace space with - in directory names, not file names on macOS. I have the following:

```<code>cd ~/foo
for directory in **; do
    if [[ -d $directory ]] && [[ -w $directory ]]; then
        sed -i '' 's/  /-/g' "$directory"
    fi
done
</code>```

However I'm getting an error in-place editing only works for regular files.

How can I replace spaces in directory names?

答:
To rename directory, you must use command mv

```<code>#!/bin/bash

cd foo
for directory in **; do
    if [[ -d $directory ]] && [[ -w $directory ]]; then
        newdir=`echo "$directory" |sed  's/ /-/g' `
        if [ "$directory" -ne "$newdir" ]
           mv -- "$directory" "$newdir"
        fi
    fi
done
</code>```

Title: sed replace spaces in directory names

Body:
I'm trying to replace space with - in directory names, not file names on macOS. I have the following:

cd ~/foo
for directory in **; do
    if [[ -d $directory ]] && [[ -w $directory ]]; then
        sed -i '' 's/  /-/g' "$directory"
    fi
done

However I'm getting an error in-place editing only works for regular files.

How can I replace spaces in directory names?

Body:
To rename directory, you must use command mv

#!/bin/bash

cd foo
for directory in **; do
    if [[ -d $directory ]] && [[ -w $directory ]]; then
        newdir=`echo "$directory" |sed  's/ /-/g' `
        if [ "$directory" -ne "$newdir" ]
           mv -- "$directory" "$newdir"
        fi
    fi
done


问:
Copy workbook name to a cell in another workbook
I want to search for an open file named "OTIF"[...].

When the macro finds the workbook, it should paste the file name into "sheet1" Cell A1 in another workbook (wb2).

```<code>Sub Filename()

Dim Wb1 As Workbook, wb2 As Workbook, wB As Workbook

For Each wB In Application.Workbooks
    If Left(wB.Name, 4) = "OTIF" Then
        Set Wb1 = wB
        Exit For
    End If
Next

If Not Wb1 Is Nothing Then
    Set wb2 = ThisWorkbook
End If

With wb2.Sheets("AAA")
    .Range("A1").Value = Dir(Wb1.FullName)
End With

Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic

MsgBox "DONE!"

End Sub
</code>```

答:
Full Edited code:

```<code>Option Explicit

Sub Filename()

Dim Wb1 As Workbook, wb2 As Workbook, wB As Workbook
Dim ws As Worksheet

Set wb2 = ThisWorkbook

On Error Resume Next
Set ws = wb2.Worksheets("AAA")
On Error GoTo 0
If ws Is Nothing Then ' make sure "AAA" sheet exists
    MsgBox "AAA sheet does not exist, or has been renamed", vbCritical
    Exit Sub
End If

For Each wB In Application.Workbooks
    If Left(wB.Name, 4) = "OTIF" Then
        ' for DEBUG ONLY
        ws.Range("A1").Value = wB.Sheets.Count

        ' 2nd Debug option
        ws.Range("A1").Value = "Test"

       ' ws.Range("A1").Value = wB.Name

        MsgBox "DONE!"
        Exit For
    End If
Next

End Sub
</code>```

Body:
I want to search for an open file named "OTIF"[...].

When the macro finds the workbook, it should paste the file name into "sheet1" Cell A1 in another workbook (wb2).

Sub Filename()

Dim Wb1 As Workbook, wb2 As Workbook, wB As Workbook

For Each wB In Application.Workbooks
    If Left(wB.Name, 4) = "OTIF" Then
        Set Wb1 = wB
        Exit For
    End If
Next

If Not Wb1 Is Nothing Then
    Set wb2 = ThisWorkbook
End If

With wb2.Sheets("AAA")
    .Range("A1").Value = Dir(Wb1.FullName)
End With

Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic

MsgBox "DONE!"

End Sub

Body:
Full Edited code:

Option Explicit

Sub Filename()

Dim Wb1 As Workbook, wb2 As Workbook, wB As Workbook
Dim ws As Worksheet

Set wb2 = ThisWorkbook

On Error Resume Next
Set ws = wb2.Worksheets("AAA")
On Error GoTo 0
If ws Is Nothing Then ' make sure "AAA" sheet exists
    MsgBox "AAA sheet does not exist, or has been renamed", vbCritical
    Exit Sub
End If

For Each wB In Application.Workbooks
    If Left(wB.Name, 4) = "OTIF" Then
        ' for DEBUG ONLY
        ws.Range("A1").Value = wB.Sheets.Count

        ' 2nd Debug option
        ws.Range("A1").Value = "Test"

       ' ws.Range("A1").Value = wB.Name

        MsgBox "DONE!"
        Exit For
    End If
Next

End Sub


问:
Build link (url) for calendar event
I want to build a url link from event, so I can use this url in my web app as a clickable link. After click on event I want to see opened event, where I can edit this event
I found this, but its not working correctly:

```<code>var calendarId = CalendarApp.getCalendarById(MYCAL).getId();

var splitEventId = event.getId().split('@');
var eventURL = "https://calendar.google.com/calendar/r/eventedit/" + Utilities.base64Encode(splitEventId[0] + " " + calendarId);
</code>```

Output (eventURL) is URL:

```<code>https://calendar.google.com/calendar/r/eventedit/MGtxajM4bjZnaDljdGZrczloNzdlZmFsM3IgbWFydGluLmJpZWxhazFAZ21haWwuY29t
</code>```

But original URL to event is :

```<code>https://calendar.google.com/calendar/r/eventedit/MGtxajM4bjZnaDljdGZrczloNzdlZmFsM3IgbWFydGluLmJpZWxhazFAbQ
</code>```

It is almost matching, but end of URL is different. I tried also without space between splitEventId and calendarId, but output was worst.
Does somebody know, why this is happening?
How can I build,get event URL?

Thanks.

答:
You can try the Events: get

HTTP request

```<code>GET https://www.googleapis.com/calendar/v3/calendars/calendarId/events/eventId
</code>```

Important parameters needed:

calendarId - Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary
  calendar of the currently logged in user, use the "primary"
  keyword.

eventId - Event identifier.

You can also use the Try it now to check if you have provided a valid/correct data for the required parameters.

Title: Build link (url) for calendar event

Body:
I want to build a url link from event, so I can use this url in my web app as a clickable link. After click on event I want to see opened event, where I can edit this event
I found this, but its not working correctly:

var calendarId = CalendarApp.getCalendarById(MYCAL).getId();

var splitEventId = event.getId().split('@');
var eventURL = "https://calendar.google.com/calendar/r/eventedit/" + Utilities.base64Encode(splitEventId[0] + " " + calendarId);

Output (eventURL) is URL:

https://calendar.google.com/calendar/r/eventedit/MGtxajM4bjZnaDljdGZrczloNzdlZmFsM3IgbWFydGluLmJpZWxhazFAZ21haWwuY29t

But original URL to event is :

https://calendar.google.com/calendar/r/eventedit/MGtxajM4bjZnaDljdGZrczloNzdlZmFsM3IgbWFydGluLmJpZWxhazFAbQ

It is almost matching, but end of URL is different. I tried also without space between splitEventId and calendarId, but output was worst.
Does somebody know, why this is happening?
How can I build,get event URL?

Thanks.

Body:
You can try the Events: get

HTTP request

GET https://www.googleapis.com/calendar/v3/calendars/calendarId/events/eventId

Important parameters needed:

calendarId - Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary
  calendar of the currently logged in user, use the "primary"
  keyword.

eventId - Event identifier.

You can also use the Try it now to check if you have provided a valid/correct data for the required parameters.


问:
Sqoop import mysql to hive ,data uncorrect
I used sqoop to import some data from mysql to hive and when it finished,I found some columns are incorrect in some rows.
Here is my code:

```<code>bin/sqoop import -Dhadoop.security.credential.provider.path=mypath
--table mytable  --hive-overwrite --hive-table myhivetable
--username myname -–password-alias mydb.password.alias
--connect  myconn  -m 1 --null-string '**' --null-non-string '**'
--fields-terminated-by '\001'  --lines-terminated-by '\n'
</code>```

Here is the correct data in mysql:

but in hive it is:

Here are some rows in hive:

答:
Your code should be somewhat in this format

Sqoop import - - connect jdbc:mysql://localhost/tablename - - driver com.mysql.jdbc.Driver - - table tablename - - hive-import

Body:
I used sqoop to import some data from mysql to hive and when it finished,I found some columns are incorrect in some rows.
Here is my code:

bin/sqoop import -Dhadoop.security.credential.provider.path=mypath
--table mytable  --hive-overwrite --hive-table myhivetable
--username myname -–password-alias mydb.password.alias
--connect  myconn  -m 1 --null-string '**' --null-non-string '**'
--fields-terminated-by '\001'  --lines-terminated-by '\n'

Here is the correct data in mysql:

but in hive it is:

Here are some rows in hive:


问:
Does adding a new member variable to a class affects the binary compatibility?
I have a class called AMFactory in a shared library. This shared library is used by many user applications. Now I want to add a new private member variable to my class. Does this break the binary compatibility? If it breaks then is there a hack for it. In my case I don't want the user applications to be recompiled. Snippet of my class [AMFactory] and its base class[Factory] below.</p>

```<code>namespace CF {
class CF_EXPORT Factory {
 public:
 virtual ~Factory();

 virtual bool registerManager(const std::string &_interface,
                      const Id_t &_id) = 0;
 virtual bool unregisterManager(const std::string &_interface,
                      const Id_t &_id) = 0;
};
}
namespace CF {
namespace AM {
class AMFactory : public CF::Factory {
public:
CF_EXPORT static std::shared_ptr<AMFactory> get();

CF_EXPORT AMFactory();
CF_EXPORT virtual ~AMFactory();

CF_EXPORT bool registerManager(const std::string &_interface,
                      const Id_t &_id);
CF_EXPORT bool unregisterManager(const std::string &_interface,
                      const Id_t &_id);

private:
CF_EXPORT bool registerManager(std::shared_ptr<AMManager>);
CF_EXPORT bool unregisterManager(std::shared_ptr<AMManager>);

static std::shared_ptr<AMFactory> theFactory;
ServicesMap services_;
};
}
}
</code>```

答:
Now I want to add a new private member variable to my class. Does this break the binary compatibility?

The size of your class will change, thus yes, it will break binary compability.

If it breaks then is there a hack for it. In my case I don't want the user applications to be recompiled.

Not a one I am aware of. That's (also) why we focus on design before starting implementing.

Body:
I have a class called AMFactory in a shared library. This shared library is used by many user applications. Now I want to add a new private member variable to my class. Does this break the binary compatibility? If it breaks then is there a hack for it. In my case I don't want the user applications to be recompiled. Snippet of my class [AMFactory] and its base class[Factory] below.

namespace CF {
class CF_EXPORT Factory {
 public:
 virtual ~Factory();

 virtual bool registerManager(const std::string &_interface,
                      const Id_t &_id) = 0;
 virtual bool unregisterManager(const std::string &_interface,
                      const Id_t &_id) = 0;
};
}
namespace CF {
namespace AM {
class AMFactory : public CF::Factory {
public:
CF_EXPORT static std::shared_ptr<AMFactory> get();

CF_EXPORT AMFactory();
CF_EXPORT virtual ~AMFactory();

CF_EXPORT bool registerManager(const std::string &_interface,
                      const Id_t &_id);
CF_EXPORT bool unregisterManager(const std::string &_interface,
                      const Id_t &_id);

private:
CF_EXPORT bool registerManager(std::shared_ptr<AMManager>);
CF_EXPORT bool unregisterManager(std::shared_ptr<AMManager>);

static std::shared_ptr<AMFactory> theFactory;
ServicesMap services_;
};
}
}


问:
Cart Summary In Layout
I develop an ecommerce application. I using C#, MVC and Entity Framework and Bootstrap.
I've saved cart item in my database. My question is :
I want to show cart's summary in my layout's top. But what's your suggestion for this operation.
Should i use a partial view for the cart's summary or another way?

And in other hand how can i read my cart's data from database every request. i cannot it in from controllers of course. because i want to show cart's summary top of the screen at every page. should i read it from application start or ? Any suggest me pls for this operations.

```<code>//_Layout.cshtml
<body>
    <div class="container">
        <nav class="navbar navbar-default" role="navigation">
            <div class="navbar-header">
                <a class="navbar-brand" href="#">E-Commerce</a>
            </div>
            <form class="navbar-form navbar-left" role="search">

                <div class="input-group">
                    <input type="text" class="form-control" placeholder="Arama">
                    <span class="input-group-addon">
                        <i class="fa fa-search"></i>
                    </span>
                </div>
            </form>
            <p class="navbar-text pull-right">

                /* I want to see shopping cart summary in this section*/

                <i class="fa fa-shopping-cart"></i>
                <span id="cartTotal">

                </span>
                (<span id="cartItemCount"></span>)
            </p>
            <p class="navbar-text pull-right">Log In</p>
            <p class="navbar-text pull-right">Register</p>

        </nav>

    </div>
    <div class="container">
        @RenderBody()
    </div>
</body>
</html>
</code>```

答:
you can use of this solution

in Controller

```<code> [ChildActionOnly]
    public ActionResult CartSummary()
    {
        ViewData["CartCount"] = 3; // count Qty in your cart
        return PartialView("CartSummary");
    }
</code>```

right click and Add view and select PartialView then in PartialView

```<code>@ViewData["CartCount"]
</code>```

in layout, where you want to show cart's qty

```<code>@{Html.RenderAction("CartSummary", "controllerName");}
</code>```

Title: Cart Summary In Layout

Body:
I develop an ecommerce application. I using C#, MVC and Entity Framework and Bootstrap.
I've saved cart item in my database. My question is :
I want to show cart's summary in my layout's top. But what's your suggestion for this operation.
Should i use a partial view for the cart's summary or another way?

And in other hand how can i read my cart's data from database every request. i cannot it in from controllers of course. because i want to show cart's summary top of the screen at every page. should i read it from application start or ? Any suggest me pls for this operations.

//_Layout.cshtml

                E-Commerce

            <form class="navbar-form navbar-left" role="search">

                    <input type="text" class="form-control" placeholder="Arama">

            </form>

                /* I want to see shopping cart summary in this section*/

                ()

Log In

Register

        @RenderBody()

Body:
you can use of this solution

in Controller

 [ChildActionOnly]
    public ActionResult CartSummary()
    {
        ViewData["CartCount"] = 3; // count Qty in your cart
        return PartialView("CartSummary");
    }

right click and Add view and select PartialView then in PartialView

@ViewData["CartCount"]

in layout, where you want to show cart's qty

@{Html.RenderAction("CartSummary", "controllerName");}


问:
Decrementing for loops
I want to have a for loop like so:

```<code>for counter in range(10,0):
       print counter,
</code>```

and the output should be 10 9 8 7 6 5 4 3 2 1

答:
```<code>a = " ".join(str(i) for i in range(10, 0, -1))
print (a)
</code>```

Title: Decrementing for loops

Body:
I want to have a for loop like so:

for counter in range(10,0):
       print counter,

and the output should be 10 9 8 7 6 5 4 3 2 1


问:
Eclipse breakpoint filtering restriction to location unavailable
I'm using Eclipse 4.7.0 and 4.7.1a respectively for different projects on two different machines. In 4.7.0, under Breakpoint Properties... > Filtering, I can restrict the breakpoint to a thread or to locations (classes and packages). In 4.7.1a, the dialog only shows the thread selection, i.e. I cannot restrict to locations. Is this a bug in 4.7.1a or a config issue?</p>

答:
Restrict to Selected Location(s) filtering is only available for Java exception breakpoints, not for example for line or for method breakpoints.

Filtering based on the location would make no sense for breakpoints like line or method breakpoints that reference code at a specific location.

This applies to both Eclipse 4.7.0 and 4.7.1a:

Create an exception breakpoint via Run > Add Java Exception Breakpoint...

Right-click the breakpoint and choose Breakpoint Properties...

In the Breakpoint Properties dialog switch to Filtering


问:
Xpath extract all the text between multiple nodes?
I'm scraping an e-commerce web site using the Python requests modul.
Well I have some problem on extracting the text between multiple nodes. The following html is the part where I'm trying to extract the text. I need to extract all the text under the (div class="rte ingredients") embedded into the two (p) tags and all the (strong) tags. Pay attention! The (strong) tags can vary from page to page.

```<code><div class="rte ingredients">
    <p>Farina sbiancata arricchita (farina sbiancata di
    <strong>grano</strong>,
    ferro ridotto, vitamine B3-B1-B2-B9), zucchero,
    agenti lievitanti E500ii-E541i-E341i, destrosio,
    <strong>latte</strong>
    scremato disidratato, olio di
    <strong>soia</strong> parzialmente
    idrogenato, sale,
    <strong>glutine</strong> di <strong>grano</strong>,
    colorante E170, estratto secco di sciroppo di granoturco, caseinati di
    sodio (<strong>latte</strong>), emulsionante E471, regolatore di acidità
    E270. Può contenere tracce di <strong>uova</strong>. Contiene OGM.</p>

    <p>Valori nutrizionali (per 100g): energia 348Kcal, lipidi 3.3g (di cui
    grassi saturi 0g), carboidrati 69.6g (di cui zuccheri 13g), proteine
    10.9g, sale 2.6g.</p>
</div>
</code>```

Well, I'm using the following code but the result I get is partial.

```<code>ingredients = parser.xpath('//*[@id="bottom_right_product_infos"]/section[2]/div/p[1]/text()')
print ingredients
['Farina sbiancata arricchita (farina sbiancata di']
</code>```

Conversely I need to extract all the text under the (DIV) tag.

Can somebody help me on this? Thanks!

答:
It seems you are using lxml library. If that is so, the below method should fetch you the full content. Use .text_content() instead of .text in the print statement.

```<code>content='''
<div class="rte ingredients">
    <p>Farina sbiancata arricchita (farina sbiancata di
    <strong>grano</strong>,
    ferro ridotto, vitamine B3-B1-B2-B9), zucchero,
    agenti lievitanti E500ii-E541i-E341i, destrosio,
    <strong>latte</strong>
    scremato disidratato, olio di
    <strong>soia</strong> parzialmente
    idrogenato, sale,
    <strong>glutine</strong> di <strong>grano</strong>,
    colorante E170, estratto secco di sciroppo di granoturco, caseinati di
    sodio (<strong>latte</strong>), emulsionante E471, regolatore di acidità
    E270. Può contenere tracce di <strong>uova</strong>. Contiene OGM.</p>

    <p>Valori nutrizionali (per 100g): energia 348Kcal, lipidi 3.3g (di cui
    grassi saturi 0g), carboidrati 69.6g (di cui zuccheri 13g), proteine
    10.9g, sale 2.6g.</p>
</div>
'''
from lxml.html import fromstring
root = fromstring(content)
for items in root.xpath("//div[contains(@class,'ingredients')]/p"):
    print(items.text_content())  #take a closer look at this .text_content() instead of .text.
</code>```

Body:
I'm scraping an e-commerce web site using the Python requests modul.
Well I have some problem on extracting the text between multiple nodes. The following html is the part where I'm trying to extract the text. I need to extract all the text under the (div class="rte ingredients") embedded into the two (p) tags and all the (strong) tags. Pay attention! The (strong) tags can vary from page to page.

Farina sbiancata arricchita (farina sbiancata di
    grano,
    ferro ridotto, vitamine B3-B1-B2-B9), zucchero,
    agenti lievitanti E500ii-E541i-E341i, destrosio,
    latte
    scremato disidratato, olio di
    soia parzialmente
    idrogenato, sale,
    glutine di grano,
    colorante E170, estratto secco di sciroppo di granoturco, caseinati di
    sodio (latte), emulsionante E471, regolatore di acidità
    E270. Può contenere tracce di uova. Contiene OGM.

Valori nutrizionali (per 100g): energia 348Kcal, lipidi 3.3g (di cui
    grassi saturi 0g), carboidrati 69.6g (di cui zuccheri 13g), proteine
    10.9g, sale 2.6g.

Well, I'm using the following code but the result I get is partial.

ingredients = parser.xpath('//*[@id="bottom_right_product_infos"]/section[2]/div/p[1]/text()')
print ingredients
['Farina sbiancata arricchita (farina sbiancata di']

Conversely I need to extract all the text under the (DIV) tag.

Can somebody help me on this? Thanks!

Body:
It seems you are using lxml library. If that is so, the below method should fetch you the full content. Use .text_content() instead of .text in the print statement.

content='''
<div class="rte ingredients">
    <p>Farina sbiancata arricchita (farina sbiancata di
    <strong>grano</strong>,
    ferro ridotto, vitamine B3-B1-B2-B9), zucchero,
    agenti lievitanti E500ii-E541i-E341i, destrosio,
    <strong>latte</strong>
    scremato disidratato, olio di
    <strong>soia</strong> parzialmente
    idrogenato, sale,
    <strong>glutine</strong> di <strong>grano</strong>,
    colorante E170, estratto secco di sciroppo di granoturco, caseinati di
    sodio (<strong>latte</strong>), emulsionante E471, regolatore di acidità
    E270. Può contenere tracce di <strong>uova</strong>. Contiene OGM.</p>

    <p>Valori nutrizionali (per 100g): energia 348Kcal, lipidi 3.3g (di cui
    grassi saturi 0g), carboidrati 69.6g (di cui zuccheri 13g), proteine
    10.9g, sale 2.6g.</p>
</div>
'''
from lxml.html import fromstring
root = fromstring(content)
for items in root.xpath("//div[contains(@class,'ingredients')]/p"):
    print(items.text_content())  #take a closer look at this .text_content() instead of .text.


问:
How could I connect a program with interface in python
I want to use tkinter to set a interface for my another program, but I do not know what is my next step.

I do not know how to connect each other.

I do not have that concept.

This is the code of trying to be a interface:

```<code>#!/usr/bin/env python -O
import subprocess
from tkinter import *
subprocess.call('/Users/Tsu-
AngChou/MasterProject/Practice/try_test/TEST5.py')

root = Tk(className ="Documents retriever")
svalue = StringVar() # defines the widget state as string
w = Entry(root,textvariable=svalue) # adds a textarea widget
w.pack()
def act():
    print ("you entered")
    print ('%s' % svalue.get())
foo = Button(root,text="Retrieve", command=act)
foo.pack()
root.mainloop()
</code>```

This is the code of my python script:

```<code>#!/usr/bin/env python
import string
import os
from bs4 import BeautifulSoup as bs
from os import listdir
from os.path import isfile, join

mypath = "/Users/Tsu-AngChou/MasterProject/Practice/try_test/"
files = listdir(mypath)
storage = {}
translator = str.maketrans("","",string.punctuation)
for f in files:
  fullpath = join(mypath, f)
  if f == '.DS_Store':
            os.remove(f)
  elif isfile(fullpath):

    print(f)
    for html_cont in range(1):
        response = open(f,'r',encoding='utf-8')
        html_cont = response.read()
        soup = bs(html_cont, 'html.parser')
        regular_string = soup.get_text()
        new_string = regular_string.translate(translator).split()
        new_list = [item[:14] for item in new_string]
        a = dict.fromkeys(new_list, f)
        b = a
        storage.update(a)
        print(a)
        storage.append(new_list)

        wordfreq = []
        for w in new_list:
            wordfreq.append(new_list.count(w))
        print("Frequency:\n" ,list(zip(b,wordfreq)))
</code>```

I want to use the value(a) and value(list(zip(b,wordfreq))
How could I give the Button value?

答:
Put code in script inside function and add if __name__ == "__main__" to the end

```<code>#!/usr/bin/env python
import string
import os
from bs4 import BeautifulSoup as bs
from os import listdir
from os.path import isfile, join

def my_function(mypath = "/Users/Tsu-AngChou/MasterProject/Practice/try_test/"):
    files = listdir(mypath)
    storage = {}
    translator = str.maketrans("","",string.punctuation)
    for f in files:
      fullpath = join(mypath, f)
      if f == '.DS_Store':
                os.remove(f)
      elif isfile(fullpath):

        print(f)
        for html_cont in range(1):
            response = open(f,'r',encoding='utf-8')
            html_cont = response.read()
            soup = bs(html_cont, 'html.parser')
            regular_string = soup.get_text()
            new_string = regular_string.translate(translator).split()
            new_list = [item[:14] for item in new_string]
            a = dict.fromkeys(new_list, f)
            b = a
            storage.update(a)
            print(a)
            storage.append(new_list)

            wordfreq = []
            for w in new_list:
                wordfreq.append(new_list.count(w))
            print("Frequency:\n" ,list(zip(b,wordfreq)))

if __name__ == '__main__':
   my_function()
</code>```

So it will still work as standalone script but now you can import it in second file and execute. I execut it in act()

```<code>#!/usr/bin/env python -O

from tkinter import *
from my_scipt import my_function

def act():
    print("you entered")
    print(svalue.get())
    my_function()

root = Tk()
svalue = StringVar()
w = Entry(root, textvariable=svalue)
w.pack()
foo = Button(root, text="Retrieve", command=act)
foo.pack()
root.mainloop()
</code>```

BTW: you can execute my_function with parameter

```<code>my_function("/path/to/different/folder")
</code>```

but you can create function with more arguments and execute

```<code>my_function("/path/", a, b)
</code>```

If you need some values from this function then use in function

```<code>return value1, value2
</code>```

and then you can use it as

```<code>val1, val2 = my_function("/path/", a, b)
</code>```

Body:
I want to use tkinter to set a interface for my another program, but I do not know what is my next step.

I do not know how to connect each other.

I do not have that concept.

This is the code of trying to be a interface:

#!/usr/bin/env python -O
import subprocess
from tkinter import *
subprocess.call('/Users/Tsu-
AngChou/MasterProject/Practice/try_test/TEST5.py')

root = Tk(className ="Documents retriever")
svalue = StringVar() # defines the widget state as string
w = Entry(root,textvariable=svalue) # adds a textarea widget
w.pack()
def act():
    print ("you entered")
    print ('%s' % svalue.get())
foo = Button(root,text="Retrieve", command=act)
foo.pack()
root.mainloop()

This is the code of my python script:

#!/usr/bin/env python
import string
import os
from bs4 import BeautifulSoup as bs
from os import listdir
from os.path import isfile, join

mypath = "/Users/Tsu-AngChou/MasterProject/Practice/try_test/"
files = listdir(mypath)
storage = {}
translator = str.maketrans("","",string.punctuation)
for f in files:
  fullpath = join(mypath, f)
  if f == '.DS_Store':
            os.remove(f)
  elif isfile(fullpath):

    print(f)
    for html_cont in range(1):
        response = open(f,'r',encoding='utf-8')
        html_cont = response.read()
        soup = bs(html_cont, 'html.parser')
        regular_string = soup.get_text()
        new_string = regular_string.translate(translator).split()
        new_list = [item[:14] for item in new_string]
        a = dict.fromkeys(new_list, f)
        b = a
        storage.update(a)
        print(a)
        storage.append(new_list)

        wordfreq = []
        for w in new_list:
            wordfreq.append(new_list.count(w))
        print("Frequency:\n" ,list(zip(b,wordfreq)))

I want to use the value(a) and value(list(zip(b,wordfreq))
How could I give the Button value?

Body:
Put code in script inside function and add if __name__ == "__main__" to the end

#!/usr/bin/env python
import string
import os
from bs4 import BeautifulSoup as bs
from os import listdir
from os.path import isfile, join

def my_function(mypath = "/Users/Tsu-AngChou/MasterProject/Practice/try_test/"):
    files = listdir(mypath)
    storage = {}
    translator = str.maketrans("","",string.punctuation)
    for f in files:
      fullpath = join(mypath, f)
      if f == '.DS_Store':
                os.remove(f)
      elif isfile(fullpath):

        print(f)
        for html_cont in range(1):
            response = open(f,'r',encoding='utf-8')
            html_cont = response.read()
            soup = bs(html_cont, 'html.parser')
            regular_string = soup.get_text()
            new_string = regular_string.translate(translator).split()
            new_list = [item[:14] for item in new_string]
            a = dict.fromkeys(new_list, f)
            b = a
            storage.update(a)
            print(a)
            storage.append(new_list)

            wordfreq = []
            for w in new_list:
                wordfreq.append(new_list.count(w))
            print("Frequency:\n" ,list(zip(b,wordfreq)))

if __name__ == '__main__':
   my_function()

So it will still work as standalone script but now you can import it in second file and execute. I execut it in act()

#!/usr/bin/env python -O

from tkinter import *
from my_scipt import my_function

def act():
    print("you entered")
    print(svalue.get())
    my_function()

root = Tk()
svalue = StringVar()
w = Entry(root, textvariable=svalue)
w.pack()
foo = Button(root, text="Retrieve", command=act)
foo.pack()
root.mainloop()

BTW: you can execute my_function with parameter

my_function("/path/to/different/folder")

but you can create function with more arguments and execute

my_function("/path/", a, b)

If you need some values from this function then use in function

return value1, value2

and then you can use it as

val1, val2 = my_function("/path/", a, b)


问:
Download pdf with retrofit 2.3 with webView from moodle - Android
I am loading a url in webView, the webSite is php base moodle.In the webView is a lot *.pdf and I need to download those pdfs but I can't and just download login page .
Notice :

1- I login to webSite in webView then I get the cookies like bellow :

```<code>urlListClassWebView.setWebViewClient(new CustomBrowsers());
urlListClassWebView.getSettings().setLoadsImagesAutomatically(true);
urlListClassWebView.getSettings().setJavaScriptEnabled(true);
urlListClassWebView.clearHistory();
urlListClassWebView.setHorizontalScrollBarEnabled(false);
urlListClassWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
urlListClassWebView.loadUrl(url);
urlListClassWebView.setWebViewClient(new WebViewClient() {

                    @Override
                    public void onPageStarted(WebView view, String url, Bitmap favicon) {
                        super.onPageStarted(view, url, favicon);
                        if (url.contains(".pdf")) {
                            String cookies = CookieManager.getInstance().getCookie(url);
                        }
                    }
                });
</code>```

2- Then I send cookies to moodle like bellow with retrofit 2.3 :

```<code>@Headers({
        "Referer: http://xx.xx.xx/course/view.php?id=2484",
        "User-Agent: Mozilla/5.0 (Linux; Android 7.0; SM-G920F Build/NRD90M; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/62.0.3202.84 Mobile Safari/537.36",
        "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
        "Upgrade-Insecure-Requests: 1"
})
@POST
@FormUrlEncoded
Call<ResponseBody> downloadFile(@Url String url,
                                @Field("_ga") String _ga,
                                @Field("MoodleSession") String MoodleSession,
                                @Field("MOODLEID1_") String MOODLEID1_,
                                @Field("loglevel") String loglevel);
</code>```

答:
Resolved my problem :

1-First I get cookies the I create them like : aa=546345; bb=dfjds65;

2-Then I pass it with retrofit like bellow :

```<code>@POST
Call<ResponseBody> downloadFile(@Url String url,
                                @Header("Cookie") String sessionIdAndToken);
</code>```

Body:
I am loading a url in webView, the webSite is php base moodle.In the webView is a lot *.pdf and I need to download those pdfs but I can't and just download login page .
Notice :

1- I login to webSite in webView then I get the cookies like bellow :

urlListClassWebView.setWebViewClient(new CustomBrowsers());
urlListClassWebView.getSettings().setLoadsImagesAutomatically(true);
urlListClassWebView.getSettings().setJavaScriptEnabled(true);
urlListClassWebView.clearHistory();
urlListClassWebView.setHorizontalScrollBarEnabled(false);
urlListClassWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
urlListClassWebView.loadUrl(url);
urlListClassWebView.setWebViewClient(new WebViewClient() {

                    @Override
                    public void onPageStarted(WebView view, String url, Bitmap favicon) {
                        super.onPageStarted(view, url, favicon);
                        if (url.contains(".pdf")) {
                            String cookies = CookieManager.getInstance().getCookie(url);
                        }
                    }
                });

2- Then I send cookies to moodle like bellow with retrofit 2.3 :

@Headers({
        "Referer: http://xx.xx.xx/course/view.php?id=2484",
        "User-Agent: Mozilla/5.0 (Linux; Android 7.0; SM-G920F Build/NRD90M; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/62.0.3202.84 Mobile Safari/537.36",
        "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
        "Upgrade-Insecure-Requests: 1"
})
@POST
@FormUrlEncoded
Call<ResponseBody> downloadFile(@Url String url,
                                @Field("_ga") String _ga,
                                @Field("MoodleSession") String MoodleSession,
                                @Field("MOODLEID1_") String MOODLEID1_,
                                @Field("loglevel") String loglevel);

Body:
Resolved my problem :

1-First I get cookies the I create them like : aa=546345; bb=dfjds65;

2-Then I pass it with retrofit like bellow :

@POST
Call<ResponseBody> downloadFile(@Url String url,
                                @Header("Cookie") String sessionIdAndToken);