问:
Displaying Youtube within an Ionic 2 app
I am trying to display Youtube videos within an Ionic 2 application, with the URLs pulled in from a JSON data feed.

Individual videos can be displayed when the Youtube url is set in the constructor on the detail page, but I need the detail page to display videos for each of the videos in the JSON feed.

Here is how an individual Youtube video is able to display in Ionic 2 within detail.ts and detail.html:

1

```<code>import {SafeResourceUrl, DomSanitizer} from '@angular/platform-browser';
</code>```

2

```<code>videoUrl: SafeResourceUrl;

constructor(private domSanitizer: DomSanitizer, public navCtrl: NavController) {
this.videoUrl = this.domSanitizer.bypassSecurityTrustResourceUrl('https://www.youtube.com/embed/DuwXCFyo4-w')
}
</code>```

3

```<code><iframe width="100%" height="315" [src]="data.youtube" frameborder="0" allowfullscreen></iframe>
</code>```

ios tweak

```<code><allow-navigation href="https://*youtube.com/*"/>
</code>```

What I need is some code tweaking in detail.ts to allow any Youtube url?

Here is the Youtube displayed in a Plunker on the detail page
http://plnkr.co/edit/Ar2whVFCmBAbE7fxA3nf?p=preview

One solution I have seen is below, but can't seem to get it working:

```<code>transform(videoId: string): SafeResourceUrl {
return this.domSanitizer.bypassSecurityTrustResourceUrl(
https://www.youtube.com/embed/${videoId});
}
</code>```

答:
You are doing it wrong. You shouldn't be using embedded youtube frames on your ionic app.

You must use the Ionic Youtube Plugin

To install it, go to your Ionic project in the command line:

```<code>ionic plugin add https://github.com/Glitchbone/CordovaYoutubeVideoPlayer.git
npm install --save @ionic-native/youtube-video-player
</code>```

Basic Usage:

```<code>import { YoutubeVideoPlayer } from '@ionic-native/youtube-video-player';

constructor(private youtube: YoutubeVideoPlayer) { }

this.youtube.openVideo('myvideoid');
</code>```

Of course 'myvideoid' is your youtube video ID passed as a string.

Body:
I am trying to display Youtube videos within an Ionic 2 application, with the URLs pulled in from a JSON data feed.

Individual videos can be displayed when the Youtube url is set in the constructor on the detail page, but I need the detail page to display videos for each of the videos in the JSON feed.

Here is how an individual Youtube video is able to display in Ionic 2 within detail.ts and detail.html:

1

import {SafeResourceUrl, DomSanitizer} from '@angular/platform-browser';

2

videoUrl: SafeResourceUrl;

constructor(private domSanitizer: DomSanitizer, public navCtrl: NavController) {
this.videoUrl = this.domSanitizer.bypassSecurityTrustResourceUrl('https://www.youtube.com/embed/DuwXCFyo4-w')
}

3

ios tweak

<allow-navigation href="https://*youtube.com/*"/>

What I need is some code tweaking in detail.ts to allow any Youtube url?

Here is the Youtube displayed in a Plunker on the detail page
http://plnkr.co/edit/Ar2whVFCmBAbE7fxA3nf?p=preview

One solution I have seen is below, but can't seem to get it working:

transform(videoId: string): SafeResourceUrl {
return this.domSanitizer.bypassSecurityTrustResourceUrl(
https://www.youtube.com/embed/${videoId});
}

Body:
You are doing it wrong. You shouldn't be using embedded youtube frames on your ionic app.

You must use the Ionic Youtube Plugin

To install it, go to your Ionic project in the command line:

ionic plugin add https://github.com/Glitchbone/CordovaYoutubeVideoPlayer.git
npm install --save @ionic-native/youtube-video-player

Basic Usage:

import { YoutubeVideoPlayer } from '@ionic-native/youtube-video-player';

constructor(private youtube: YoutubeVideoPlayer) { }

this.youtube.openVideo('myvideoid');

Of course 'myvideoid' is your youtube video ID passed as a string.


来源: stackexchange

问:
Execute C script needing ext lib
Refering to Connect Postgresql in C

I asked some help to compile my script of Postgres database connection. This is now compiling well but now I have a problem when I execute it.

There is the code :

```<code>#include <stdio.h>
#include "libpq-fe.h"
#include <stdlib.h>

int     main() {
PGconn          *conn;
PGresult        *res;
int             rec_count;
int             row;
int             col;

        conn = PQconnectdb("dbname=ljdata host=localhost user=dataman password=supersecret");

        if (PQstatus(conn) == CONNECTION_BAD) {
                puts("We were unable to connect to the database");
                exit(0);
        }

        res = PQexec(conn,
                "update people set phonenumber=\'5055559999\' where id=3");

        res = PQexec(conn,
                "select lastname,firstname,phonenumber from people order by id");

        if (PQresultStatus(res) != PGRES_TUPLES_OK) {
                puts("We did not get any data!");
                exit(0);
        }

        rec_count = PQntuples(res);

        printf("We received %d records.\n", rec_count);
        puts("==========================");

        for (row=0; row<rec_count; row++) {
                for (col=0; col<3; col++) {
                        printf("%s\t", PQgetvalue(res, row, col));
                }
                puts("");
        }

        puts("==========================");

        PQclear(res);

        PQfinish(conn);

        return 0;
}
</code>```

And this is the compilation line it's actually working :

```<code>gcc -m64 -I "C:\Program Files\PostgreSQL\9.6\include" -L "C:\Program Files\PostgreSQL\9.6\lib" test.c -lpq -o test.exe
</code>```

Now when I double-click on the .exe I have the following error :

"Unable to start the program because LIBPQ.dll is missing"

So it clearly means that I have to link the libpq.dll

But what I'm trying to do is compiling all the methods from the .c/.dll etc in the binary .exe which I plan to distribute and the postgresql libs will not be installed on the target machines.

After some web search, I found the "-static" parameter but I'm not sure that it's what I'm looking for and I'm not able to have it compiling with this parameter.

Then I tried to add "-static-libgcc" which results as :

```<code>gcc -m64 -static-libgcc -I "C:\Program Files\PostgreSQL\9.6\include" -L "C:\Program Files\PostgreSQL\9.6\lib" test.c -lpq -o test.exe
</code>```

But I still have the "System error" when I try to run it :

"Unable to run the script because LIBPQ.dll is missing on your computer"
(Not sure if my french translate is exact)

Do you know the parameter or the way I can compile my C program into a binary .exe which would be totally standalone and without any library requirement ?

EDIT

Screenshot :

答:
Stick with dynamic linking.

Your problem is that the system cannot find libpq.dll at runtime.

There are two solutions:

Add C:\Program Files\PostgreSQL\9.6\lib to the PATH environment variable.

Put a copy of libpq.dll in the same path as your executable.

ContentLicense: CC BY-SA 3.0

Title: Execute C script needing ext lib

Body:
Refering to Connect Postgresql in C

I asked some help to compile my script of Postgres database connection. This is now compiling well but now I have a problem when I execute it.

There is the code :

#include <stdio.h>
#include "libpq-fe.h"
#include <stdlib.h>

int     main() {
PGconn          *conn;
PGresult        *res;
int             rec_count;
int             row;
int             col;

        conn = PQconnectdb("dbname=ljdata host=localhost user=dataman password=supersecret");

        if (PQstatus(conn) == CONNECTION_BAD) {
                puts("We were unable to connect to the database");
                exit(0);
        }

        res = PQexec(conn,
                "update people set phonenumber=\'5055559999\' where id=3");

        res = PQexec(conn,
                "select lastname,firstname,phonenumber from people order by id");

        if (PQresultStatus(res) != PGRES_TUPLES_OK) {
                puts("We did not get any data!");
                exit(0);
        }

        rec_count = PQntuples(res);

        printf("We received %d records.\n", rec_count);
        puts("==========================");

        for (row=0; row<rec_count; row++) {
                for (col=0; col<3; col++) {
                        printf("%s\t", PQgetvalue(res, row, col));
                }
                puts("");
        }

        puts("==========================");

        PQclear(res);

        PQfinish(conn);

        return 0;
}

And this is the compilation line it's actually working :

gcc -m64 -I "C:\Program Files\PostgreSQL\9.6\include" -L "C:\Program Files\PostgreSQL\9.6\lib" test.c -lpq -o test.exe

Now when I double-click on the .exe I have the following error :

"Unable to start the program because LIBPQ.dll is missing"

So it clearly means that I have to link the libpq.dll

But what I'm trying to do is compiling all the methods from the .c/.dll etc in the binary .exe which I plan to distribute and the postgresql libs will not be installed on the target machines.

After some web search, I found the "-static" parameter but I'm not sure that it's what I'm looking for and I'm not able to have it compiling with this parameter.

Then I tried to add "-static-libgcc" which results as :

gcc -m64 -static-libgcc -I "C:\Program Files\PostgreSQL\9.6\include" -L "C:\Program Files\PostgreSQL\9.6\lib" test.c -lpq -o test.exe

But I still have the "System error" when I try to run it :

"Unable to run the script because LIBPQ.dll is missing on your computer"
(Not sure if my french translate is exact)

Do you know the parameter or the way I can compile my C program into a binary .exe which would be totally standalone and without any library requirement ?

EDIT

Screenshot :


问:
Randomly assign an integer within each group of ID's in Dataframe - R
I am trying to set a random integer within each group of existing ID's. The integers must meet the following conditions: unique, non repeating, and the highest integer for a group of ID's will not be greater than the number of rows with that ID.

I have tried doing this in a for loop, and it works for the first group of ID's, but does not repeat for the next set. I looked at several existing stack overflow questions and other sites which address this to some degree, but still have not been able to get it right. Links below:

Randomly Assign Integers in R within groups without replacement

http://r.789695.n4.nabble.com/Random-numbers-for-a-group-td964301.html

random selection within groups

I need it to be dynamic in the sense that week by week there could be more ID's or fewer ID's. The actual DF has several other columns, but for ease of reproduction they were left out as they are not used.

Example below:

```<code>#Desired Output

Groups <- c("A","A","A","A","B","B","B","B","B","B","B","B","C","C","C","C","C","C")
Desired_Integer <- c(1,4,2,3,6,3,1,2,8,5,7,4,5,6,1,4,3,2)
Example <- data.frame(Groups,Desired_Integer)

#Attempted For Loop for Example (assuming Example is a DF with one column, Groups for the For Loop)

Groups <- c("A","A","A","A","B","B","B","B","B","B","B","B","C","C","C","C","C","C")
Example <- as.data.frame(Groups)

for (i in Example$Groups)
{
Example$Desired_Integer <- sample.int(length(which(Example$Groups == i)))
}
</code>```

Thank you in advance for your help!

答:
You can do this with the base function ave with

```<code>dd <- data.frame(Groups = rep(c("A","B","C"), c(4,8,6)))
rand_seq_for <- function(x) sample.int(length(x))
dd$rand_int <- ave(1:nrow(dd), dd$Groups, FUN=rand_seq_for)
</code>```

or using dplyr, you can do

```<code>library(dplyr)
dd %>% group_by(Groups) %>% mutate(rand_int=sample.int(n()))
</code>```

Body:
I am trying to set a random integer within each group of existing ID's. The integers must meet the following conditions: unique, non repeating, and the highest integer for a group of ID's will not be greater than the number of rows with that ID.

I have tried doing this in a for loop, and it works for the first group of ID's, but does not repeat for the next set. I looked at several existing stack overflow questions and other sites which address this to some degree, but still have not been able to get it right. Links below:

Randomly Assign Integers in R within groups without replacement

http://r.789695.n4.nabble.com/Random-numbers-for-a-group-td964301.html

random selection within groups

I need it to be dynamic in the sense that week by week there could be more ID's or fewer ID's. The actual DF has several other columns, but for ease of reproduction they were left out as they are not used.

Example below:

#Desired Output

Groups <- c("A","A","A","A","B","B","B","B","B","B","B","B","C","C","C","C","C","C")
Desired_Integer <- c(1,4,2,3,6,3,1,2,8,5,7,4,5,6,1,4,3,2)
Example <- data.frame(Groups,Desired_Integer)

#Attempted For Loop for Example (assuming Example is a DF with one column, Groups for the For Loop)

Groups <- c("A","A","A","A","B","B","B","B","B","B","B","B","C","C","C","C","C","C")
Example <- as.data.frame(Groups)

for (i in Example$Groups)
{
Example$Desired_Integer <- sample.int(length(which(Example$Groups == i)))
}

Thank you in advance for your help!

Body:
You can do this with the base function ave with

dd <- data.frame(Groups = rep(c("A","B","C"), c(4,8,6)))
rand_seq_for <- function(x) sample.int(length(x))
dd$rand_int <- ave(1:nrow(dd), dd$Groups, FUN=rand_seq_for)

or using dplyr, you can do

library(dplyr)
dd %>% group_by(Groups) %>% mutate(rand_int=sample.int(n()))


问:
Android Studio: SharedPreferences not working between activities
I'm currently working on an android app where I want to add a login/logout system using JDBC for the SQL and SharedPreferences to handle the sessions, the SQL works perfectly but when i go from the login activity to the main activity and try to get the values in the sharedpreferences it returns the default values.

Here is my Login Activity:

```<code>private TextView usernameHeader, passwordHeader;
private EditText username, password;
private Button loginButton;
private Handler alertHandler;
private String userRes, passwdRes;
SharedPreferences sharedPreferences;
public static final String MySession = "MySession";
public static final String nameField = "nameKey";
public static final String passwordField = "passwordKey";

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

    loginButton = (Button) findViewById(R.id.loginButton);

    username = (EditText) findViewById(R.id.username);
    password = (EditText) findViewById(R.id.passwd);

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

            sqlThread.start(); //The loginIntent is called inside the thread using a handler
        }
    });

}

public void loginIntent(){

    try{
        sharedPreferences = getSharedPreferences(MySession, Context.MODE_PRIVATE);

        SharedPreferences.Editor editor = sharedPreferences.edit();

        editor.putString(nameField, userRes);
        editor.putString(passwordField, passwdRes);
        editor.apply();
        //editor.commit();

    }catch (Exception ex){
        ex.printStackTrace();
    }

    Intent intent = new Intent(LoginActivity.this, MainActivity.class);
    startActivity(intent);

}
</code>```

Here's my Main Activity:

```<code>SharedPreferences sharedPreferences;
private String name;

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

    submitButton = (Button) findViewById(R.id.submitButton);

    mMapView = (MapView) findViewById(mapView);
    map = new ArcGISMap(Basemap.Type.TOPOGRAPHIC, 34.056295, -117.195800, 16);
    mMapView.setMap(map);

    sharedPreferences = getSharedPreferences(LoginActivity.MySession, Context.MODE_PRIVATE);

    name = (String) sharedPreferences.getString(LoginActivity.nameField,"");

    Toast.makeText(MainActivity.this,name,Toast.LENGTH_LONG).show();
}
</code>```

The Toast output is empty.

答: Have you tried checking out the values of the variables userRes and passwdRes? Based on the codes you have provided on your post, they may not have been initialized.

Body:
I'm currently working on an android app where I want to add a login/logout system using JDBC for the SQL and SharedPreferences to handle the sessions, the SQL works perfectly but when i go from the login activity to the main activity and try to get the values in the sharedpreferences it returns the default values.

Here is my Login Activity:

private TextView usernameHeader, passwordHeader;
private EditText username, password;
private Button loginButton;
private Handler alertHandler;
private String userRes, passwdRes;
SharedPreferences sharedPreferences;
public static final String MySession = "MySession";
public static final String nameField = "nameKey";
public static final String passwordField = "passwordKey";

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

    loginButton = (Button) findViewById(R.id.loginButton);

    username = (EditText) findViewById(R.id.username);
    password = (EditText) findViewById(R.id.passwd);

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

            sqlThread.start(); //The loginIntent is called inside the thread using a handler
        }
    });

}

public void loginIntent(){

    try{
        sharedPreferences = getSharedPreferences(MySession, Context.MODE_PRIVATE);

        SharedPreferences.Editor editor = sharedPreferences.edit();

        editor.putString(nameField, userRes);
        editor.putString(passwordField, passwdRes);
        editor.apply();
        //editor.commit();

    }catch (Exception ex){
        ex.printStackTrace();
    }

    Intent intent = new Intent(LoginActivity.this, MainActivity.class);
    startActivity(intent);

}

Here's my Main Activity:

SharedPreferences sharedPreferences;
private String name;

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

    submitButton = (Button) findViewById(R.id.submitButton);

    mMapView = (MapView) findViewById(mapView);
    map = new ArcGISMap(Basemap.Type.TOPOGRAPHIC, 34.056295, -117.195800, 16);
    mMapView.setMap(map);

    sharedPreferences = getSharedPreferences(LoginActivity.MySession, Context.MODE_PRIVATE);

    name = (String) sharedPreferences.getString(LoginActivity.nameField,"");

    Toast.makeText(MainActivity.this,name,Toast.LENGTH_LONG).show();
}

The Toast output is empty.


问:
Script fails when using python-shell Node.js package
So I'm having a pretty odd issue. I have a python script whose function is to analyze an image and produce an output string. I decided to implement this script into the backend of my NodeJS server using the package 'python-shell.' The funny thing is, this script works perfectly when it's run on its own. It is able to analyze the image and produce the output string. However, when I attempt to have the 'python-shell' package run it, there is an error that is produced (related to the python code). I've tested and the python-shell runs the same version of python as is used at the terminal, so I'm not 100% sure why this issue is occurring. For reference, the below code is how I'm running the script: </p>

```<code>var express = require('express');
var router = express.Router();
var pythonshell = require('python-shell');
pythonshell.defaultOptions = { scriptPath: '/path/to/myscript.py' };

var outputString = '';
var options = {args: ['-p', '/path/to/image.jpg']}
var pyshell = new pythonshell('myscript.py', options);

pyshell.on('message', function(message) {
    // received a message sent from the Python script
    console.log(message);
    outputString = message;
});

pyshell.end(function(err) {
    // This is where the error occurs
    if (err) throw err;
    console.log('Picture analysis complete');
    console.log('outputString: ' + outputString);
});
</code>```

<p>Again, when the script is manually run (i.e. python myscript.py -p image.jpg), it runs perfectly fine. I can include the code in myscript.py, although I doubt that will help as it doesn't seem to be an error with the actual python code. The image is analyzed using several packages including OpenCV (and the produced error is, I believe, based off that). Any tips are greatly appreciated! </p>

答:
change the default path
pythonshell.defaultOptions = { scriptPath: '/path/to/myscript.py' };

Body:
So I'm having a pretty odd issue. I have a python script whose function is to analyze an image and produce an output string. I decided to implement this script into the backend of my NodeJS server using the package 'python-shell.' The funny thing is, this script works perfectly when it's run on its own. It is able to analyze the image and produce the output string. However, when I attempt to have the 'python-shell' package run it, there is an error that is produced (related to the python code). I've tested and the python-shell runs the same version of python as is used at the terminal, so I'm not 100% sure why this issue is occurring. For reference, the below code is how I'm running the script:

var express = require('express');
var router = express.Router();
var pythonshell = require('python-shell');
pythonshell.defaultOptions = { scriptPath: '/path/to/myscript.py' };

var outputString = '';
var options = {args: ['-p', '/path/to/image.jpg']}
var pyshell = new pythonshell('myscript.py', options);

pyshell.on('message', function(message) {
    // received a message sent from the Python script
    console.log(message);
    outputString = message;
});

pyshell.end(function(err) {
    // This is where the error occurs
    if (err) throw err;
    console.log('Picture analysis complete');
    console.log('outputString: ' + outputString);
});

Again, when the script is manually run (i.e. python myscript.py -p image.jpg), it runs perfectly fine. I can include the code in myscript.py, although I doubt that will help as it doesn't seem to be an error with the actual python code. The image is analyzed using several packages including OpenCV (and the produced error is, I believe, based off that). Any tips are greatly appreciated!


问:
How to compile a whole c++ project
i am trying to execute a program. I have no experience with c++. I got this network generator code and wanted to try it. However, i am not able to compile it. I have tried to open a solution and then add files to visual studio, gave me errors for libraries, then tried to compile with the command prompt of visual studio, again gave me error. The readme file only says that:

-------------------- How to compile -----------------------------------

In order to compile, type:

make

I typed 'make' to every place i have found if this command is known, not working. How can i compile this project? The libraries throw several coding errors like "X variable is not declared"...etc. I don't think that the library is badly written. How to compile a project with its libraries? The direct download link and the file root link is given below. Thank you for helping me with this small problem.

A direct download link is here: https://sites.google.com/site/andrealancichinetti/files/binary_networks.tar.gz?attredirects=0&d=1

The project is here, the first one:
https://sites.google.com/site/andrealancichinetti/files

答:
Without posting any code, answers to these will be difficult but, to get you started I will post some beginner related stuff here.

I would recommend to first watch a video on how to use visual studio C++:
https://www.youtube.com/watch?v=-PAn2V3j1wA

This video will show how to compile a project.

And then, I would recommend getting some basic understanding in C++ or you will be overwhelmed with everything. Here is a good site to get started:

http://www.learncpp.com/

Hope this helps

Title: How to compile a whole c++ project


问:
Unable to force left align text in rmarkdown document
I'm using R markdown for a university assignment. I'd like to have questions number/letters left aligned on my document, but rmarkdown is adding spaces before "a)" and "b)", which I'd like to be aligned with the rest of my text.

```<code> ---
title: "Untitled"
author: "dsn084"
date: "26 March 2017"
output: pdf_document
---

This is a paragraph.

a) this is part a.

b) this is part b.
</code>```

And my output ...

答:
As you are using output: pdf_document, the rmarkdown document will be converted into latex before pdf, so you can use latex instructions to accomplish that.

flushleft will do it. Example:

This is a paragraph.

\begin{flushleft}

a) this is part a.

b) this is part b.

\end{flushleft}

Body:
I'm using R markdown for a university assignment. I'd like to have questions number/letters left aligned on my document, but rmarkdown is adding spaces before "a)" and "b)", which I'd like to be aligned with the rest of my text.

 ---
title: "Untitled"
author: "dsn084"
date: "26 March 2017"
output: pdf_document
---

This is a paragraph.

a) this is part a.

b) this is part b.

And my output ...


问:
Algolia : Search result order
I have some difficulties in the ranking configuration in algolia.
I have a resultset like this when I search for "Contrat" :

[
  {
    "ope_id" : 1,
    "ope_lib" : "Contrat de maintenance en entretien de toitures",
    "ope_description" : "Réalisation d'un entretien régulier des toitures",
    "ope_nb_offre" : "42"
  },
  {
    "ope_id" : 2,
    "ope_lib" : "Contrat d'entretien de pompe à chaleur",
    "ope_description" : "
Confort et sécurité au quotidien

Votre domicile est équipé d’une pompe à chaleur comme système de chauffage ?
Qu’elle soit géothermique ou aérothermique, il est indispensable de veiller à son entretien. En effet, en cas de dysfonctionnement, son efficacité sera réduite ce qui nuira à votre confort intérieur.En souscrivant un contrat d’entretien avec un professionnel pour votre pompe à chaleur, la durée de vie de votre installation sera prolongée et ses performances seront en permanence optimales, vous évitant ainsi toute augmentation de vos dépenses énergétiques.
Le contrat d’entretien inclut :

Une révision annuelle de votre pompe à chaleur

La vérification des fluides frigorigènes par un professionnel certifié Qualipac (opération imposée par la réglementation sur les appareils contenant plus de 2 kg de fluide)

le remplacement des pièces et accessoires usagés

un service de dépannage

",
    "ope_nb_offre" : "41"
  },
  {
   "ope_id" : 3,
    "ope_lib" : "Contrat d'entretien de chaudière murale au gaz",
    "ope_description" : "
Economie d'énergie et sécurité de votre habitat

Pour le chauffage et la production d’eau chaude, vous utilisez une chaudière au gaz ?
Les défaillances de cet appareil peuvent avoir des conséquences désagréables voire dangereuses. Afin d’éviter les risques de panne ou d’intoxication, vous avez la possibilité de souscrire un contrat d’entretien auprès d’un professionnel spécialisé. Ce contrat vous garantira le bon état permanent de votre chaudière, il comprend :
Une visite annuelle incluant :

 Le nettoyage des composants de votre chaudière ( corps de chauffe , brûleur , extracteur, veilleuse)

 Le réglage des organes de régulations et des systèmes de sécurité

 La vérification de l’état, de la nature et de la géométrie du conduit de raccordement de l’appareil.

 La mesure des polluants atmosphériques (teneur en monoxyde de carbone)

 Le contrôle des points liés à la sécurité des biens et des personnes (entrée d\'air, évacuation des gaz de combustion)

Un dépannage éventuel sur appel justifié du souscripteur du contrat

Certificat nécessaire à votre assurance
",
    "ope_nb_offre" : "265"
  }
]```
</div>
</div>
</p>

<p>And I don't understand why the ope_id 1 is displayed before the other.
Here is ma algolia config :
Searchable attributes : "ope_lib,ope_description" (unordered)
Custom ranking attributes : "ope_nb_offre".
Sort by attributes : false.
Ranking formula :
- typo
- attribute
- exact
- geo
- words
- filters
- proximity
Custom ranking criteria (as said above) : desc(op_nb_offre).</p>

<p>ope_id 3 has more occurrences of my search keyword "contrat" AND ha more ope_nb_offre than the other, but it still is displayed after them.</p>

<p>If it helps, here is the ranking info for each result :</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>OPE_ID 1:
1 Number of typos 0
2 Best matching attribute
- ope_lib,ope_description (1st word)
3 Exact words count 0 (=> Why 0??)
4 Matching words 1
5 Matching filters 0
6 Proximity distance 0
7 Custom Ranking
- ope_nb_offre_total=42

OPE_ID 2
1 Number of typos 0
2 Best matching attribute
- ope_lib,ope_description (1st word)
3 Exact words count 0 (=> Why 0??)
4 Matching words 1
5 Matching filters 0
6 Proximity distance 0
7 Custom Ranking
- ope_nb_offre_total=41
was
- ope_nb_offre_total=42

OPE_ID 3
1 Number of typos 0
2 Best matching attribute
- ope_lib,ope_description (1st word)
3 Exact words count 0
4 Matching words 1
5 Matching filters 0
6 Proximity distance 0
7 Custom Ranking
- ope_nb_offre_total=265
was
- ope_nb_offre_total=27 (=> and why is 27 after 265??)</code>```

I think I gave all the information I had. If anyone has any clue, please let me know!

Thanks!

答:
Why is 27 after 265?

The attribute ope_nb_offre has been pushed to Algolia as a string.
What this means, is that when the engine reaches the custom ranking rule to determine what record is most relevant
it will actually try to sort alphabetically instead of numerically.

To solve this, you should re-index your data and make sure you cast that attribute as an integer.

Why you have no exact words count

Algolia uses prefix matching to determine the text relevancy of a record.
Prefix matching means that if you type "soft" it will return results having a searchable attribute containing for example
"software".

As long as your word is not finished though, the query string is considered as a prefix, meaning it is not a perfect match.
The engine has no way to know if you have finished typing.

If you were to add a "space" after "Contrat " then you will see exact matches.

Words frequency

My assumption here is that you have the following configuration in Algolia:

Searchable attributes:

unordered(ope_lib)

unordered(ope_description)

What you tell the engine here, is that it should first try to find matching words in ope_lib and then in ope_description.
What is important here is the order in which those appear in the configuration.

In your configuration, if something matched in the ope_lib, then no matching will be done on ope_description.

To solve this, you can add both those attributes at the same level in the dashboard.
Here is a screenshot to illustrate what you should be doing.
Please note that in this case, you don't need to wrap the attributes into unordered given it is the default if you have multiple attributes
 at the same level.

Title: Algolia : Search result order

Body:
I have some difficulties in the ranking configuration in algolia.
I have a resultset like this when I search for "Contrat" :

[
  {
    "ope_id" : 1,
    "ope_lib" : "Contrat de maintenance en entretien de toitures",
    "ope_description" : "Réalisation d'un entretien régulier des toitures",
    "ope_nb_offre" : "42"
  },
  {
    "ope_id" : 2,
    "ope_lib" : "Contrat d'entretien de pompe à chaleur",
    "ope_description" : "
Confort et sécurité au quotidien

Votre domicile est équipé d’une pompe à chaleur comme système de chauffage ?
Qu’elle soit géothermique ou aérothermique, il est indispensable de veiller à son entretien. En effet, en cas de dysfonctionnement, son efficacité sera réduite ce qui nuira à votre confort intérieur.En souscrivant un contrat d’entretien avec un professionnel pour votre pompe à chaleur, la durée de vie de votre installation sera prolongée et ses performances seront en permanence optimales, vous évitant ainsi toute augmentation de vos dépenses énergétiques.
Le contrat d’entretien inclut :

Une révision annuelle de votre pompe à chaleur

La vérification des fluides frigorigènes par un professionnel certifié Qualipac (opération imposée par la réglementation sur les appareils contenant plus de 2 kg de fluide)

le remplacement des pièces et accessoires usagés

un service de dépannage

",
    "ope_nb_offre" : "41"
  },
  {
   "ope_id" : 3,
    "ope_lib" : "Contrat d'entretien de chaudière murale au gaz",
    "ope_description" : "
Economie d'énergie et sécurité de votre habitat

Pour le chauffage et la production d’eau chaude, vous utilisez une chaudière au gaz ?
Les défaillances de cet appareil peuvent avoir des conséquences désagréables voire dangereuses. Afin d’éviter les risques de panne ou d’intoxication, vous avez la possibilité de souscrire un contrat d’entretien auprès d’un professionnel spécialisé. Ce contrat vous garantira le bon état permanent de votre chaudière, il comprend :
Une visite annuelle incluant :

 Le nettoyage des composants de votre chaudière ( corps de chauffe , brûleur , extracteur, veilleuse)

 Le réglage des organes de régulations et des systèmes de sécurité

 La vérification de l’état, de la nature et de la géométrie du conduit de raccordement de l’appareil.

 La mesure des polluants atmosphériques (teneur en monoxyde de carbone)

 Le contrôle des points liés à la sécurité des biens et des personnes (entrée d\'air, évacuation des gaz de combustion)

Un dépannage éventuel sur appel justifié du souscripteur du contrat

Certificat nécessaire à votre assurance
",
    "ope_nb_offre" : "265"
  }
]

And I don't understand why the ope_id 1 is displayed before the other.
Here is ma algolia config :
Searchable attributes : "ope_lib,ope_description" (unordered)
Custom ranking attributes : "ope_nb_offre".
Sort by attributes : false.
Ranking formula :
- typo
- attribute
- exact
- geo
- words
- filters
- proximity
Custom ranking criteria (as said above) : desc(op_nb_offre).

ope_id 3 has more occurrences of my search keyword "contrat" AND ha more ope_nb_offre than the other, but it still is displayed after them.

If it helps, here is the ranking info for each result :

OPE_ID 1:
1 Number of typos 0
2 Best matching attribute
- ope_lib,ope_description (1st word)
3 Exact words count 0 (=> Why 0??)
4 Matching words 1
5 Matching filters 0
6 Proximity distance 0
7 Custom Ranking
- ope_nb_offre_total=42

OPE_ID 2
1 Number of typos 0
2 Best matching attribute
- ope_lib,ope_description (1st word)
3 Exact words count 0 (=> Why 0??)
4 Matching words 1
5 Matching filters 0
6 Proximity distance 0
7 Custom Ranking
- ope_nb_offre_total=41
was
- ope_nb_offre_total=42

OPE_ID 3
1 Number of typos 0
2 Best matching attribute
- ope_lib,ope_description (1st word)
3 Exact words count 0
4 Matching words 1
5 Matching filters 0
6 Proximity distance 0
7 Custom Ranking
- ope_nb_offre_total=265
was
- ope_nb_offre_total=27 (=> and why is 27 after 265??)

I think I gave all the information I had. If anyone has any clue, please let me know!

Thanks!


问:
What is the impact of writes to a cassandra cluster that is hosting analytics jobs?
I am considering a heavily analytics based spark cluster that also has to consume some writes from a response time sensitive UI.

Will the analytics jobs impact or hinder my rest response time ?

Will it have any other impact ?

答:
Your best bet would be to keep multiple separate data centres. I couldn't find the blog about newest version of DSE but all the principles from the article still apply and the principles are applicable for the community cassandra too.

https://docs.datastax.com/en/datastax_enterprise/4.5/datastax_enterprise/deploy/deployWkLdSep.html


问:
What is the meaning of 'No bundle URL present' in react-native?
When I run a react-native project, I get a error no bundle URL present , but I don't know what mistakes I do, I was very confused.

答:
This is an issue with react-native v0.42.1. Try to close all terminal and XCode instances and run:</p>

```<code>launchctl unload ~/Library/LaunchAgents/com.github.facebook.watchman.plist
watchman version
react-native run-ios
</code>```

ContentLicense: CC BY-SA 4.0

Body:
This is an issue with react-native v0.42.1. Try to close all terminal and XCode instances and run:

launchctl unload ~/Library/LaunchAgents/com.github.facebook.watchman.plist
watchman version
react-native run-ios


问:
How to deal with API response
I was able to connect to Mind Body api and run a simple command to get all clients data

```<code>from Helper.ClientService import ClientServiceCalls

calls = ClientServiceCalls()
clients = calls.GetAllClients()
print(clients)
</code>```

the server will respond with these information:

```<code>(GetClientsResult){
   Status = "Success"
   ErrorCode = 200
   XMLDetail = "Full"
   ResultCount = 4503
   CurrentPageIndex = 0
   TotalPageCount = 181
   Clients =
      (ArrayOfClient){
         Client[] =
            (Client){
               MobileProvider = None
               AppointmentGenderPreference = "None"
               Gender = "Female"
               IsCompany = False
               LiabilityRelease = False
               PromotionalEmailOptIn = True
               CreationDate = 2017-02-23 00:00:00
               Liability =
                  (Liability){
                     IsReleased = False
                     AgreementDate = None
                     ReleasedBy = None
                  }
               UniqueID = 100015484
               ID = "100015484"
               FirstName = "Sdfoij"
               LastName = "[asodfj"
               EmailOptIn = True
               State = "CA"
               Country = "US"
               BirthDate = None
               FirstAppointmentDate = 2017-03-03 00:00:00
               HomeLocation =
                  (Location){
                     SiteID = -99
                     BusinessDescription = ""The MINDBODY Health Club Demo is awesome." - Anonymous (but probably someone cool and smart)"
                     AdditionalImageURLs = ""
                     FacilitySquareFeet = None
                     TreatmentRooms = None
                     HasClasses = True
                     PhoneExtension = None
                     ID = 1
                     Name = "Clubville"
                  }
               PhotoURL = "https://clients.mindbodyonline.com/studios/DemoAPISandboxRestore/clients/100015484_large.jpg?v=98"
               IsProspect = False
               Status = "Active"
               ContactMethod = 1
            }.... **and continue printing other client informations**

     }
 }
</code>```

now The issue is i want to extract these info from it,

```<code>Client Email, Client Name, Client Phone Number, Client Status (active or inactive), Client Birthday, Client Address, Most Recent Visit Date, Most Recent Visit Description, Start Date, Custom Field(s)
</code>```

But i don't know what Library I can use to parse through this output, I am thinking about Beautiful Soup but I am not really sure,

I am really newbie to working with apis, so if anyone could give me an idea about how to do this it would be really great.

答:
OK, I did a search on mindbody WSDL in the googs and got back the following link: https://api.mindbodyonline.com/0_5/SiteService.asmx?wsdl. From looking at the code in the API examples it looks like they are definitely using SOAP. My recommendation is that you try the following:

```<code>from suds.client import Client
from Helper.ClientService import ClientServiceMethods
calls = ClientServiceMethods()
clients = calls.GetAllClients()
client_dict = Client.dict(clients)
</code>```

Or take a look at this link for taking a response and turning it into a dict.

Title: How to deal with API response

Body:
I was able to connect to Mind Body api and run a simple command to get all clients data

from Helper.ClientService import ClientServiceCalls

calls = ClientServiceCalls()
clients = calls.GetAllClients()
print(clients)

the server will respond with these information:

(GetClientsResult){
   Status = "Success"
   ErrorCode = 200
   XMLDetail = "Full"
   ResultCount = 4503
   CurrentPageIndex = 0
   TotalPageCount = 181
   Clients =
      (ArrayOfClient){
         Client[] =
            (Client){
               MobileProvider = None
               AppointmentGenderPreference = "None"
               Gender = "Female"
               IsCompany = False
               LiabilityRelease = False
               PromotionalEmailOptIn = True
               CreationDate = 2017-02-23 00:00:00
               Liability =
                  (Liability){
                     IsReleased = False
                     AgreementDate = None
                     ReleasedBy = None
                  }
               UniqueID = 100015484
               ID = "100015484"
               FirstName = "Sdfoij"
               LastName = "[asodfj"
               EmailOptIn = True
               State = "CA"
               Country = "US"
               BirthDate = None
               FirstAppointmentDate = 2017-03-03 00:00:00
               HomeLocation =
                  (Location){
                     SiteID = -99
                     BusinessDescription = ""The MINDBODY Health Club Demo is awesome." - Anonymous (but probably someone cool and smart)"
                     AdditionalImageURLs = ""
                     FacilitySquareFeet = None
                     TreatmentRooms = None
                     HasClasses = True
                     PhoneExtension = None
                     ID = 1
                     Name = "Clubville"
                  }
               PhotoURL = "https://clients.mindbodyonline.com/studios/DemoAPISandboxRestore/clients/100015484_large.jpg?v=98"
               IsProspect = False
               Status = "Active"
               ContactMethod = 1
            }.... **and continue printing other client informations**

     }
 }

now The issue is i want to extract these info from it,

Client Email, Client Name, Client Phone Number, Client Status (active or inactive), Client Birthday, Client Address, Most Recent Visit Date, Most Recent Visit Description, Start Date, Custom Field(s)

But i don't know what Library I can use to parse through this output, I am thinking about Beautiful Soup but I am not really sure,

I am really newbie to working with apis, so if anyone could give me an idea about how to do this it would be really great.

Body:
OK, I did a search on mindbody WSDL in the googs and got back the following link: https://api.mindbodyonline.com/0_5/SiteService.asmx?wsdl. From looking at the code in the API examples it looks like they are definitely using SOAP. My recommendation is that you try the following:

from suds.client import Client
from Helper.ClientService import ClientServiceMethods
calls = ClientServiceMethods()
clients = calls.GetAllClients()
client_dict = Client.dict(clients)

Or take a look at this link for taking a response and turning it into a dict.


问:
How to display output of tasks of an Ansible playbook without using the '-v' option
I have the following task to print out the current version of jenkins that is installed on some servers:

```<code>---
- hosts: all
  remote_user: user
  tasks:
      - name: Printing the Jenkins version running on the masters
        yum:
          name: jenkins
        register: version

      - debug: var=version
</code>```

I am trying to avoid using the -v option when running the playbook with hopes to keep the output as clean as possible.

If the playbook is run without the -v option the output looks like this:

```<code>TASK [Printing the jenkins version that is installed on each of the servers]***************
ok: [Server1]
ok: [Server2]
ok: [Server3]

TASK [debug] *******************************************************************    ok: [Server1] => {
"changed": false,
"version": "VARIABLE IS NOT DEFINED!"
}

ok: [Server1] => {
"changed": false,
"version": "VARIABLE IS NOT DEFINED!"
}

ok: [Server1] => {
"changed": false,
"version": "VARIABLE IS NOT DEFINED!"
}
</code>```

However it returns that version is not defined. I am confused as to why this is happening because I have done the printing the same way for a bunch of other tasks without any problems. Any suggestions are greatly appreciated.

答:
You can create ansible callback plugin, or use one available in network
i.e.

human_log

Body:
I have the following task to print out the current version of jenkins that is installed on some servers:

---
- hosts: all
  remote_user: user
  tasks:
      - name: Printing the Jenkins version running on the masters
        yum:
          name: jenkins
        register: version

      - debug: var=version

I am trying to avoid using the -v option when running the playbook with hopes to keep the output as clean as possible.

If the playbook is run without the -v option the output looks like this:

TASK [Printing the jenkins version that is installed on each of the servers]***************
ok: [Server1]
ok: [Server2]
ok: [Server3]

TASK [debug] *******************************************************************    ok: [Server1] => {
"changed": false,
"version": "VARIABLE IS NOT DEFINED!"
}

ok: [Server1] => {
"changed": false,
"version": "VARIABLE IS NOT DEFINED!"
}

ok: [Server1] => {
"changed": false,
"version": "VARIABLE IS NOT DEFINED!"
}

However it returns that version is not defined. I am confused as to why this is happening because I have done the printing the same way for a bunch of other tasks without any problems. Any suggestions are greatly appreciated.


问:
Is there some kind of tool to look at the encoding of Intel x86 instructions?
Forgive me if this might be a dumb question but, I'm in an assembly class that was mostly taught using an emulated CPU that was supposed to teach the concepts of assembly code. We haven't even written an Intel program, so I'm trying to adjust. In our emulated CPU, we were able to generate a symbol table file that gave the bytes equivalent for instructions:

http://imgur.com/tw5S8.png

Would I be able to do such a thing with Intel x86 instructions?

答:
Try IDA. It has an option to show binary values of opcodes.

EDIT: Well.. it's a disassembler. Try opening a binary file, and set the number of opcode bytes to show (in Options/General/)  to something that is not zero.

If you are looking for an IDE that shows you in real time the opcodes for the instruction you've used, then I don't think you'll find one, because of lack of "market". Can you explain why you need it? Do you want to know just their length, or want to learn them? There is simple pattern for lengths, so by dissasembling many binaries you'll catch it. If it's the opcodes you want.. well, there are lots of them, almost no rules, and practically no use to do it.

I see.. then you have to generate the list file . Your assembler should have an option for that. (for NASM it's -l listfile). Just put any instruction(s) in your .asm file, and generate listing for it. It should contain the binary encoding for each instruction.

First, get Intel Instruction Set Refference, or, better, this link: http://siyobik.info/index.php?module=x86 . There you'll find that most opcodes have several encodings. In your particular case, the bit 1 of the opcode specifies direction, and since both operands are registers, you can toggle the direction and swap the register codes, and the result will be the same. Usually you have this freedom on most register to register arithmetic operations. To check this, try decompiling with IDA this source file:

```<code>db 02h, E0h
db 00h, C4h
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Try IDA. It has an option to show binary values of opcodes.

EDIT: Well.. it's a disassembler. Try opening a binary file, and set the number of opcode bytes to show (in Options/General/)  to something that is not zero.

If you are looking for an IDE that shows you in real time the opcodes for the instruction you've used, then I don't think you'll find one, because of lack of "market". Can you explain why you need it? Do you want to know just their length, or want to learn them? There is simple pattern for lengths, so by dissasembling many binaries you'll catch it. If it's the opcodes you want.. well, there are lots of them, almost no rules, and practically no use to do it.

I see.. then you have to generate the list file . Your assembler should have an option for that. (for NASM it's -l listfile). Just put any instruction(s) in your .asm file, and generate listing for it. It should contain the binary encoding for each instruction.

First, get Intel Instruction Set Refference, or, better, this link: http://siyobik.info/index.php?module=x86 . There you'll find that most opcodes have several encodings. In your particular case, the bit 1 of the opcode specifies direction, and since both operands are registers, you can toggle the direction and swap the register codes, and the result will be the same. Usually you have this freedom on most register to register arithmetic operations. To check this, try decompiling with IDA this source file:

db 02h, E0h
db 00h, C4h


问:
"many to many to many" relation
I have a simple database of cosmetics. Each product may consist of multiple ingredients. Therefore it is a simple many to many relation and currently I have a database like this:

```<code>CREATE TABLE `products` (
  `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `name` TEXT NOT NULL,
  PRIMARY KEY (`id`),
);

CREATE TABLE `ingredients` (
  `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `name` TEXT NOT NULL,
  PRIMARY KEY (`id`),
);

CREATE TABLE `ingredient_to_product` (
  `ingredient_id` INT UNSIGNED NOT NULL,
  `product_id` INT UNSIGNED NOT NULL,
  PRIMARY KEY (`ingredient_id`, `product_id`),
  INDEX (`product_id`)
);
</code>```

However, some ingredients can have many different names. For example: "LINALOOL ESSENTIAL OIL", "LINALYL ALCOHOL" and "3,7-DIMETHYL-1,6-OCTADIEN-3-OL" refers to the same ingredient.

When I am presenting one product, I would like to keep ingredient name as on product label. So in case of one product it will be "LINALYL ALCOHOL" and in case of another product it may be something other, but referring to identical ingredient.

Now I would like to query database for all names of the product by specifying one of its names or by its ID, however how one ID could refer to many names? Do I have to keep two tables: one for specific ingredient in general and another table just for names (relation many names to one ingredient)? Is there any better way?

答: Why don't you create a separate table for other ingredient name/chemical names, etc. and have it connected with the product id so it can be used separately when needed, and to avoid having any NULL values in your main table.</p>

Title: "many to many to many" relation

Body:
I have a simple database of cosmetics. Each product may consist of multiple ingredients. Therefore it is a simple many to many relation and currently I have a database like this:

CREATE TABLE `products` (
  `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `name` TEXT NOT NULL,
  PRIMARY KEY (`id`),
);

CREATE TABLE `ingredients` (
  `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `name` TEXT NOT NULL,
  PRIMARY KEY (`id`),
);

CREATE TABLE `ingredient_to_product` (
  `ingredient_id` INT UNSIGNED NOT NULL,
  `product_id` INT UNSIGNED NOT NULL,
  PRIMARY KEY (`ingredient_id`, `product_id`),
  INDEX (`product_id`)
);

However, some ingredients can have many different names. For example: "LINALOOL ESSENTIAL OIL", "LINALYL ALCOHOL" and "3,7-DIMETHYL-1,6-OCTADIEN-3-OL" refers to the same ingredient.

When I am presenting one product, I would like to keep ingredient name as on product label. So in case of one product it will be "LINALYL ALCOHOL" and in case of another product it may be something other, but referring to identical ingredient.

Now I would like to query database for all names of the product by specifying one of its names or by its ID, however how one ID could refer to many names? Do I have to keep two tables: one for specific ingredient in general and another table just for names (relation many names to one ingredient)? Is there any better way?


问:
ChromeOptions AddUserProfilePreference
I am using Webdriver 3.3.1 with Java. I am trying to disable the pop-up asking to save passwords. Based on search results I need to use
ChromOptions.AddUserProfilePreference("","")
However, there is no AddUserProfilePreference
the only add method is addArguments.

I am using Eclipse Neon.2 and Java 1.8

答:
With ChromeDriver 2.28 & Selenium 3.3.1, the following works:</p>

```<code>final DesiredCapabilities capabilities = DesiredCapabilities.chrome();
final ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.addArguments("--start-maximized");
Map<String, Object> prefs = new LinkedHashMap<>();
prefs.put("credentials_enable_service", Boolean.valueOf(false));
prefs.put("profile.password_manager_enabled", Boolean.valueOf(false));
chromeOptions.setExperimentalOption("prefs", prefs);
capabilities.setCapability(ChromeOptions.CAPABILITY, chromeOptions);
WebDriver driver = new ChromeDriver(capabilities);
</code>```

Title: ChromeOptions AddUserProfilePreference

Body:
With ChromeDriver 2.28 & Selenium 3.3.1, the following works:

final DesiredCapabilities capabilities = DesiredCapabilities.chrome();
final ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.addArguments("--start-maximized");
Map<String, Object> prefs = new LinkedHashMap<>();
prefs.put("credentials_enable_service", Boolean.valueOf(false));
prefs.put("profile.password_manager_enabled", Boolean.valueOf(false));
chromeOptions.setExperimentalOption("prefs", prefs);
capabilities.setCapability(ChromeOptions.CAPABILITY, chromeOptions);
WebDriver driver = new ChromeDriver(capabilities);


问:
Populating a JList using a JButton and Populating the JTextField using DoubleClick on the Jlist
I am trying to populate a JList through a button, and then populate the JTextField using DoubleClick on the previously populated Jlist.

Code:

```<code> private void extractUsedVariablesActionPerformed(java.awt.event.ActionEvent evt) {
     // TODO add your handling code here:

     if(arguments.size() > 0)
        JOptionPane.showMessageDialog(null, "Please complete the predicates before accessing this");

     DefaultListModel lista1 = new DefaultListModel();
     for (int i = 0;i<variableList.size();i++)
        {
        if (!lista1.contains(variableList.get(i)))
        {
        lista1.addElement(variableList.get(i));
        }
        }
     argVariables_List.setModel(lista1);
     revalidate();
     repaint();

    if (lista1.size()>0){
         System.out.println("got here1");
         MouseListener mouseListener2 = new MouseAdapter()
              {
                public void mouseClicked1(MouseEvent mouseEvent2)
                 {
                  JList varList = (JList) mouseEvent2.getSource();
                      if (mouseEvent2.getClickCount() == 2)
                         {
                         System.out.println("may be");
                         int index varList.locationToIndex(mouseEvent2.getPoint());
                        if (index >= 0)
                         {
                          Object o2 = varList.getModel().getElementAt(index);
                          System.out.println(o2.toString());
                        }
                      }
                    }
                  };
                   argVariables_List.addMouseListener(mouseListener2);
    }

}
</code>```

It is working fine till populating the Jlist. But when I try the doubleclick operation and print the text at the clicked index I am not getting any output neither any errors. Please suggest me if I am missing something.

答:
```<code>public void mouseClicked1(MouseEvent mouseEvent2)
</code>```

There is no such method in the MouseListener interface. (note the "1").

Make sure you include @Override in the line above the method and you will get a compiler error when you make a typo.

```<code>@Override
public void mouseClicked1(MouseEvent mouseEvent2)
</code>```

Body:
I am trying to populate a JList through a button, and then populate the JTextField using DoubleClick on the previously populated Jlist.

Code:

 private void extractUsedVariablesActionPerformed(java.awt.event.ActionEvent evt) {
     // TODO add your handling code here:

     if(arguments.size() > 0)
        JOptionPane.showMessageDialog(null, "Please complete the predicates before accessing this");

     DefaultListModel lista1 = new DefaultListModel();
     for (int i = 0;i<variableList.size();i++)
        {
        if (!lista1.contains(variableList.get(i)))
        {
        lista1.addElement(variableList.get(i));
        }
        }
     argVariables_List.setModel(lista1);
     revalidate();
     repaint();

    if (lista1.size()>0){
         System.out.println("got here1");
         MouseListener mouseListener2 = new MouseAdapter()
              {
                public void mouseClicked1(MouseEvent mouseEvent2)
                 {
                  JList varList = (JList) mouseEvent2.getSource();
                      if (mouseEvent2.getClickCount() == 2)
                         {
                         System.out.println("may be");
                         int index varList.locationToIndex(mouseEvent2.getPoint());
                        if (index >= 0)
                         {
                          Object o2 = varList.getModel().getElementAt(index);
                          System.out.println(o2.toString());
                        }
                      }
                    }
                  };
                   argVariables_List.addMouseListener(mouseListener2);
    }

}

It is working fine till populating the Jlist. But when I try the doubleclick operation and print the text at the clicked index I am not getting any output neither any errors. Please suggest me if I am missing something.

Body:
public void mouseClicked1(MouseEvent mouseEvent2)

There is no such method in the MouseListener interface. (note the "1").

Make sure you include @Override in the line above the method and you will get a compiler error when you make a typo.

@Override
public void mouseClicked1(MouseEvent mouseEvent2)


问:
Enable ion-list of ion-menu after login
I have to do something like that:
when I click to the login, a page will appear and it verifies connection to database ( which is well done ), if success it will be redirected to homePage, the hidden ion-list(<ion-list hidden  #menu2 >) should appear in the menu.

import { Component } from '@angular/core';
import { NavController,MenuController ,NavParams,AlertController,LoadingController,ViewController} from 'ionic-angular';
import {Http} from "@angular/http";
import 'rxjs/add/operator/map';
import {HomePage} from '../home/home';
import { MyService } from '../../providers/my-service';
import { Storage } from '@ionic/storage';

@Component({
  selector: 'page-modal-page',
  templateUrl: 'modal-page.html',
  providers: [MyService]
})
export class ModalPagePage {
  data:any;
ftechdata:any;

  constructor(public navCtrl: NavController ,public viewCtrl:ViewController, private http:Http,private alert :AlertController,private loading:LoadingController) {
    this.data={};
    this.data.username="";
    this.data.password="";

  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad LoginPage');
  }
login(){
let username=this.data.username;
let password=this.data.password;
let data =JSON.stringify({username,password});
let link="https://stationpfe.000webhostapp.com/login.php";
this.http.post(link,data)
.subscribe(data=>{
let loader=this.loading.create({
 content:"cheking! please wait...",
    duration:1000
  });
  loader.present();
  this.navCtrl.setRoot(HomePage);
  //

},error=>{
let alert =this.alert.create({
title:'warning',
subTitle:'wrong username or password !please try agin !',
buttons:['Ok']
  });
  alert.present();
});

}

close() {
    this.viewCtrl.dismiss(); // This works fine
  }
  showPopup(){
console.log("action sur label ");
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ion-menu [content]="content" >
  <ion-header>
    <!--> lec hangement de couleur pour la liste des items page app.html, app.scss<-->
    <ion-toolbar color="danger"  >
      <ion-title > MyApp </ion-title>
    </ion-toolbar>
  </ion-header>

  <ion-content  class="custom">
    <ion-list >
       <ion-list-header>
          Navigate
        </ion-list-header>
      <button menuClose ion-item *ngFor="let p of pages" (click)="openPage(p)" >
       <ion-icon  name="alarm"  item-left> </ion-icon>

        {{p.title}}
      </button>
    </ion-list>

    <ion-list hidden  #menu2 >
      <ion-list-header>
          Account
        </ion-list-header>
      <button menuClose ion-item *ngFor="let p of pages1" (click)="openPage(p)" >

        {{p.title}}
      </button>
    </ion-list>

  </ion-content>

</ion-menu>

<!--  swipeBackEnabled="false"   Disable swipe-to-go-back because it's poor UX to combine STGB with side menus -->
<ion-nav [root]="rootPage" #content ></ion-nav></code>```

import { Component, ViewChild } from '@angular/core';
import { Nav, Platform } from 'ionic-angular';
import { StatusBar, Splashscreen } from 'ionic-native';

import { TabsPage } from '../pages/tabs/tabs';

import { SettingsPage } from '../pages/settings/settings';
import { AccountPage } from '../pages/account/account';
import { VoiturePage } from '../pages/voiture/voiture';
 import { LoginPage } from '../pages/login/login';
 import { TarifPage } from '../pages/tarif/tarif';
  import { HomePage } from '../pages/home/home';
  import { ModalPagePage } from '../pages/modal-page/modal-page';
  import { ListevoiturePage } from '../pages/listevoiture/listevoiture';

  import { InsertvoiturePage } from '../pages/insertvoiture/insertvoiture';

@Component({
  templateUrl: 'app.html',
 providers: [ModalPagePage]
})
export class MyApp {
  @ViewChild(Nav) nav: Nav;

  rootPage = HomePage;

  pages: Array<{title: string, component: any}>;
 pages1: Array<{title: string, component: any}>;
  constructor(public platform: Platform) {
    this.initializeApp();

this.pages = [
      { title: ' Home', component: TabsPage },
      { title: 'tickets' , component: TarifPage },
      { title: 'login', component: LoginPage },

    ];
    this.pages1 = [
      { title: 'liste Voiture', component: InsertvoiturePage},

    ];

  }
  openPage(page) {

    this.nav.setRoot(page.component);

  }

  initializeApp() {
    this.platform.ready().then(() => {
      // Okay, so the platform is ready and our plugins are available.
      // Here you can do any higher level native things you might need.
      StatusBar.styleDefault();
      Splashscreen.hide();

    });
  }
}```

答:
loginPage.ts

import { Component } from '@angular/core';
import { NavController, ModalController } from 'ionic-angular';
import { Storage } from '@ionic/storage';
import { ModalPagePage } from '../modal-page/modal-page';
import {HomePage} from '../home/home';

@Component({
  selector: 'page-login',
  templateUrl: 'login.html'
})
export class LoginPage {

  data: any;
  public getsession: any;
  x: any;

  public local: Storage;
  constructor(public navCtrl: NavController,public modalCtrl:ModalController) {
    this.data = {};
    this.data.title = "";
    this.data.desc = "";
    this.local = new Storage;
    this.local.set('session', 'true');

  }

      ionViewWillEnter() {
     this.getsession = this.local.get('session');
      this.getsession.then((value)=>{
       this.x = value;
      if( this.x !== ""){
         let modal = this.modalCtrl.create(ModalPagePage);
         modal.present();
        //this.navCtrl.setRoot(ModalPagePage);

    }
    });
  }

}```
</div>
</div>
</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>homePage.ts

import { Component } from '@angular/core';

import { NavController, AlertController } from 'ionic-angular';
import {ContactPage} from '../../pages/contact/contact';
import {AccountPage} from '../../pages/account/account';
import {ListevoiturePage} from '../../pages/listevoiture/listevoiture';
import {VoitureService} from '../../providers/voitureservice';
@Component({
  selector: 'page-home',
  templateUrl: 'home.html',
  providers:[VoitureService],

  styles: [`
    @media (max-width: 600px) {
      .hide-xs {
        display: none;
      }
    }
  `],
})
export class HomePage {
showbutton:boolean = false;
 nbr:any;
  constructor(public navCtrl: NavController,public alertCtrl: AlertController,public voitureservice:VoitureService) {
  this.getNombreVoiture();

  }
   getNombreVoiture(){
    this.voitureservice.nombrevoiture().subscribe(response=>
{
  this.nbr=response.Nombre;

});
  }
openContact() {
        this.navCtrl.push(ContactPage);
    }

goToPage1() {
   this.navCtrl.push(AccountPage);
 }

  goListeVoiture(){
  this.navCtrl.push(ListevoiturePage);
  }
}</code>```

Title: Enable ion-list of ion-menu after login

Body:
I have to do something like that:
when I click to the login, a page will appear and it verifies connection to database ( which is well done ), if success it will be redirected to homePage, the hidden ion-list(<ion-list hidden  #menu2 >) should appear in the menu.

import { Component } from '@angular/core';
import { NavController,MenuController ,NavParams,AlertController,LoadingController,ViewController} from 'ionic-angular';
import {Http} from "@angular/http";
import 'rxjs/add/operator/map';
import {HomePage} from '../home/home';
import { MyService } from '../../providers/my-service';
import { Storage } from '@ionic/storage';

@Component({
  selector: 'page-modal-page',
  templateUrl: 'modal-page.html',
  providers: [MyService]
})
export class ModalPagePage {
  data:any;
ftechdata:any;

  constructor(public navCtrl: NavController ,public viewCtrl:ViewController, private http:Http,private alert :AlertController,private loading:LoadingController) {
    this.data={};
    this.data.username="";
    this.data.password="";

  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad LoginPage');
  }
login(){
let username=this.data.username;
let password=this.data.password;
let data =JSON.stringify({username,password});
let link="https://stationpfe.000webhostapp.com/login.php";
this.http.post(link,data)
.subscribe(data=>{
let loader=this.loading.create({
 content:"cheking! please wait...",
    duration:1000
  });
  loader.present();
  this.navCtrl.setRoot(HomePage);
  //

},error=>{
let alert =this.alert.create({
title:'warning',
subTitle:'wrong username or password !please try agin !',
buttons:['Ok']
  });
  alert.present();
});

}

close() {
    this.viewCtrl.dismiss(); // This works fine
  }
  showPopup(){
console.log("action sur label ");
  }
}

<ion-menu [content]="content" >
  <ion-header>

    <ion-toolbar color="danger"  >
      <ion-title > MyApp </ion-title>
    </ion-toolbar>
  </ion-header>

  <ion-content  class="custom">
    <ion-list >
       <ion-list-header>
          Navigate
        </ion-list-header>
      <button menuClose ion-item *ngFor="let p of pages" (click)="openPage(p)" >
       <ion-icon  name="alarm"  item-left> </ion-icon>

        {{p.title}}
      </button>
    </ion-list>

    <ion-list hidden  #menu2 >
      <ion-list-header>
          Account
        </ion-list-header>
      <button menuClose ion-item *ngFor="let p of pages1" (click)="openPage(p)" >

        {{p.title}}
      </button>
    </ion-list>

  </ion-content>

</ion-menu>

<ion-nav [root]="rootPage" #content ></ion-nav>

import { Component, ViewChild } from '@angular/core';
import { Nav, Platform } from 'ionic-angular';
import { StatusBar, Splashscreen } from 'ionic-native';

import { TabsPage } from '../pages/tabs/tabs';

import { SettingsPage } from '../pages/settings/settings';
import { AccountPage } from '../pages/account/account';
import { VoiturePage } from '../pages/voiture/voiture';
 import { LoginPage } from '../pages/login/login';
 import { TarifPage } from '../pages/tarif/tarif';
  import { HomePage } from '../pages/home/home';
  import { ModalPagePage } from '../pages/modal-page/modal-page';
  import { ListevoiturePage } from '../pages/listevoiture/listevoiture';

  import { InsertvoiturePage } from '../pages/insertvoiture/insertvoiture';

@Component({
  templateUrl: 'app.html',
 providers: [ModalPagePage]
})
export class MyApp {
  @ViewChild(Nav) nav: Nav;

  rootPage = HomePage;

  pages: Array<{title: string, component: any}>;
 pages1: Array<{title: string, component: any}>;
  constructor(public platform: Platform) {
    this.initializeApp();

this.pages = [
      { title: ' Home', component: TabsPage },
      { title: 'tickets' , component: TarifPage },
      { title: 'login', component: LoginPage },

    ];
    this.pages1 = [
      { title: 'liste Voiture', component: InsertvoiturePage},

    ];

  }
  openPage(page) {

    this.nav.setRoot(page.component);

  }

  initializeApp() {
    this.platform.ready().then(() => {
      // Okay, so the platform is ready and our plugins are available.
      // Here you can do any higher level native things you might need.
      StatusBar.styleDefault();
      Splashscreen.hide();

    });
  }
}

Body:
loginPage.ts

import { Component } from '@angular/core';
import { NavController, ModalController } from 'ionic-angular';
import { Storage } from '@ionic/storage';
import { ModalPagePage } from '../modal-page/modal-page';
import {HomePage} from '../home/home';

@Component({
  selector: 'page-login',
  templateUrl: 'login.html'
})
export class LoginPage {

  data: any;
  public getsession: any;
  x: any;

  public local: Storage;
  constructor(public navCtrl: NavController,public modalCtrl:ModalController) {
    this.data = {};
    this.data.title = "";
    this.data.desc = "";
    this.local = new Storage;
    this.local.set('session', 'true');

  }

      ionViewWillEnter() {
     this.getsession = this.local.get('session');
      this.getsession.then((value)=>{
       this.x = value;
      if( this.x !== ""){
         let modal = this.modalCtrl.create(ModalPagePage);
         modal.present();
        //this.navCtrl.setRoot(ModalPagePage);

    }
    });
  }

}

homePage.ts

import { Component } from '@angular/core';

import { NavController, AlertController } from 'ionic-angular';
import {ContactPage} from '../../pages/contact/contact';
import {AccountPage} from '../../pages/account/account';
import {ListevoiturePage} from '../../pages/listevoiture/listevoiture';
import {VoitureService} from '../../providers/voitureservice';
@Component({
  selector: 'page-home',
  templateUrl: 'home.html',
  providers:[VoitureService],

  styles: [`
    @media (max-width: 600px) {
      .hide-xs {
        display: none;
      }
    }
  `],
})
export class HomePage {
showbutton:boolean = false;
 nbr:any;
  constructor(public navCtrl: NavController,public alertCtrl: AlertController,public voitureservice:VoitureService) {
  this.getNombreVoiture();

  }
   getNombreVoiture(){
    this.voitureservice.nombrevoiture().subscribe(response=>
{
  this.nbr=response.Nombre;

});
  }
openContact() {
        this.navCtrl.push(ContactPage);
    }

goToPage1() {
   this.navCtrl.push(AccountPage);
 }

  goListeVoiture(){
  this.navCtrl.push(ListevoiturePage);
  }
}


问:
jQuery clicking click event not working on Datatables
Hey all I have a unique issue that I can not seem to find a way to fixing.

This is what my data table looks like:

I've added the red trashcan that you currently see in the image above in order for the user to delete that row. I add this trashcan by injecting it within the datatables createdRow:

```<code>fnRowCallback: function (nRow, aData, iDisplayIndex) {
   $(nRow).find('#trashIcon').attr({ 'data-indexer': (iDisplayIndex + 1) });
   $(nRow).find('#trashIcon').attr({ 'data-table': 1 });
},
createdRow: function (row, data, dataIndex) {
   $(row).prepend('<i id="trashIcon" ' +
           'data-eventid="' + data.RequestID + '" ' +
                  'class="fa fa-trash-o fa-lg grow-1" ' +
            'aria-hidden="true" ' +
                  'style="color: rgba(169, 68, 66, 1); ' +
                         'left: 3px; top: 10px; ' +
                         'position: relative; ' +
                         'z-index: 500; ' +
                         'box-shadow: 0px 2px 2px rgba(150,150,150,0.3);">' +
                  '</i>');
},
</code>```

And after all that's said and done with the injections the HTML code looks like:

```<code><table width="100%"
       class="display cell-border dataTable no-footer"
       id="theDT2"
       role="grid"
       aria-describedby="theDT2_info"
       style="width: 100%;"
       cellspacing="0">
<thead>
    [HEADER CODE HERE...]
</thead>
<tbody>
    <tr class="odd" role="row">
        <i class="fa fa-trash-o fa-lg grow-1"
           id="trashIcon"
           aria-hidden="true"
           style="left: 3px;
                               top: 10px;
                             color: rgba(169, 68, 66, 1);
                          position: relative;
                        box-shadow: 0px 2px 2px rgba(150,150,150,0.3);"
           data-eventid="976"
           data-indexer="1"
           data-table="2">
        </i>
        <td class="sorting_1">976</td>
        [TABLE CODE HERE]
    </tr>
</table>
</code>```

id="trashIcon" is the trashcan image you see in the rows. As you see I am setting trashcanHover to true on the trashcan click event but that doesn't seem to pass fast enough to the datatables click even when I console.log that out - it always says false.

The jQuery code I have for clicking on the trashcan is this:

```<code>$(document).on('click', '#trashIcon', function (e) {
    e.preventDefault();
    trashcanHover = true;
});
</code>```

And this is the jQuery code for the clicking of any part of the datatables row:

```<code>$(document.body).on('click', 'tr', function (e) {
    //Listens for the user to click on a data row in the table
    if (typeof $(this).attr('class') != 'undefined') {
        var tblName = $(this).closest('table').attr("ID");
        var headerClick = $(this).attr("aria-controls");

        console.log(trashcanHover);

        if (typeof $(this).attr('class') != 'undefined') {
            if (tblName == "theDT") {
                edit_person(theTable.row(this).data().RequestID);
            } else {
                edit_event(theTable2.row(this).data().EventID);
            }
        } else {
            if ($(this).data('table') == 1) {
                $('#theDT').dataTable().fnDeleteRow($(this).closest('tr')[0]);
            } else {
                $('#theDT2').dataTable().fnDeleteRow($(this).closest('tr')[0]);
            }
        }
    }
});
</code>```

Now if I comment out either one of those click functions then it does what it should do (either open data to edit or delete that row). What I am having issues with is that it never fully sees the trashcan click (even though I click on it with the mouse). It just fires off the datatables click row function and I can not find a way to distinguish between the two of them in order to do an IF THAN.

The code above does work with checking if just the headers were clicked on and if so, don't edit that row's data.

Currently though when I click on the trashcan it does delete that row but also opens the edit for that row that just got deleted.

for Louys Patrice Bessette

Seems to always goto the datatable's click event first...

答:
Use a class to target elements that are created via a loop.

Because an id must be unique.

I assume this is an immediate delete row function...

So this should work:

```<code>$(document).on('click', '.fa-trash-o', function (e) {
    // To stop the click propagation up to the `tr` handler
    e.stopPropagation();

    // Delete the row.
    $('#theDT2').dataTable().fnDeleteRow($(this).closest('tr')[0]);
});
</code>```

EDIT

okay... Let's try something else then.

In the tr handler, add:

```<code>$(document.body).on('click', 'tr', function (e) {
    if(e.target.className.split(" ")[1]=="fa-trash-o"){
        return;
    }
    // rest of your code...
</code>```

Body:
Hey all I have a unique issue that I can not seem to find a way to fixing.

This is what my data table looks like:

I've added the red trashcan that you currently see in the image above in order for the user to delete that row. I add this trashcan by injecting it within the datatables createdRow:

fnRowCallback: function (nRow, aData, iDisplayIndex) {
   $(nRow).find('#trashIcon').attr({ 'data-indexer': (iDisplayIndex + 1) });
   $(nRow).find('#trashIcon').attr({ 'data-table': 1 });
},
createdRow: function (row, data, dataIndex) {
   $(row).prepend('' +
                  '');
},

And after all that's said and done with the injections the HTML code looks like:

    [HEADER CODE HERE...]

        976
        [TABLE CODE HERE]

id="trashIcon" is the trashcan image you see in the rows. As you see I am setting trashcanHover to true on the trashcan click event but that doesn't seem to pass fast enough to the datatables click even when I console.log that out - it always says false.

The jQuery code I have for clicking on the trashcan is this:

$(document).on('click', '#trashIcon', function (e) {
    e.preventDefault();
    trashcanHover = true;
});

And this is the jQuery code for the clicking of any part of the datatables row:

$(document.body).on('click', 'tr', function (e) {
    //Listens for the user to click on a data row in the table
    if (typeof $(this).attr('class') != 'undefined') {
        var tblName = $(this).closest('table').attr("ID");
        var headerClick = $(this).attr("aria-controls");

        console.log(trashcanHover);

        if (typeof $(this).attr('class') != 'undefined') {
            if (tblName == "theDT") {
                edit_person(theTable.row(this).data().RequestID);
            } else {
                edit_event(theTable2.row(this).data().EventID);
            }
        } else {
            if ($(this).data('table') == 1) {
                $('#theDT').dataTable().fnDeleteRow($(this).closest('tr')[0]);
            } else {
                $('#theDT2').dataTable().fnDeleteRow($(this).closest('tr')[0]);
            }
        }
    }
});

Now if I comment out either one of those click functions then it does what it should do (either open data to edit or delete that row). What I am having issues with is that it never fully sees the trashcan click (even though I click on it with the mouse). It just fires off the datatables click row function and I can not find a way to distinguish between the two of them in order to do an IF THAN.

The code above does work with checking if just the headers were clicked on and if so, don't edit that row's data.

Currently though when I click on the trashcan it does delete that row but also opens the edit for that row that just got deleted.

for Louys Patrice Bessette

Seems to always goto the datatable's click event first...

Body:
Use a class to target elements that are created via a loop.

Because an id must be unique.

I assume this is an immediate delete row function...

So this should work:

$(document).on('click', '.fa-trash-o', function (e) {
    // To stop the click propagation up to the `tr` handler
    e.stopPropagation();

    // Delete the row.
    $('#theDT2').dataTable().fnDeleteRow($(this).closest('tr')[0]);
});

EDIT

okay... Let's try something else then.

In the tr handler, add:

$(document.body).on('click', 'tr', function (e) {
    if(e.target.className.split(" ")[1]=="fa-trash-o"){
        return;
    }
    // rest of your code...


问:
iOS perform action after period of inactivity (no user interaction)
How can I add a timer to my iOS app that is based on user interaction (or lack thereof)? In other words, if there is no user interaction for 2 minutes, I want to have the app do something, in this case navigate to the initial view controller. If at 1:55 someone touches the screen, the timer resets. I would think this would need to be a global timer so no matter which view you are on, the lack of interaction starts the timer. Although, I could create a unique timer on each view. Does anyone have any suggestions, links or sample code where this has been done before?</p>

答:
Swift 3.0 Conversion of the subclassed UIApplication in Vanessa's Answer

```<code>class TimerUIApplication: UIApplication {
static let ApplicationDidTimoutNotification = "AppTimout"

    // The timeout in seconds for when to fire the idle timer.
    let timeoutInSeconds: TimeInterval = 5 * 60

    var idleTimer: Timer?

    // Resent the timer because there was user interaction.
    func resetIdleTimer() {
        if let idleTimer = idleTimer {
            idleTimer.invalidate()
        }

        idleTimer = Timer.scheduledTimer(timeInterval: timeoutInSeconds, target: self, selector: #selector(TimerUIApplication.idleTimerExceeded), userInfo: nil, repeats: false)
    }

    // If the timer reaches the limit as defined in timeoutInSeconds, post this notification.
    func idleTimerExceeded() {
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: TimerUIApplication.ApplicationDidTimoutNotification), object: nil)
    }

    override func sendEvent(_ event: UIEvent) {

        super.sendEvent(event)

        if idleTimer != nil {
            self.resetIdleTimer()
        }

        if let touches = event.allTouches {
            for touch in touches {
                if touch.phase == UITouchPhase.began {
                    self.resetIdleTimer()
                }
            }
        }

    }
}
</code>```

Body:
Swift 3.0 Conversion of the subclassed UIApplication in Vanessa's Answer

class TimerUIApplication: UIApplication {
static let ApplicationDidTimoutNotification = "AppTimout"

    // The timeout in seconds for when to fire the idle timer.
    let timeoutInSeconds: TimeInterval = 5 * 60

    var idleTimer: Timer?

    // Resent the timer because there was user interaction.
    func resetIdleTimer() {
        if let idleTimer = idleTimer {
            idleTimer.invalidate()
        }

        idleTimer = Timer.scheduledTimer(timeInterval: timeoutInSeconds, target: self, selector: #selector(TimerUIApplication.idleTimerExceeded), userInfo: nil, repeats: false)
    }

    // If the timer reaches the limit as defined in timeoutInSeconds, post this notification.
    func idleTimerExceeded() {
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: TimerUIApplication.ApplicationDidTimoutNotification), object: nil)
    }

    override func sendEvent(_ event: UIEvent) {

        super.sendEvent(event)

        if idleTimer != nil {
            self.resetIdleTimer()
        }

        if let touches = event.allTouches {
            for touch in touches {
                if touch.phase == UITouchPhase.began {
                    self.resetIdleTimer()
                }
            }
        }

    }
}


问:
Updating a class after changing its Interface
Say I add a function to an outstanding Interface.
In Visual Studio, within a class which implements it I can right click the Interface declaration and re-implement it. This will update the code to reflect the changes made. Is there anyway to do the same thing in eclipse?
It'd be nice if there was.
I've searched the net, alas no joy.</p>

答:
Put the cursor on the name of the class and press CTRL+1 to activate the quick-fix. That should offer the option of adding the new method.

UPDATE: BTW, here's a really handy list of Eclipse keyboard shortcuts. If you're on Mac, you can usually substitute ⌘ for CTRL.

OwnerDisplayName: Hank Gay

LastEditorDisplayName: Hank Gay


问:
Automatic formula calculation in excel
I have a small query regarding automatic formula value calculation in excel.
In my project I will be having 200 questions and corresponding 200 answers( numerical values of 10,20 and 30). Those questions and answers are obtained from webpages and all the questions and answers are stored in my sql database. I will collect the answers that are posted in mysql database to excel with the help of mysql add-in.

 My question is I have some formulas
given in my excel sheet ex:mean(C204), STDEV(C205), final risk( my own formula F209)

I want the formulas to automatically calculate the formula values whenever I import the
data from mysql. Is it possible in excel if not is there any alternative? Please help!

答:
This is kind of a stab in the dark since I'm not at all familiar with the add in or how it operates. It seems odd that it would import data and not allow a application.calculate event to take place after import.

Perhaps... you can run the application.calculate method on worksheet change. In your VBE, double click the worksheet upon which the mysql data is dropped. Then add this code to that worksheet:

```<code>Private Sub Worksheet_Change(ByVal Target As Range)
    Application.Calculate
End Sub
</code>```

There's fairly good chance that the add in also snuffs events by setting application.enableEvents = false which means this won't work, but... it's worth a shot.

Title: Automatic formula calculation in excel

Body:
This is kind of a stab in the dark since I'm not at all familiar with the add in or how it operates. It seems odd that it would import data and not allow a application.calculate event to take place after import.

Perhaps... you can run the application.calculate method on worksheet change. In your VBE, double click the worksheet upon which the mysql data is dropped. Then add this code to that worksheet:

Private Sub Worksheet_Change(ByVal Target As Range)
    Application.Calculate
End Sub

There's fairly good chance that the add in also snuffs events by setting application.enableEvents = false which means this won't work, but... it's worth a shot.


问:
Button's Text Cycle Through String-Array
I have a button that when clicked, the text inside changes. I'm trying to accomplish this with an array in my strings.xml, thinking that the onClick will do a for loop through the string-array

```<code><string-array name="RG_answers">
     <item>text 1</item><!--Of course this is example text-->
     <item>text 2</item>
     <item>text 3</item>
</string-array>
</code>```

I don't know if I'm just not Googling correctly, or what. Inside my onCreate() my button is basic

```<code> mTrueButton = (Button) findViewById(R.id.true_button);
        mTrueButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
</code>```

So basic that it's only helpful (if that) by providing the names I called it. Is it possible/feasible? From what I've found I haven't seen anyone ask a question like this.

答:
Is it possible to loop through the string-array?

Yes, change the button text using button.setText(text); Keep a counter as global variable so that you can cycle through the list of 'button text' you have mentioned.

eg: button.setText(array[index]);

Body:
I have a button that when clicked, the text inside changes. I'm trying to accomplish this with an array in my strings.xml, thinking that the onClick will do a for loop through the string-array

<string-array name="RG_answers">
     <item>text 1</item>
     <item>text 2</item>
     <item>text 3</item>
</string-array>

I don't know if I'm just not Googling correctly, or what. Inside my onCreate() my button is basic

 mTrueButton = (Button) findViewById(R.id.true_button);
        mTrueButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });

So basic that it's only helpful (if that) by providing the names I called it. Is it possible/feasible? From what I've found I haven't seen anyone ask a question like this.


问:
ViewChildren not finding Dynamic Components
A parent component that contains a @ViewChildren is not returning results for components that are created dynamically.

The container component contains a highlight directive, and the dynamically generated component contains a highlight directive within it's template.  When queried with @ViewChildren the query length returns 1.  The expected result is 2.

As you can see from the HTML there are definitely two highlight directives on the DOM.

```<code><container-component>
    <div></div>
     <dynamic-component ng-version="4.0.0">
        <div highlight="" style="background-color: yellow;">Dynamic!</div>
     </dynamic-component>
     <div highlight="" style="background-color: yellow;">Number of Highlights
        <div></div>
     </div>
</container-component>
</code>```

Am I missing something?

https://plnkr.co/edit/LilvHJgFjPHnPuaNIKir?p=preview

Container Component

```<code>@Component({
  selector: 'container-component',
  template: `
    <div #contentProjection></div>
    <div highlight>Number of Highlights {{highlightCount}}<div>
  `,
})
export class ContainerComponent implements OnInit, AfterViewInit {
  @ViewChildren(HighlightDirective) private highlights: QueryList<HighlightDirective>;
  @ViewChild('contentProjection', { read: ViewContainerRef }) private contentProjection: ViewContainerRef;

  constructor(
    private resolver: ComponentFactoryResolver
    ) {
  }

  ngOnInit() {
    this.createDynamicComponent();
  }

  ngAfterViewInit() {
    console.log(this.highlights.length);

    // Should update with any DOM changes
    this.highlights.changes.subscribe(x => {
      console.log(this.highlights.length);
    });
  }

  private createDynamicComponent(){
    const componentFactory = this.resolver.resolveComponentFactory(DynamicComponent);
    this.contentProjection.createComponent(componentFactory);

  }
}
</code>```

Dynamic Component

```<code> @Component({
      selector: 'dynamic-component',
      template: `
        <div highlight>Dynamic!</div>
      `,
    })
    export class DynamicComponent {
    }
</code>```

Highlight Directive

```<code> @Directive({
      selector: '[highlight]'
    })
    export class HighlightDirective {
      constructor(private elementRef: ElementRef) {
         elementRef.nativeElement.style.backgroundColor = 'yellow';
      }
    }
</code>```

答:
That doesn't work because @ViewChildren only queries its own view, not the view contained within child components. Your dynamic component is a child component that has its own view.

To get around this you could add a @ViewChildren query in the dynamic component that has an output event to let anyone who cares (your parent component) know that a new instance exists.

Body:
A parent component that contains a @ViewChildren is not returning results for components that are created dynamically.

The container component contains a highlight directive, and the dynamically generated component contains a highlight directive within it's template.  When queried with @ViewChildren the query length returns 1.  The expected result is 2.

As you can see from the HTML there are definitely two highlight directives on the DOM.

<container-component>

     <dynamic-component ng-version="4.0.0">

Dynamic!

     </dynamic-component>

Number of Highlights

</container-component>

Am I missing something?

https://plnkr.co/edit/LilvHJgFjPHnPuaNIKir?p=preview

Container Component

@Component({
  selector: 'container-component',
  template: `

Number of Highlights {{highlightCount}}

  `,
})
export class ContainerComponent implements OnInit, AfterViewInit {
  @ViewChildren(HighlightDirective) private highlights: QueryList<HighlightDirective>;
  @ViewChild('contentProjection', { read: ViewContainerRef }) private contentProjection: ViewContainerRef;

  constructor(
    private resolver: ComponentFactoryResolver
    ) {
  }

  ngOnInit() {
    this.createDynamicComponent();
  }

  ngAfterViewInit() {
    console.log(this.highlights.length);

    // Should update with any DOM changes
    this.highlights.changes.subscribe(x => {
      console.log(this.highlights.length);
    });
  }

  private createDynamicComponent(){
    const componentFactory = this.resolver.resolveComponentFactory(DynamicComponent);
    this.contentProjection.createComponent(componentFactory);

  }
}

Dynamic Component

 @Component({
      selector: 'dynamic-component',
      template: `

Dynamic!

      `,
    })
    export class DynamicComponent {
    }

Highlight Directive

 @Directive({
      selector: '[highlight]'
    })
    export class HighlightDirective {
      constructor(private elementRef: ElementRef) {
         elementRef.nativeElement.style.backgroundColor = 'yellow';
      }
    }


问:
How can I play sound system with text?
Do we have any ways to get sound from text?

For example, we have:

```<code>let str = "Hello English" .
</code>```

I want to get sound system from that text.

答:
As Ravy Chheng answered, this uses the built-in AVFoundation library to initialize basic text-to speak function. For more information, check out the documentation by Apple: https://developer.apple.com/reference/avfoundation/avspeechsynthesizer</p>

```<code>import AVFoundation

func playSound(str: String) {
    let speechSynthesizer = AVSpeechSynthesizer()
    let speechUtterance = AVSpeechUtterance(string: str)
    speechSynthesizer.speak(speechUtterance)
}
</code>```

Title: How can I play sound system with text?

Body:
Do we have any ways to get sound from text?

For example, we have:

let str = "Hello English" .

I want to get sound system from that text.

Body:
As Ravy Chheng answered, this uses the built-in AVFoundation library to initialize basic text-to speak function. For more information, check out the documentation by Apple: https://developer.apple.com/reference/avfoundation/avspeechsynthesizer

import AVFoundation

func playSound(str: String) {
    let speechSynthesizer = AVSpeechSynthesizer()
    let speechUtterance = AVSpeechUtterance(string: str)
    speechSynthesizer.speak(speechUtterance)
}


问:
Does red hat hackers exist?
Hello i am searching info about hacking and i found a category that called red hat hackers.

I searching for a couple of hours but i cant find any valiant info...

I have found articles about hackers (white,black,grey,green) but almost none about red hat's .

I also found this
"A Red Hat hacker is employed by one government to hack and bring down websites and online services of another country."
But i am not sure if this is the red hat or spy hacker....
Also some claim that this category dosnt exist.

Any help?
thanks :)

答:
There is no such thing as a Red Hat Hacker.

There are following categories of Hackers:

White hat hacker

Black hat hacker

Grey hat hacker

Script kiddie

Suicide hacker

Hacktivist

There may be some other categories but the main ones are listed above.

I think you are confused in RedHat Linux and other categories of Hackers.

RedHat is an organization which has created a Linux OS, known as RedHat.

Title: Does red hat hackers exist?


问:
Groupby and where clause in Linq
I am a newbie to Linq. I am trying to write a linq query to get a min value from a set of records. I need to use groupby, where , select and min function in the same query but i am having issues when using group by clause. here is the query I wrote

```<code>var data =newTrips.groupby (x => x.TripPath.TripPathLink.Link.Road.Name)
                  .Where(x => x.TripPath.PathNumber == pathnum)
                  .Select(x => x.TripPath.TripPathLink.Link.Speed).Min();
</code>```

I am not able to use group by and where together it keeps giving error .

My query should

Select all the values.

filter it through the where clause (pathnum).

Groupby the road Name

finally get the min value.

can some one tell me what i am doing wrong and how to achieve the desired result.

Thanks,
Pawan

答:
Since I think you want the Trip which has the minimum speed, rather than the speed, and I'm assuming a different data structure, I'll add to tvanfosson's answer:</p>

```<code>var pathnum = 1;
var trips = from trip in newTrips
            where trip.TripPath.PathNumber == pathnum
            group trip by trip.TripPath.TripPathLink.Link.Road.Name into g
            let minSpeed = g.Min(t => t.TripPath.TripPathLink.Link.Speed)
            select new {
                Name = g.Key,
                Trip = g.Single(t => t.TripPath.TripPathLink.Link.Speed == minSpeed) };

foreach (var t in trips)
{
    Console.WriteLine("Name = {0}, TripId = {1}", t.Name, t.Trip.TripId);
}
</code>```

Title: Groupby and where clause in Linq

Body:
I am a newbie to Linq. I am trying to write a linq query to get a min value from a set of records. I need to use groupby, where , select and min function in the same query but i am having issues when using group by clause. here is the query I wrote

var data =newTrips.groupby (x => x.TripPath.TripPathLink.Link.Road.Name)
                  .Where(x => x.TripPath.PathNumber == pathnum)
                  .Select(x => x.TripPath.TripPathLink.Link.Speed).Min();

I am not able to use group by and where together it keeps giving error .

My query should

Select all the values.

filter it through the where clause (pathnum).

Groupby the road Name

finally get the min value.

can some one tell me what i am doing wrong and how to achieve the desired result.

Thanks,
Pawan

Body:
Since I think you want the Trip which has the minimum speed, rather than the speed, and I'm assuming a different data structure, I'll add to tvanfosson's answer:

var pathnum = 1;
var trips = from trip in newTrips
            where trip.TripPath.PathNumber == pathnum
            group trip by trip.TripPath.TripPathLink.Link.Road.Name into g
            let minSpeed = g.Min(t => t.TripPath.TripPathLink.Link.Speed)
            select new {
                Name = g.Key,
                Trip = g.Single(t => t.TripPath.TripPathLink.Link.Speed == minSpeed) };

foreach (var t in trips)
{
    Console.WriteLine("Name = {0}, TripId = {1}", t.Name, t.Trip.TripId);
}


问:
"The project file was unloaded" when moving VS2010 project to another server
I have moved a Visual Studio 2010 project to another server by copying and pasting the folder contents into another folder on a different server.

My understand was that VS2010 handled this well; when I have done this locally it has never been an issue.

Now I get an error like this:

When I right click and "Reload project", the list of files briefly appears before disappearing again, giving the original error.

Am I doing something wrong?

答:
Found this answer and it worked for me.

Note:Sometimes, the path in File path property is grayed out and you are unable to get to the Browse button. In this case try deleting .suo files. Don’t worry, these files gets recreated when you rebuild the solution / project.

http://www.howtosolutions.net/2013/02/solving-project-file-error-could-not-find-part-of-the-path-with-visual-studio/