问:
@Embedded object not instantiated automatically if it has no basic datatype fields
Fundamental question: Why aren't @Embedded objects always instantiated?

The interesting observation is that Ebean does not instantiate @Embedded objects if those do not contain basic datatypes (int, boolean...) or weren't touched before. Example:

```<code>@Entity
public class Embedder {
    // getNotAutoInstantiated() will return null if this field was not touched before
    @Embedded
    private NotAutoInstantiated notAutoInstantiated = new NotAutoInstantiated();
    // getAutoInstantiated() will always return an instance!
    @Embedded
    private AutoInstantiated autoInstantiated = new AutoInstantiated();
}

@Embeddable
public class AutoInstantiated {
    // theKey is why this embedded object is always instantiated
    private int theKey;
    private String field1;
}

@Embeddable
public class NotAutoInstantiated {
    private String field2;
}
</code>```

答:
I just hit the same issue with Hibernate.
The original question, about the "why" is answered.

But to talk about a solution, I just use a @PostLoad method, so within class Embedder something like:

```<code>@PostLoad
private void initData() {
  if(notAutoInstantiated == null) {
    notAutoInstantiated = new NotAutoInstantiated();
  }
}
</code>```

Update:

Warning! The upper code is working, but does have an unexpected side effect! As soon as you load your object with null pointer from the database, it is marked as dirty, because of this post load code!
In my case, this side effects leads to an SQL update command from a thread, which should only load the data and hours of searching this bug!

Body:
Fundamental question: Why aren't @Embedded objects always instantiated?

The interesting observation is that Ebean does not instantiate @Embedded objects if those do not contain basic datatypes (int, boolean...) or weren't touched before. Example:

@Entity
public class Embedder {
    // getNotAutoInstantiated() will return null if this field was not touched before
    @Embedded
    private NotAutoInstantiated notAutoInstantiated = new NotAutoInstantiated();
    // getAutoInstantiated() will always return an instance!
    @Embedded
    private AutoInstantiated autoInstantiated = new AutoInstantiated();
}

@Embeddable
public class AutoInstantiated {
    // theKey is why this embedded object is always instantiated
    private int theKey;
    private String field1;
}

@Embeddable
public class NotAutoInstantiated {
    private String field2;
}

Body:
I just hit the same issue with Hibernate.
The original question, about the "why" is answered.

But to talk about a solution, I just use a @PostLoad method, so within class Embedder something like:

@PostLoad
private void initData() {
  if(notAutoInstantiated == null) {
    notAutoInstantiated = new NotAutoInstantiated();
  }
}

Update:

Warning! The upper code is working, but does have an unexpected side effect! As soon as you load your object with null pointer from the database, it is marked as dirty, because of this post load code!
In my case, this side effects leads to an SQL update command from a thread, which should only load the data and hours of searching this bug!


来源: stackexchange

问:
Rest fb - authorization url to get page access token
I need to authenticate user's page from my Gui App. I didnt find any solution for me how to do it with java and restfb library. I am able to authenticate user from my Gui App, but i want to access user's page, not user's wall.

```<code>String domain = "http://seznam.cz/";
String appId = "1784741508503328";
String authUrl = "https://graph.facebook.com/oauth/authorize?type=user_agent&client_id="+appId+"&redirect_uri="+domain+"&scope=user_about_me,"
      + "user_actions.books,user_actions.fitness,user_actions.music,user_actions.news,user_actions.video,user_birthday,user_education_history,"
      + "user_events,user_photos,user_friends,user_games_activity,user_hometown,user_likes,user_location,user_photos,user_relationship_details,"
      + "user_relationships,user_religion_politics,user_status,user_tagged_places,user_videos,user_website,user_work_history,ads_management,ads_read,email,"
      + "manage_pages,publish_actions,read_insights,user_friends,read_page_mailboxes,rsvp_event";
</code>```

This code works only for user's wall/photos...etc But not for user's page. Could you please help me how to edit this url to get page access token? Thanks a lot.

Whole code:

```<code>public void getAccessToken(){
        String domain = "http://seznam.cz/";
        String appId = "1784741508503328";
        String authUrl = "https://graph.facebook.com/oauth/authorize?type=user_agent&client_id="+appId+"&redirect_uri="+domain+"&scope=user_about_me,"
             + "user_actions.books,user_actions.fitness,user_actions.music,user_actions.news,user_actions.video,user_birthday,user_education_history,"
             + "user_events,user_photos,user_friends,user_games_activity,user_hometown,user_likes,user_location,user_photos,user_relationship_details,"
             + "user_relationships,user_religion_politics,user_status,user_tagged_places,user_videos,user_website,user_work_history,ads_management,ads_read,email,"
             + "manage_pages,publish_actions,read_insights,user_friends,read_page_mailboxes,rsvp_event";
        System.setProperty("webdriver.chrome.driver", "chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.get(authUrl);
        while(true){
            if(!driver.getCurrentUrl().contains("facebook.com")){
                String url = driver.getCurrentUrl();
                accessToken = url.replaceAll(".*#access_token=(.+)&.*", "$1");
                PrintWriter p = null;
                try {p = new PrintWriter("users.txt");}
                catch (FileNotFoundException ex) {Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);}
                fbClient = new DefaultFacebookClient(accessToken);
                if(!accessToken.equals("null")){
                    p.println(extendToken().getAccessToken() + "," + extendToken().getExpires());
                }

                else{
                    p.print("");
                }
                driver.quit();
                p.close();
                return;
            }
        }
}
</code>```

答:
It was easy as:

```<code>Connection<Account> result2 = fbClient.fetchConnection("me/accounts",Account.class);
for(List<Account> page : result2){
      for(Account a : page){
            System.out.println(a.getAccessToken());
            System.out.println(a.getName());
      }
}
</code>```

This code will print out all the pages names and their access tokens. You can simply store them in String and later use them.

ContentLicense: CC BY-SA 3.0

Body:
I need to authenticate user's page from my Gui App. I didnt find any solution for me how to do it with java and restfb library. I am able to authenticate user from my Gui App, but i want to access user's page, not user's wall.

String domain = "http://seznam.cz/";
String appId = "1784741508503328";
String authUrl = "https://graph.facebook.com/oauth/authorize?type=user_agent&client_id="+appId+"&redirect_uri="+domain+"&scope=user_about_me,"
      + "user_actions.books,user_actions.fitness,user_actions.music,user_actions.news,user_actions.video,user_birthday,user_education_history,"
      + "user_events,user_photos,user_friends,user_games_activity,user_hometown,user_likes,user_location,user_photos,user_relationship_details,"
      + "user_relationships,user_religion_politics,user_status,user_tagged_places,user_videos,user_website,user_work_history,ads_management,ads_read,email,"
      + "manage_pages,publish_actions,read_insights,user_friends,read_page_mailboxes,rsvp_event";

This code works only for user's wall/photos...etc But not for user's page. Could you please help me how to edit this url to get page access token? Thanks a lot.

Whole code:

public void getAccessToken(){
        String domain = "http://seznam.cz/";
        String appId = "1784741508503328";
        String authUrl = "https://graph.facebook.com/oauth/authorize?type=user_agent&client_id="+appId+"&redirect_uri="+domain+"&scope=user_about_me,"
             + "user_actions.books,user_actions.fitness,user_actions.music,user_actions.news,user_actions.video,user_birthday,user_education_history,"
             + "user_events,user_photos,user_friends,user_games_activity,user_hometown,user_likes,user_location,user_photos,user_relationship_details,"
             + "user_relationships,user_religion_politics,user_status,user_tagged_places,user_videos,user_website,user_work_history,ads_management,ads_read,email,"
             + "manage_pages,publish_actions,read_insights,user_friends,read_page_mailboxes,rsvp_event";
        System.setProperty("webdriver.chrome.driver", "chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.get(authUrl);
        while(true){
            if(!driver.getCurrentUrl().contains("facebook.com")){
                String url = driver.getCurrentUrl();
                accessToken = url.replaceAll(".*#access_token=(.+)&.*", "$1");
                PrintWriter p = null;
                try {p = new PrintWriter("users.txt");}
                catch (FileNotFoundException ex) {Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);}
                fbClient = new DefaultFacebookClient(accessToken);
                if(!accessToken.equals("null")){
                    p.println(extendToken().getAccessToken() + "," + extendToken().getExpires());
                }

                else{
                    p.print("");
                }
                driver.quit();
                p.close();
                return;
            }
        }
}

Body:
It was easy as:

Connection<Account> result2 = fbClient.fetchConnection("me/accounts",Account.class);
for(List<Account> page : result2){
      for(Account a : page){
            System.out.println(a.getAccessToken());
            System.out.println(a.getName());
      }
}

This code will print out all the pages names and their access tokens. You can simply store them in String and later use them.


问:
"No backupset selected to be restored" SQL Server 2012
I have a SQL Server 2012 database with filestream enabled. However, when I backup it and try to restore it on another SQL Server 2012 instance (on another machine), I simply get this message that:

No backupset selected to be restored.

Not even a single line of more explanation. What's wrong here?

Every other database without filestream is OK and can be restored successfully. Is it something related to filestream? Should I install a hotfix or something like that.

答:
For me it's a user privilege issue.
I logged-in with sa user and its working fine.</p>


问:
Not able to check the condition on submit button swift
Short description :

I am getting one value called UserValue. This will come from one response.And i have one Confirm button press method. In that each time i need to check whether the user entered amount is greater then UserValue amount.

but some time the value will be UserValue  will be nill.That time it should not check whethere entered amount in text filed is greater than UserValue

Now here my code :

```<code> @IBAction func confirmButnClicked(_ sender: Any) {
 print(UserValue)
 let Mvalue = Double((UserValue.formattedAmount()))
                    let stringValue = Int(Mvalue!)

 if doubleValue < stringValue {
      DialogUtils.showMessageWithOk(controller: self, message:  "Maximum Value is : \(UserValue)")

  }
}
</code>```

Its working fine when i got some value in UserValue but when i get nill value here its crashing...How can i handle this:

```<code>let stringValue = Int(Mvalue!)   // crash here
</code>```

Thanks in advance !!

答:
You are forcefully unwrapping the nil, Due to that its crashing.

Check the UserValue is nil or not. If not nil then do the comparison

```<code> @IBAction func confirmButnClicked(_ sender: Any) {
     print(UserValue)

     if let UserValue = UserValue {
       if let Mvalue = Double((UserValue.formattedAmount())) {
          if let stringValue = Int(Mvalue) {
           if doubleValue < stringValue {
               DialogUtils.showMessageWithOk(controller: self, message:  "Maximum Value is : \(UserValue)")
            }
          }
        }
     }
}
</code>```

Body:
Short description :

I am getting one value called UserValue. This will come from one response.And i have one Confirm button press method. In that each time i need to check whether the user entered amount is greater then UserValue amount.

but some time the value will be UserValue  will be nill.That time it should not check whethere entered amount in text filed is greater than UserValue

Now here my code :

 @IBAction func confirmButnClicked(_ sender: Any) {
 print(UserValue)
 let Mvalue = Double((UserValue.formattedAmount()))
                    let stringValue = Int(Mvalue!)

 if doubleValue < stringValue {
      DialogUtils.showMessageWithOk(controller: self, message:  "Maximum Value is : \(UserValue)")

  }
}

Its working fine when i got some value in UserValue but when i get nill value here its crashing...How can i handle this:

let stringValue = Int(Mvalue!)   // crash here

Thanks in advance !!

Body:
You are forcefully unwrapping the nil, Due to that its crashing.

Check the UserValue is nil or not. If not nil then do the comparison

 @IBAction func confirmButnClicked(_ sender: Any) {
     print(UserValue)

     if let UserValue = UserValue {
       if let Mvalue = Double((UserValue.formattedAmount())) {
          if let stringValue = Int(Mvalue) {
           if doubleValue < stringValue {
               DialogUtils.showMessageWithOk(controller: self, message:  "Maximum Value is : \(UserValue)")
            }
          }
        }
     }
}


问:
Proper ultimate way to migrate JMS event listening to Spring Integration with Spring Boot
I got a JmsConfig configuration class that handles JMS events from a topic in the following way:

It defines a @Bean ConnectionFactory, containing an ActiveMQ implementation

It defines a @Bean JmsListenerContainerFactory instantiating a DefaultJmsListenerContainerFactory and passing it through Boot's DefaultJmsListenerContainerFactoryConfigurer

It defines a @Bean MessageConverter containing a MappingJackson2MessageConverter and setting a custom ObjectMapper

I use @JmsListener annotation pointing to myfactory on a method of my service. This is the only use I have for the topic, subscription alone.

Now I want to move to Spring Integration. After reading a lot, and provided I don't need a bidirectional use (discarding Gateways) neither a polling mechanism (discarding @InboundChannelAdapter), I am going for a message-driven-channel-adapter, in traditional XML configuration wording. I found that Java idiom should be accomplished by means of the new Spring Integration DSL library, and thus, I look for the proper snippet.

It seems JmsMessageDrivenChannelAdapter is the proper equivalent, and I found a way:

IntegrationFlows.from(Jms.messageDriverChannelAdapter(...))

But the problem is that this only accepts the ActiveMQ ConnectionFactory or an AbstractMessageListenerContainer, but no my boot pre-configured JmsListenerContainerFactory !

How should this be implemented in an ultimate way?

答:
There is even a better approach. I am surprised Gary did not comment it.
There's an out-of-the-box builder called Jms.container(...).

```<code>@Bean
public IntegrationFlow jmsMyServiceMsgInboundFlow(ConnectionFactory connectionFactory, MessageConverter jmsMessageConverter, MyService myService, JmsProperties jmsProperties, @Value("${mycompany.jms.destination.my-topic}") String topicDestination){

      JmsProperties.Listener jmsInProps = jmsProperties.getListener();

      return IntegrationFlows.from(
                                Jms.messageDrivenChannelAdapter(  Jms.container(connectionFactory, topicDestination)
                                                                     .pubSubDomain(false)
                                                                     .sessionAcknowledgeMode(jmsInProps .getAcknowledgeMode().getMode())
                                                                     .maxMessagesPerTask(1)
                                                                     .errorHandler(e -> e.printStackTrace())
                                                                     .cacheLevel(0)
                                                                     .concurrency(jmsInProps.formatConcurrency())
                                                                     .taskExecutor(Executors.newCachedThreadPool())
                                                                     .get()))
                                   )
                                   .extractPayload(true)
                                   .jmsMessageConverter(jmsMessageConverter)
                                   .destination(topicDestination)
                                   .autoStartup(true)
                                    //.errorChannel("NOPE")
                             )
                             .log(LoggingHandler.Level.DEBUG)
                             .log()
                             .handle(myService, "myMethod", e -> e.async(true).advice(retryAdvice()))
                             .get();
</code>```

Body:
There is even a better approach. I am surprised Gary did not comment it.
There's an out-of-the-box builder called Jms.container(...).

@Bean
public IntegrationFlow jmsMyServiceMsgInboundFlow(ConnectionFactory connectionFactory, MessageConverter jmsMessageConverter, MyService myService, JmsProperties jmsProperties, @Value("${mycompany.jms.destination.my-topic}") String topicDestination){

      JmsProperties.Listener jmsInProps = jmsProperties.getListener();

      return IntegrationFlows.from(
                                Jms.messageDrivenChannelAdapter(  Jms.container(connectionFactory, topicDestination)
                                                                     .pubSubDomain(false)
                                                                     .sessionAcknowledgeMode(jmsInProps .getAcknowledgeMode().getMode())
                                                                     .maxMessagesPerTask(1)
                                                                     .errorHandler(e -> e.printStackTrace())
                                                                     .cacheLevel(0)
                                                                     .concurrency(jmsInProps.formatConcurrency())
                                                                     .taskExecutor(Executors.newCachedThreadPool())
                                                                     .get()))
                                   )
                                   .extractPayload(true)
                                   .jmsMessageConverter(jmsMessageConverter)
                                   .destination(topicDestination)
                                   .autoStartup(true)
                                    //.errorChannel("NOPE")
                             )
                             .log(LoggingHandler.Level.DEBUG)
                             .log()
                             .handle(myService, "myMethod", e -> e.async(true).advice(retryAdvice()))
                             .get();


问:
Docker: Docker-compose ruby + postgres - PG::ConnectionBadcould not connect to server
I created Dockerfile to ruby from official docker-compose website. I used docker compose to integrate this with Postgres. When docker-compose up, then PostgreSQL starts but I cannot connect to this. The main problem is in ruby database config because I can't change to listen to another host and set the default user. I don't know how to connect these two containers without changing the ruby database config.

Dockerfile

```<code>FROM ruby:2.3.4
RUN apt-get update -qq && apt-get install -y build-essential libpq-dev nodejs
RUN mkdir /myapp
WORKDIR /myapp
ADD Gemfile /myapp/Gemfile
ADD Gemfile.lock /myapp/Gemfile.lock
RUN bundle install
ADD . /myapp
</code>```

Docker-compose

```<code>version: '3'
services:
  db:
    image: postgres:9.6
    ports:
      - "5432:5432"
  web:
    build: .
    ports:
      - "4000:4000"
    depends_on:
      - db
</code>```

Ruby database.yml

```<code>default: &default
  adapter: postgresql
  encoding: unicode
  pool: 5

development:
  <<: *default
  database: project_development
</code>```

If i run inside web conatiner "bundle exec rake db:create I get error:

```<code>psql: could not connect to server: No such file or directory
Is the server running locally and accepting
connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?
</code>```

I don't know what env set that will connect together.

答:
You should update your database.yml with the following:

```<code>  database: ENV['DB_NAME']
  username: ENV['DB_USERNAME']
  password: ENV['DB_PASSWORD']
</code>```

There's no such thing as "default PG user", so you have to create your own user with a proper permissions.

So, once you have a PG user created inside of container, you can update your docker-compose.yml file with a proper DB settings:

```<code>web:
  environment:
    - DB_NAME=rails_development
    - DB_USERNAME=rails_user
    - DB_PASSWORD=rails_password
</code>```

Also, you probably want to mount local storage of postgres in your docker-compose.yml to keep data when container restarts:

```<code>volumes:
  - /var/lib/postgresql/data
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I created Dockerfile to ruby from official docker-compose website. I used docker compose to integrate this with Postgres. When docker-compose up, then PostgreSQL starts but I cannot connect to this. The main problem is in ruby database config because I can't change to listen to another host and set the default user. I don't know how to connect these two containers without changing the ruby database config.

Dockerfile

FROM ruby:2.3.4
RUN apt-get update -qq && apt-get install -y build-essential libpq-dev nodejs
RUN mkdir /myapp
WORKDIR /myapp
ADD Gemfile /myapp/Gemfile
ADD Gemfile.lock /myapp/Gemfile.lock
RUN bundle install
ADD . /myapp

Docker-compose

version: '3'
services:
  db:
    image: postgres:9.6
    ports:
      - "5432:5432"
  web:
    build: .
    ports:
      - "4000:4000"
    depends_on:
      - db

Ruby database.yml

default: &default
  adapter: postgresql
  encoding: unicode
  pool: 5

development:
  <<: *default
  database: project_development

If i run inside web conatiner "bundle exec rake db:create I get error:

psql: could not connect to server: No such file or directory
Is the server running locally and accepting
connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?

I don't know what env set that will connect together.

Body:
You should update your database.yml with the following:

  database: ENV['DB_NAME']
  username: ENV['DB_USERNAME']
  password: ENV['DB_PASSWORD']

There's no such thing as "default PG user", so you have to create your own user with a proper permissions.

So, once you have a PG user created inside of container, you can update your docker-compose.yml file with a proper DB settings:

web:
  environment:
    - DB_NAME=rails_development
    - DB_USERNAME=rails_user
    - DB_PASSWORD=rails_password

Also, you probably want to mount local storage of postgres in your docker-compose.yml to keep data when container restarts:

volumes:
  - /var/lib/postgresql/data


问:
HTML form - PHP not inserting into Database correctly
i'm only tring to make a form work.
Its a similar for than i am fillin now: question, text, tags.

Fine,

this is when i print the form

```<code>function imprimir_formulario_pregunta(){
    $html = '<form id="pregunta" name ="pregunta" method="post" action="preguntas.php">';
    $html .= '<h2>Pregunta</h2>';

    $html .= '<input name="q" id="q" type="text" value=" "></input>';
    $html .= '<h2>Explica tu duda</h2>';
    $html .= '<textarea name="texto" id="texto" /
                    ></textarea>';
    $html .= '<h2>Etiquetas (separadas por comas)</h2>';
    $html .= '<input name="tags" id="tags"/>';
    $html .= '<input name="responde_a" style="display:none;" id="responde_a" value="0"/>';

    $html .= '<button name="pregunta" id="pregunta" type="submit" >Publicar</button>';

    $html .= '</form>';

    echo $html;

}
</code>```

this is when i recive data

```<code>if(isset($_POST['pregunta'])){
    $p_title = $_POST['q'];
    $p_text = $_POST['texto'];
    $p_et = $_POST['etiquetas'];
    $p_resp = $_POST['responde_a'];
    post_pregunta($p_title,$p_text, $p_et, $p_resp);
</code>```

this is when i process data

```<code>function obtener_id_pregunta($p,$t){
    $consulta = mysql_query("SELECT * FROM preguntas WHERE pregunta='$p' && texto='$t'");
    while($item = mysql_fetch_array($consulta)){
        return $item['id'];
    }
}

function    post_pregunta($a,$t,$et,$r){
    mostrar_notificacion("hemos entrado");
    //// ******
    if($a != '' && $t != ''){
        $b = $a;
        guardar_pregunta($b,$t,$r);
        $id = obtener_id_pregunta($b,$t);
        $temp = new etiqueta(0, '');
        $basura = $temp->guardar_etiquetas($et, $id, $_SESSION['id']);

    }else
        mostrar_notificacion("hemos salido $a $t");
}

function guardar_pregunta($p,$t,$r){
    $id_tmp = $_SESSION['id'];
    $insert = "INSERT INTO preguntas (pregunta,texto,id_usuario,fecha,responde_a) VALUES ('$p','$t','$id_tmp',NOW(),'$r')";
    $qry = mysql_query($insert);
    if(mysql_affected_rows())
    {
        mostrar_notificacion("La pregunta $p ($t)($r) se guardo");
        return true;
    }
    else
    {
        mostrar_notificacion("Error Ingresando datos");
        return false;
    }
    return false;
}
</code>```

Result:

I get the insert in the database done, but the 'q' field has a '' value....

Notes:
It looses the value in the step ** because it enters in the condition, but it doesn't in the next one wich is the same question...

Please tell me you have my answer, been too long on this.. and i need it done this week for class

Thanks in advance

答:
It's hard to see what's going on - as @vincebowdren says, you just need to debug this every step of the way.

However, more worryingly you're using $_POST data directly in a SQL query - this is an SQL injection attack waiting to happen.

Ensure you wrap ALL such variables in a mysql_real_escape_string function within your queries.

e.g.:

```<code> $insert = "INSERT INTO preguntas (pregunta,texto,id_usuario,fecha,responde_a) VALUES ('".mysql_real_escape_string($p)."','".mysql_real_escape_string($t)."','$id_tmp',NOW(),'".mysql_real_escape_string($r)."')";
</code>```

See How can I prevent SQL injection in PHP? for more information.

ContentLicense: CC BY-SA 2.5

Body:
i'm only tring to make a form work.
Its a similar for than i am fillin now: question, text, tags.

Fine,

this is when i print the form

function imprimir_formulario_pregunta(){
    $html = '<form id="pregunta" name ="pregunta" method="post" action="preguntas.php">';
    $html .= '
Pregunta
';

    $html .= '<input name="q" id="q" type="text" value=" "></input>';
    $html .= '
Explica tu duda
';
    $html .= '<textarea name="texto" id="texto" /
                    ></textarea>';
    $html .= '
Etiquetas (separadas por comas)
';
    $html .= '<input name="tags" id="tags"/>';
    $html .= '<input name="responde_a" style="display:none;" id="responde_a" value="0"/>';

    $html .= '<button name="pregunta" id="pregunta" type="submit" >Publicar</button>';

    $html .= '</form>';

    echo $html;

}

this is when i recive data

if(isset($_POST['pregunta'])){
    $p_title = $_POST['q'];
    $p_text = $_POST['texto'];
    $p_et = $_POST['etiquetas'];
    $p_resp = $_POST['responde_a'];
    post_pregunta($p_title,$p_text, $p_et, $p_resp);

this is when i process data

function obtener_id_pregunta($p,$t){
    $consulta = mysql_query("SELECT * FROM preguntas WHERE pregunta='$p' && texto='$t'");
    while($item = mysql_fetch_array($consulta)){
        return $item['id'];
    }
}

function    post_pregunta($a,$t,$et,$r){
    mostrar_notificacion("hemos entrado");
    //// ******
    if($a != '' && $t != ''){
        $b = $a;
        guardar_pregunta($b,$t,$r);
        $id = obtener_id_pregunta($b,$t);
        $temp = new etiqueta(0, '');
        $basura = $temp->guardar_etiquetas($et, $id, $_SESSION['id']);

    }else
        mostrar_notificacion("hemos salido $a $t");
}

function guardar_pregunta($p,$t,$r){
    $id_tmp = $_SESSION['id'];
    $insert = "INSERT INTO preguntas (pregunta,texto,id_usuario,fecha,responde_a) VALUES ('$p','$t','$id_tmp',NOW(),'$r')";
    $qry = mysql_query($insert);
    if(mysql_affected_rows())
    {
        mostrar_notificacion("La pregunta $p ($t)($r) se guardo");
        return true;
    }
    else
    {
        mostrar_notificacion("Error Ingresando datos");
        return false;
    }
    return false;
}

Result:

I get the insert in the database done, but the 'q' field has a '' value....

Notes:
It looses the value in the step ** because it enters in the condition, but it doesn't in the next one wich is the same question...

Please tell me you have my answer, been too long on this.. and i need it done this week for class

Thanks in advance

Body:
It's hard to see what's going on - as @vincebowdren says, you just need to debug this every step of the way.

However, more worryingly you're using $_POST data directly in a SQL query - this is an SQL injection attack waiting to happen.

Ensure you wrap ALL such variables in a mysql_real_escape_string function within your queries.

e.g.:

 $insert = "INSERT INTO preguntas (pregunta,texto,id_usuario,fecha,responde_a) VALUES ('".mysql_real_escape_string($p)."','".mysql_real_escape_string($t)."','$id_tmp',NOW(),'".mysql_real_escape_string($r)."')";

See How can I prevent SQL injection in PHP? for more information.


问:
Adding Methods to Constructors
Refactor the carlike function in a way that allows us to use the method calling syntax with "dot access".

var carlike = function(obj, loc) {
  obj.loc = loc;
  return obj;
};

var move = function(car) {
  car.loc++;
};

var amy = carlike({}, 1);
var ben = carlike({}, 9);

/*
Here we want to call move with "dot access"

amy.move();
ben.move();
*/```
</div>
</div>
</p>

<p><strong>THIS IS WHAT I'VE DONE...</strong></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>var carlike = function(obj, loc) {
  obj.loc = loc;
  obj.move = move;//CHANGE#1
  return obj;
};

var move = function(car) {
  car.loc++;
};

var amy = carlike({}, 1);
var ben = carlike({}, 9);
amy.move();//CHANGE#2
ben.move();//CHANGE#3</code>```

BUT IT WON'T WORK IT'S HAVING ERROR REGARDING LOCATION VARIABLE WHICH WAS WORKING GOOD UNTIL!

Thank You in Advance ☺

答:
The problem here is you're trying to execute function car without arguments, a proper solution should be change move function like this:

```<code>var move = function() {
  this.loc++;
};
</code>```

Now, you're accessing to the object over the function is executed, in the first case amy, in the second ben. The final solution should be something like this.

var carlike = function(obj, loc) {
  obj.loc = loc;
  obj.move = move;
  return obj;
};

var move = function() {
  this.loc++;
};

var amy = carlike({}, 1);
var ben = carlike({}, 9);
amy.move();
ben.move();```

Title: Adding Methods to Constructors

Body:
Refactor the carlike function in a way that allows us to use the method calling syntax with "dot access".

var carlike = function(obj, loc) {
  obj.loc = loc;
  return obj;
};

var move = function(car) {
  car.loc++;
};

var amy = carlike({}, 1);
var ben = carlike({}, 9);

/*
Here we want to call move with "dot access"

amy.move();
ben.move();
*/

THIS IS WHAT I'VE DONE...

var carlike = function(obj, loc) {
  obj.loc = loc;
  obj.move = move;//CHANGE#1
  return obj;
};

var move = function(car) {
  car.loc++;
};

var amy = carlike({}, 1);
var ben = carlike({}, 9);
amy.move();//CHANGE#2
ben.move();//CHANGE#3

BUT IT WON'T WORK IT'S HAVING ERROR REGARDING LOCATION VARIABLE WHICH WAS WORKING GOOD UNTIL!

Thank You in Advance ☺

Body:
The problem here is you're trying to execute function car without arguments, a proper solution should be change move function like this:

var move = function() {
  this.loc++;
};

Now, you're accessing to the object over the function is executed, in the first case amy, in the second ben. The final solution should be something like this.

var carlike = function(obj, loc) {
  obj.loc = loc;
  obj.move = move;
  return obj;
};

var move = function() {
  this.loc++;
};

var amy = carlike({}, 1);
var ben = carlike({}, 9);
amy.move();
ben.move();


问:
Fast taps (clicks) on RecyclerView opens multiple Fragments
I have implemented onClick listener to my ViewHolder for my RecyclerView

But when I perform very fast double taps or mouse clicks, it performs the task (opens a seperate fragment in this case) twice or three times.

here is my code

```<code>    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
    TextView tvTitle, tvDescription;

    public ViewHolder(View itemView) {
        super(itemView);
        itemView.setClickable(true);
        itemView.setOnClickListener(this);

        tvTitle = (TextView) itemView.findViewById(R.id.tv_title);
        tvDescription = (TextView) itemView.findViewById(R.id.tv_description);
    }

    @Override
    public void onClick(View v) {
        mListener.onClick(FRAGMENT_VIEW, getAdapterPosition()); // open FRAGMENT_VIEW
    }
}
</code>```

Any ideas on how to prevent such behaviour?

答:
Add below attributes in your theme

```<code><item name="android:splitMotionEvents">false</item>
<item name="android:windowEnableSplitTouch">false</item>
</code>```

This will prevent multiple tap at same time.

Body:
I have implemented onClick listener to my ViewHolder for my RecyclerView

But when I perform very fast double taps or mouse clicks, it performs the task (opens a seperate fragment in this case) twice or three times.

here is my code

    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
    TextView tvTitle, tvDescription;

    public ViewHolder(View itemView) {
        super(itemView);
        itemView.setClickable(true);
        itemView.setOnClickListener(this);

        tvTitle = (TextView) itemView.findViewById(R.id.tv_title);
        tvDescription = (TextView) itemView.findViewById(R.id.tv_description);
    }

    @Override
    public void onClick(View v) {
        mListener.onClick(FRAGMENT_VIEW, getAdapterPosition()); // open FRAGMENT_VIEW
    }
}

Any ideas on how to prevent such behaviour?

Body:
Add below attributes in your theme

<item name="android:splitMotionEvents">false</item>
<item name="android:windowEnableSplitTouch">false</item>

This will prevent multiple tap at same time.


问:
PageSettings keep getting modifed unexpectedly
It seems that you can persist in a settings file PrinterSettings and also PageSettings, they are Serializable etc.  Great!  Everything was going OK until I tried to persist my PageSettings and the margins.  Everytime I change the margins, save the settings and then reload them back into the PageSetupDialog.PageSettings - they have been modified.  Does anyone know why this happens? Is it something that the driver or Windows is doing ?  Its bizarre, see below:

Here I show the dialog:

```<code>PageSetupDialog psd = new PageSetupDialog();
psd.PageSettings = MySettings.Default.pageSettings;

    if (psd.ShowDialog() == DialogResult.OK)
</code>```

I manually change the values to 5.

Then I save the changes:

```<code>MySettings.Default.pageSettings = psd.PageSettings;
</code>```

When I reload the dialog and load in the settings from the settings file the values have changed to 2!?

UPDATE:

So just to try and expand on the problem - if we show the PageSetupDialog for the first time with default settings values which are 10 for all margins.  If we inspect the values during debug then we see them represented like this:

So they are all 100, strange but I expected them to be 10 i.e. like 10mm like the dialog says, so I don't know what unit of measure 100 is pertaining to be but anyway lets assume that it correlates with 10 in the dialog.

We then edit them all to 5 in the dialog and press OK - so we get past this code:

```<code>if (psd.ShowDialog() == DialogResult.OK)
</code>```

so we would expect to see on inspection of the pageSettingDialog object to see some values for the margins to be all 5 (or 50, as seems to be the case in the 10 vs 100 confusion, see above).  Let's have a look at the object then:

Low and behold it's not what we were expecting, it's 20 for some bizarre reason.  That's where I get stuck, I just can't work out whats going on behind the seens here.  Why is it changing from 50 to 20?, why won't it keep the value I set?
Hope that explains it a little bit better.

答:
The values for margins are in hundredths of an inch, with a default value of 100 (= 1 inch). 5 mm equals 0.196845455 inch, which rounds to 0.20. 0.20 times 100 equals 20. See this article on MSDN.

This explains what you are seeing during your debug session. As for your dialog, I think there is some cultural issue going on. I will look into this more if I have some time, but for now I hope this will help you a little further.

EDIT

Ok, what I think happens is that the dialog converts the metrics when leaving the dialog but doesn't do it when opening. I think you can create a workaround by converting your values when opening the dialog. Something like this:

```<code>PageSetupDialog psd = new PageSetupDialog();
Margins currentMargins =  MySettings.Default.pageSettings.Margins;
psd.PageSettings.Margins = new Margins(
   ConvInchToMm(currentMargins.Left), ConvInchToMm(currentMargins.Right),
   ConvInchToMm(currentMargins.Top), ConvInchToMm(currentMargins.Bottom));

private int ConvInchToMm(int hundrInch)
{
   return (int)(hundrInch * 2.54);
}
</code>```

Your PageSetupDialog also has an EnableMetric property, which should also solve your problems. I have not tested this though. See here.

```<code>PageSetupDialog psd = new PageSetupDialog();
psd.EnableMetric = true;
</code>```

Body:
It seems that you can persist in a settings file PrinterSettings and also PageSettings, they are Serializable etc.  Great!  Everything was going OK until I tried to persist my PageSettings and the margins.  Everytime I change the margins, save the settings and then reload them back into the PageSetupDialog.PageSettings - they have been modified.  Does anyone know why this happens? Is it something that the driver or Windows is doing ?  Its bizarre, see below:

Here I show the dialog:

PageSetupDialog psd = new PageSetupDialog();
psd.PageSettings = MySettings.Default.pageSettings;

    if (psd.ShowDialog() == DialogResult.OK)

I manually change the values to 5.

Then I save the changes:

MySettings.Default.pageSettings = psd.PageSettings;

When I reload the dialog and load in the settings from the settings file the values have changed to 2!?

UPDATE:

So just to try and expand on the problem - if we show the PageSetupDialog for the first time with default settings values which are 10 for all margins.  If we inspect the values during debug then we see them represented like this:

So they are all 100, strange but I expected them to be 10 i.e. like 10mm like the dialog says, so I don't know what unit of measure 100 is pertaining to be but anyway lets assume that it correlates with 10 in the dialog.

We then edit them all to 5 in the dialog and press OK - so we get past this code:

if (psd.ShowDialog() == DialogResult.OK)

so we would expect to see on inspection of the pageSettingDialog object to see some values for the margins to be all 5 (or 50, as seems to be the case in the 10 vs 100 confusion, see above).  Let's have a look at the object then:

Low and behold it's not what we were expecting, it's 20 for some bizarre reason.  That's where I get stuck, I just can't work out whats going on behind the seens here.  Why is it changing from 50 to 20?, why won't it keep the value I set?
Hope that explains it a little bit better.

Body:
The values for margins are in hundredths of an inch, with a default value of 100 (= 1 inch). 5 mm equals 0.196845455 inch, which rounds to 0.20. 0.20 times 100 equals 20. See this article on MSDN.

This explains what you are seeing during your debug session. As for your dialog, I think there is some cultural issue going on. I will look into this more if I have some time, but for now I hope this will help you a little further.

EDIT

Ok, what I think happens is that the dialog converts the metrics when leaving the dialog but doesn't do it when opening. I think you can create a workaround by converting your values when opening the dialog. Something like this:

PageSetupDialog psd = new PageSetupDialog();
Margins currentMargins =  MySettings.Default.pageSettings.Margins;
psd.PageSettings.Margins = new Margins(
   ConvInchToMm(currentMargins.Left), ConvInchToMm(currentMargins.Right),
   ConvInchToMm(currentMargins.Top), ConvInchToMm(currentMargins.Bottom));

private int ConvInchToMm(int hundrInch)
{
   return (int)(hundrInch * 2.54);
}

Your PageSetupDialog also has an EnableMetric property, which should also solve your problems. I have not tested this though. See here.

PageSetupDialog psd = new PageSetupDialog();
psd.EnableMetric = true;


问:
List actually used maven plugins in XML format for pom
It is an often helpful practice to declare the versions of all used maven plugins in the pom.xml, e.g. to make old builds reproducible after a new plugin version comes out. For a fresh project: is there a way to output the plugins currently used in the build in the XML-format I could easily put into the pluginManagement section of the pom.xml?

I found that versions:display-plugin-updates does output the plugins with versions that are not yet fixed, and help:effective-pom does display the actually used versions implicitly in <build><plugins>, but garbled with the configuration, executions and other information not needed for the pluginManagement section. So I'm looking for something easier - just like mvn -DoutputXML=true dependency:analyze does for dependencies.

答:
How about parsing the output of help:effective-pom ?

With grep for a quick-and-dirty solution :

```<code>$ mvn help:effective-pom -Doutput=effective-pom.xml
$ grep "<plugin>" -A 3 effective-pom.xml
    <plugin>
      <artifactId>maven-antrun-plugin</artifactId>
      <version>1.3</version>
    </plugin>
    <plugin>
      <artifactId>maven-assembly-plugin</artifactId>
      <version>2.2-beta-5</version>
    </plugin>
    <plugin>
      <artifactId>maven-dependency-plugin</artifactId>
      <version>2.8</version>
    </plugin>
    [...]
</code>```

Or with an XML Parser and the use of XSLT or XQuery for a more robust solution.

For example, the following XQuery code

```<code>declare default element namespace "http://maven.apache.org/POM/4.0.0";
string-join(
    for $plugin in //plugin
    return string-join(($plugin/groupId/text(), $plugin/artifactId/text(), $plugin/version/text()), ":"),
    "
"
)
</code>```

Will produce this kind of output :

```<code><?xml version="1.0" encoding="UTF-8"?>maven-antrun-plugin:1.3
maven-assembly-plugin:2.2-beta-5
maven-dependency-plugin:2.8
maven-release-plugin:2.3.2
maven-source-plugin:3.0.1
maven-clean-plugin:2.5
maven-install-plugin:2.4
maven-deploy-plugin:2.7
maven-site-plugin:3.3
</code>```

Note that the xml header could be removed with the appropriate configuration.

Body:
How about parsing the output of help:effective-pom ?

With grep for a quick-and-dirty solution :

$ mvn help:effective-pom -Doutput=effective-pom.xml
$ grep "<plugin>" -A 3 effective-pom.xml
    <plugin>
      <artifactId>maven-antrun-plugin</artifactId>
      <version>1.3</version>
    </plugin>
    <plugin>
      <artifactId>maven-assembly-plugin</artifactId>
      <version>2.2-beta-5</version>
    </plugin>
    <plugin>
      <artifactId>maven-dependency-plugin</artifactId>
      <version>2.8</version>
    </plugin>
    [...]

Or with an XML Parser and the use of XSLT or XQuery for a more robust solution.

For example, the following XQuery code

declare default element namespace "http://maven.apache.org/POM/4.0.0";
string-join(
    for $plugin in //plugin
    return string-join(($plugin/groupId/text(), $plugin/artifactId/text(), $plugin/version/text()), ":"),
    "&#10;"
)

Will produce this kind of output :

<?xml version="1.0" encoding="UTF-8"?>maven-antrun-plugin:1.3
maven-assembly-plugin:2.2-beta-5
maven-dependency-plugin:2.8
maven-release-plugin:2.3.2
maven-source-plugin:3.0.1
maven-clean-plugin:2.5
maven-install-plugin:2.4
maven-deploy-plugin:2.7
maven-site-plugin:3.3

Note that the xml header could be removed with the appropriate configuration.


问:
Wix Installer -- cannot view Radio Button on dialog
I am trying to give a choice to the user to choose a mode of authentication with which he/she wants to connect to database. Two choices I am providing are: windows authentication and sql server authentication.

For some reason I am not able to see the radio button on the dialog.

Dialog code is shown below:

```<code><Property Id="CHOICE_WIN_SQL" Value="1" Secure="yes"/>

  <Dialog Id="WinSqlChoiceDlg" Width="370" Height="270" Title="[ProductName] Setup">
    <Control Type="Text" Width="275" Height="10" X="25" Y="98" Id="TestRadioButton" Text="Radio button should appear below:" />
    <Control Id="AuthenticationType" Property="CHOICE_WIN_SQL" Type="RadioButtonGroup"  X="25" Y="98" Width="300" Height="50">
      <RadioButtonGroup Property="CHOICE_WIN_SQL">
        <RadioButton X="25" Y="110" Value="0" Height="10" Width="275" Text="Windows Authentication"/>
        <RadioButton X="25" Y="123" Value="1" Height="10" Width="275" Text="Sql Authentication"/>
      </RadioButtonGroup>
    </Control>
  </Dialog>
</code>```

答:
Change the X and Y values of the RadionButton to the following numbers:

RadioButton X="0" Y="0"

RadioButton X="0" Y="20"

So they should look like this:

```<code><RadioButton X="0" Y="0" Value="0" Height="10" Width="275" Text="Windows Authentication"/>
<RadioButton X="0" Y="20" Value="1" Height="10" Width="275" Text="Sql Authentication"/>
</code>```

Now the radio buttons will appear but the 'Windows Authentication' radio button will overlap with your label. So change the Y value to 50 for example:

```<code><Control Type="Text" Width="275" Height="10" X="25" Y="50" Id="TestRadioButton"
Text="Radio button should appear below:" />
</code>```

Your final code should look like this:

```<code><Property Id="CHOICE_WIN_SQL" Value="1" Secure="yes"/>
<Dialog Id="WinSqlChoiceDlg" Width="370" Height="270" Title="[ProductName] Setup">
<Control Type="Text" Width="275" Height="10" X="25" Y="50" Id="TestRadioButton" Text="Radio button should appear below:" />
<Control Id="AuthenticationType" Property="CHOICE_WIN_SQL" Type="RadioButtonGroup"  X="25" Y="98" Width="300" Height="50">
  <RadioButtonGroup Property="CHOICE_WIN_SQL">
    <RadioButton X="0" Y="0" Value="0" Height="10" Width="275" Text="Windows Authentication"/>
    <RadioButton X="0" Y="20" Value="1" Height="10" Width="275" Text="Sql Authentication"/>
  </RadioButtonGroup>
</Control>
</code>```

That should do the trick.

Body:
I am trying to give a choice to the user to choose a mode of authentication with which he/she wants to connect to database. Two choices I am providing are: windows authentication and sql server authentication.

For some reason I am not able to see the radio button on the dialog.

Dialog code is shown below:

<Property Id="CHOICE_WIN_SQL" Value="1" Secure="yes"/>

  <Dialog Id="WinSqlChoiceDlg" Width="370" Height="270" Title="[ProductName] Setup">
    <Control Type="Text" Width="275" Height="10" X="25" Y="98" Id="TestRadioButton" Text="Radio button should appear below:" />
    <Control Id="AuthenticationType" Property="CHOICE_WIN_SQL" Type="RadioButtonGroup"  X="25" Y="98" Width="300" Height="50">
      <RadioButtonGroup Property="CHOICE_WIN_SQL">
        <RadioButton X="25" Y="110" Value="0" Height="10" Width="275" Text="Windows Authentication"/>
        <RadioButton X="25" Y="123" Value="1" Height="10" Width="275" Text="Sql Authentication"/>
      </RadioButtonGroup>
    </Control>
  </Dialog>

Body:
Change the X and Y values of the RadionButton to the following numbers:

RadioButton X="0" Y="0"

RadioButton X="0" Y="20"

So they should look like this:

<RadioButton X="0" Y="0" Value="0" Height="10" Width="275" Text="Windows Authentication"/>
<RadioButton X="0" Y="20" Value="1" Height="10" Width="275" Text="Sql Authentication"/>

Now the radio buttons will appear but the 'Windows Authentication' radio button will overlap with your label. So change the Y value to 50 for example:

<Control Type="Text" Width="275" Height="10" X="25" Y="50" Id="TestRadioButton"
Text="Radio button should appear below:" />

Your final code should look like this:

<Property Id="CHOICE_WIN_SQL" Value="1" Secure="yes"/>
<Dialog Id="WinSqlChoiceDlg" Width="370" Height="270" Title="[ProductName] Setup">
<Control Type="Text" Width="275" Height="10" X="25" Y="50" Id="TestRadioButton" Text="Radio button should appear below:" />
<Control Id="AuthenticationType" Property="CHOICE_WIN_SQL" Type="RadioButtonGroup"  X="25" Y="98" Width="300" Height="50">
  <RadioButtonGroup Property="CHOICE_WIN_SQL">
    <RadioButton X="0" Y="0" Value="0" Height="10" Width="275" Text="Windows Authentication"/>
    <RadioButton X="0" Y="20" Value="1" Height="10" Width="275" Text="Sql Authentication"/>
  </RadioButtonGroup>
</Control>

That should do the trick.


问:
c# implementing an interface to operate running program commandline style
I am using NDesk.Options to parse command line arguments.

This allows me to call my WPF Application with different startup options like open Formular Foo with Entity X. This works.

I wonder how I might implement an interface which allows injecting a command line argument in the running application.

I guess I'd have to look-up the process and call a method CustomCommandlineProcessing(string) on it, passing the arguments I need.

Questions

How can I implement a method that can be called external?

How do I call it on the running Application?

Do I need to take note of anything special?

e.g. special access to the GUI Thread (beside the normal async stuff)?

Just comment requesting me to qualify my Questions.

答:
If your application is already running, then anything you 'pass' to it will not be a command line argument...

You probably want to look into inter-process communication;

https://en.wikipedia.org/wiki/Inter-process_communication

The most common methods would be a web interface, a socket or named pipe, a memory-mapped file or a shared database.


问:
JQuery find a div with a certain classname and specific text
What I'm trying to do is is find an elements from all the child elements within my parent element (el) that have a certain class and a certain text. I just want the div

This works $(el).children().find("div") and finds all the children

So I want the div with inner text "hello" with a class of "selected"

```<code>$(el).children().find("div").text("hello").hasClass("selected");
</code>```

The line above doesn't do anything or has some were side effect of changing all this child elements text to something random.

I am def NOT a jquery expert and can't seem to find the right combination of selectors to get the job done

答:
Using class selector and contains together, this should do </p>

```<code>  var childs =   $(el).find("div.selected:contains('hello')");
</code>```

Body:
What I'm trying to do is is find an elements from all the child elements within my parent element (el) that have a certain class and a certain text. I just want the div

This works $(el).children().find("div") and finds all the children

So I want the div with inner text "hello" with a class of "selected"

$(el).children().find("div").text("hello").hasClass("selected");

The line above doesn't do anything or has some were side effect of changing all this child elements text to something random.

I am def NOT a jquery expert and can't seem to find the right combination of selectors to get the job done

Body:
Using class selector and contains together, this should do

  var childs =   $(el).find("div.selected:contains('hello')");


问:
OutOfMemoryError Failed to allocate a 1250874912 byte allocation with 16777216 free bytes and 338MB until OOM
I am just fetching an image from drawable and getting it into bitmap but while getting into bitmap its throws an error

java.lang.OutOfMemoryError: Failed to allocate a 1250874912 byte allocation with 16777216 free bytes and 338MB until OOM

Here is my code below

```<code>Bitmap icon = BitmapFactory.decodeResource(getResources(),
            R.drawable.vr_image);
    int size = icon.getByteCount();
</code>```

Some solution found on stackoverflow but these also not working.

on manifest under application tag i have define following values

```<code> android:allowBackup="true"
    android:hardwareAccelerated="false"
    android:largeHeap="true"
    android:supportsRtl="true"
</code>```

So any one can help me out from this problem not getting any solution for this.

答: You are facing this problem because of the size of the image . It is too big either use  library like ---http://square.github.io/picasso/  or decrease the size of image. better to use picasso .please dont increase size in the application it will effect the app performance.</p>

Body:
I am just fetching an image from drawable and getting it into bitmap but while getting into bitmap its throws an error

java.lang.OutOfMemoryError: Failed to allocate a 1250874912 byte allocation with 16777216 free bytes and 338MB until OOM

Here is my code below

Bitmap icon = BitmapFactory.decodeResource(getResources(),
            R.drawable.vr_image);
    int size = icon.getByteCount();

Some solution found on stackoverflow but these also not working.

on manifest under application tag i have define following values

 android:allowBackup="true"
    android:hardwareAccelerated="false"
    android:largeHeap="true"
    android:supportsRtl="true"

So any one can help me out from this problem not getting any solution for this.


问:
NHibernate sub sub class property query
I have a class A which contains a class B which contains a class C with a property P. So something like this should work shouldn't it?:

```<code>var query = Session.CreateCriteria(typeof(A));
query.Add(Expression.InsensitiveLike(
              Projections.Cast(NHibernateUtil.String,
                               Projections.Property("B.C.P")),
              "%bla%", MatchMode.Exact));
</code>```

I get a could not resolve property exception.

I understand that I can use CreateAlias etc., which I have also tried with no avail. At the moment I opted for an 'implicit association join'.

Any feedback would be very much appreciated. Many thanks.

Chris

答:
CreateAlias (or CreateCriteria) is the only way to do it.</p>

```<code>var query = Session.CreateCriteria<A>()
                   .CreateAlias("B", "B")
                   .CreateAlias("B.C", "C");
query.Add(Expression.InsensitiveLike(
              Projections.Cast(NHibernateUtil.String,
                               Projections.Property("C.P")),
              "%bla%", MatchMode.Exact));
</code>```

Title: NHibernate sub sub class property query

Body:
I have a class A which contains a class B which contains a class C with a property P. So something like this should work shouldn't it?:

var query = Session.CreateCriteria(typeof(A));
query.Add(Expression.InsensitiveLike(
              Projections.Cast(NHibernateUtil.String,
                               Projections.Property("B.C.P")),
              "%bla%", MatchMode.Exact));

I get a could not resolve property exception.

I understand that I can use CreateAlias etc., which I have also tried with no avail. At the moment I opted for an 'implicit association join'.

Any feedback would be very much appreciated. Many thanks.

Chris

Body:
CreateAlias (or CreateCriteria) is the only way to do it.

var query = Session.CreateCriteria<A>()
                   .CreateAlias("B", "B")
                   .CreateAlias("B.C", "C");
query.Add(Expression.InsensitiveLike(
              Projections.Cast(NHibernateUtil.String,
                               Projections.Property("C.P")),
              "%bla%", MatchMode.Exact));


问:
Using OnkeyDown as an if condition Javascript
I would like to use .onkeydown to restrain my input field. I wrote this function, but I'd like to use it in an if condition, to check if entry keys are right or wrong.

But I don't know how form should I use in my if to call this function, because actually it's not really an Angular scope function, but a JS one...

var cpNumber = document.getElementById("cpNumber");
cpNumber.onkeydown = function(e) {
    if((e.keyCode > 95 && e.keyCode < 106)
        || (e.keyCode > 47 && e.keyCode < 58)
        || ((e.keyCode > 95 && e.keyCode < 106)
        || (e.keyCorde == 65))
        || ((e.keyCode > 47 && e.keyCode < 58)
        || (e.keyCode == 65))
        || ((e.keyCode > 95 && e.keyCode < 106)
        || (e.keyCorde == 66))
        || ((e.keyCode > 47 && e.keyCode < 58)
        || (e.keyCode == 66))
        || e.keyCode == 8) {
        return true;
    } else {
        return false;
    }
};

// If condition, check if entry keys are wrong.
// I tried cpNumber.onkeydown(e), but the "e"
// seems drop from the sky, it always shows "false".

if(cpNumber.onkeydown(e) === false) {
    alertPopup = $ionicPopup.alert({
        title: 'Oups...',
        cssClass: 'pop',
        template: '
This is Wrong !
'
    });
}
  ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form>
    <input class="input"
           type="text"
           id="cpNumber"
           maxlength="5"
           ng-model="cp"
           placeholder="CP">
</form></code>```

答:
Event cannot be called this way. For making your program functional you can add a function in your else block and call it and do whatever you want.
PLUS you can also pass your event to function. So that will serve as an added advantage.
HTML:

```<code> <form><input class="input" type="text" id="cpNumber" maxlength="5" ng-model="cp" placeholder="CP"></form>
</code>```

Script::

```<code>ar cpNumber = document.getElementById("cpNumber");

                        cpNumber.onkeydown = function(e) {

                                if((e.keyCode > 95 && e.keyCode < 106)
                                  || (e.keyCode > 47 && e.keyCode < 58)
                                  || ((e.keyCode > 95 && e.keyCode < 106)
                                  || (e.keyCorde == 65))
                                  || ((e.keyCode > 47 && e.keyCode < 58)
                                  || (e.keyCode == 65))
                                  || ((e.keyCode > 95 && e.keyCode < 106)
                                  || (e.keyCorde == 66))
                                  || ((e.keyCode > 47 && e.keyCode < 58)
                                  || (e.keyCode == 66))
                                  || e.keyCode == 8)
                                {
                                    return true;
                                }
                                else
                                {
                                    notAllowed(e);
                                }
                        };

        // If condition, check if entry keys are wrong. I tried cpNumber.onkeydown(e), but the "e" seems drop from the sky, it always shows "false".

                            function notAllowed (ev) {
                               alertPopup = $ionicPopup.alert({
                                    title: 'Oups...',
                                    cssClass: 'pop',
                                    template: '<div class="center-form">This is Wrong !</div>'
                                });
                            }
</code>```

Body:
I would like to use .onkeydown to restrain my input field. I wrote this function, but I'd like to use it in an if condition, to check if entry keys are right or wrong.

But I don't know how form should I use in my if to call this function, because actually it's not really an Angular scope function, but a JS one...

var cpNumber = document.getElementById("cpNumber");
cpNumber.onkeydown = function(e) {
    if((e.keyCode > 95 && e.keyCode < 106)
        || (e.keyCode > 47 && e.keyCode < 58)
        || ((e.keyCode > 95 && e.keyCode < 106)
        || (e.keyCorde == 65))
        || ((e.keyCode > 47 && e.keyCode < 58)
        || (e.keyCode == 65))
        || ((e.keyCode > 95 && e.keyCode < 106)
        || (e.keyCorde == 66))
        || ((e.keyCode > 47 && e.keyCode < 58)
        || (e.keyCode == 66))
        || e.keyCode == 8) {
        return true;
    } else {
        return false;
    }
};

// If condition, check if entry keys are wrong.
// I tried cpNumber.onkeydown(e), but the "e"
// seems drop from the sky, it always shows "false".

if(cpNumber.onkeydown(e) === false) {
    alertPopup = $ionicPopup.alert({
        title: 'Oups...',
        cssClass: 'pop',
        template: '
This is Wrong !
'
    });
}

<form>
    <input class="input"
           type="text"
           id="cpNumber"
           maxlength="5"
           ng-model="cp"
           placeholder="CP">
</form>

Body:
Event cannot be called this way. For making your program functional you can add a function in your else block and call it and do whatever you want.
PLUS you can also pass your event to function. So that will serve as an added advantage.
HTML:

 <form><input class="input" type="text" id="cpNumber" maxlength="5" ng-model="cp" placeholder="CP"></form>

Script::

ar cpNumber = document.getElementById("cpNumber");

                        cpNumber.onkeydown = function(e) {

                                if((e.keyCode > 95 && e.keyCode < 106)
                                  || (e.keyCode > 47 && e.keyCode < 58)
                                  || ((e.keyCode > 95 && e.keyCode < 106)
                                  || (e.keyCorde == 65))
                                  || ((e.keyCode > 47 && e.keyCode < 58)
                                  || (e.keyCode == 65))
                                  || ((e.keyCode > 95 && e.keyCode < 106)
                                  || (e.keyCorde == 66))
                                  || ((e.keyCode > 47 && e.keyCode < 58)
                                  || (e.keyCode == 66))
                                  || e.keyCode == 8)
                                {
                                    return true;
                                }
                                else
                                {
                                    notAllowed(e);
                                }
                        };

        // If condition, check if entry keys are wrong. I tried cpNumber.onkeydown(e), but the "e" seems drop from the sky, it always shows "false".

                            function notAllowed (ev) {
                               alertPopup = $ionicPopup.alert({
                                    title: 'Oups...',
                                    cssClass: 'pop',
                                    template: '<div class="center-form">This is Wrong !</div>'
                                });
                            }


问:
How to read SNMP variable bindings
I am trying to make a snmp trap receiver, that can capture all the incoming snmp trap from UDP 162 port and translate them into meaningful alarms. The image I attached is a sample trap that I captured using wireshark.

My script can capture and parse all different parts of the packet, but I got stuck in the variable binding section. Im not sure how I can re-present this section into some user friendly information (that I can show in the user interface). How do I know these sequences are sending something alarming or just some general information regarding the agent node? are these sequences independent information each or together they are forming one piece of information?

答:
As with any incoming data, it is important to know what kind of info you are getting. The variable bindings of an SNMP trap is basically a hierarchical piece of data. Every object or element represents it's own data. If you take the first element (1.3.6.1.2.1.1.3.0) you will find that this contains the sysUpTime (see link), which is pretty general.

Most of the other elements seem to start with 1.3.6.1.4.1.4421 which appears to be object from a specific vendor; Santera systems (see link). You might want to try and contact them in order to obtain their MIB (Management Information Base), which should have details on what kind of data is shown in these fields.

It might be possible to find info like this online, have a look at the XML-files on this link.

Title: How to read SNMP variable bindings


问:
Mongoose/Mongo: Update Not Saving
I'm extremely perplexed by this issue that I'm having with mongo/mongoose. I'm essentially trying to get an array of products, delete a certain product from the array, and then update the shopping chart with the new array that omits the selected product. Here's the snippet of code I'm dealing with:

```<code>const remove = (req, res, next) => {
  console.log('here is the product id ' + req.body.cart.product)
  delete req.body._owner // disallow owner reassignment.
  Cart.find({_id: req.user.cartId})
  .then((products1) => {
    console.log("array of products: " + products1[0].product)
    const index = products1[0].product.indexOf(req.body.cart.product)
    console.log("index valeu: " + index)
    if (index > -1) {
      products1[0].product.splice(index, 1)
      return products1[0].product
    }
    return products1[0].product
  })
  .then((products2) => {
    console.log('Second Promise Input: ' + products2)
    Cart.update({_id: req.user.cartId}, {$set: {product: products2}})
  })
  .then(() => res.sendStatus(204))
  .catch(next)
  }
</code>```

And here's the output from my server:

```<code>Server listening on port 4741
here is the product id 5952b57ea52d092b8d34c6b0
array of products: 5952b57ea52d092b8d34c6b0,5952b57ea52d092b8d34c6b0,5952b57ea52d092b8d34c6b0,5952b57ea52d092b8d34c6b0,5952b57ea52d092b8d34c6b0
index valeu: 0
Second Promise Input: 5952b57ea52d092b8d34c6b0,5952b57ea52d092b8d34c6b0,5952b57ea52d092b8d34c6b0,5952b57ea52d092b8d34c6b0
PATCH /carts-decrease/595b037e128cfd37e0c864d7 204 38.773 ms
</code>```

According to my console.logs, I'm getting the array just the way I want it but it simply does not update the shopping cart with the new array. I've been staring at this code for far too long and I'd appreciate a second set of eyes on this. Thanks.

P.S. Ignore the fact that the product ids are all the same, its just a testing variable

Cart Schema:

```<code>'use strict'

const mongoose = require('mongoose')

const cartSchema = new mongoose.Schema({
  product: {
    type: Array,
    required: false
  },
  owner: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User',
    required: false
  }
}, {
  timestamps: true,
  toJSON: {
    virtuals: true,
    transform: function (doc, ret, options) {
      const userId = (options.user && options.user._id) || false
      ret.editable = userId && userId.equals(doc._owner)
      return ret
    }
  }
})

const Cart = mongoose.model('Cart', cartSchema)

module.exports = Cart
</code>```

Product Schema:

```<code>'use strict'

const mongoose = require('mongoose')

const productSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true
  },
  price: {
    type: Number,
    required: true
  },
  description: {
    type: String,
    required: true
  }
}, {
  toJSON: {
    virtuals: true
  }
})

const Product = mongoose.model('Product', productSchema)

module.exports = Product
</code>```

Show request:

```<code>const show = (req, res) => {
  const product = {}
  product.array = []
//  console.log(req.cart.product)
  const promises = []

  Promise.all(req.cart.product.map(function (id) {
    return Product.find({_id: ObjectId(id)})
  })).then(function (products) {
    console.log(products)
    req.cart.product = products
    return res.json({
      cart: req.cart.toJSON({virtuals: true, user: req.user})
    })
  }).catch(function (err) {
    console.log(err)
    return res.sendStatus(500)
  })
}
</code>```

答:
I would recommend you to slightly modify your cartSchema and store products in the form of an array of embedded documents:

```<code>const cartSchema = new mongoose.Schema({
    products: [{
        name: { type: String },
        price: { type: Number }
        ...
    }]
    ...
});
</code>```

If you do this you can simply use the $pull update operator to remove products from your cart:

```<code>{ $pull: { <field1>: <value|condition>, <field2>: <value|condition>, ... } }
</code>```

In your case the query should then look like this:

```<code>Cart.update(
    { _id: req.user.cartId },
    { $pull: { products: { '_id': req.body.cart.product } }}
);
</code>```

As the embedded documents will have their own ObjectId there will only be one document matching the query.

Title: Mongoose/Mongo: Update Not Saving

Body:
I'm extremely perplexed by this issue that I'm having with mongo/mongoose. I'm essentially trying to get an array of products, delete a certain product from the array, and then update the shopping chart with the new array that omits the selected product. Here's the snippet of code I'm dealing with:

const remove = (req, res, next) => {
  console.log('here is the product id ' + req.body.cart.product)
  delete req.body._owner // disallow owner reassignment.
  Cart.find({_id: req.user.cartId})
  .then((products1) => {
    console.log("array of products: " + products1[0].product)
    const index = products1[0].product.indexOf(req.body.cart.product)
    console.log("index valeu: " + index)
    if (index > -1) {
      products1[0].product.splice(index, 1)
      return products1[0].product
    }
    return products1[0].product
  })
  .then((products2) => {
    console.log('Second Promise Input: ' + products2)
    Cart.update({_id: req.user.cartId}, {$set: {product: products2}})
  })
  .then(() => res.sendStatus(204))
  .catch(next)
  }

And here's the output from my server:

Server listening on port 4741
here is the product id 5952b57ea52d092b8d34c6b0
array of products: 5952b57ea52d092b8d34c6b0,5952b57ea52d092b8d34c6b0,5952b57ea52d092b8d34c6b0,5952b57ea52d092b8d34c6b0,5952b57ea52d092b8d34c6b0
index valeu: 0
Second Promise Input: 5952b57ea52d092b8d34c6b0,5952b57ea52d092b8d34c6b0,5952b57ea52d092b8d34c6b0,5952b57ea52d092b8d34c6b0
PATCH /carts-decrease/595b037e128cfd37e0c864d7 204 38.773 ms

According to my console.logs, I'm getting the array just the way I want it but it simply does not update the shopping cart with the new array. I've been staring at this code for far too long and I'd appreciate a second set of eyes on this. Thanks.

P.S. Ignore the fact that the product ids are all the same, its just a testing variable

Cart Schema:

'use strict'

const mongoose = require('mongoose')

const cartSchema = new mongoose.Schema({
  product: {
    type: Array,
    required: false
  },
  owner: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User',
    required: false
  }
}, {
  timestamps: true,
  toJSON: {
    virtuals: true,
    transform: function (doc, ret, options) {
      const userId = (options.user && options.user._id) || false
      ret.editable = userId && userId.equals(doc._owner)
      return ret
    }
  }
})

const Cart = mongoose.model('Cart', cartSchema)

module.exports = Cart

Product Schema:

'use strict'

const mongoose = require('mongoose')

const productSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true
  },
  price: {
    type: Number,
    required: true
  },
  description: {
    type: String,
    required: true
  }
}, {
  toJSON: {
    virtuals: true
  }
})

const Product = mongoose.model('Product', productSchema)

module.exports = Product

Show request:

const show = (req, res) => {
  const product = {}
  product.array = []
//  console.log(req.cart.product)
  const promises = []

  Promise.all(req.cart.product.map(function (id) {
    return Product.find({_id: ObjectId(id)})
  })).then(function (products) {
    console.log(products)
    req.cart.product = products
    return res.json({
      cart: req.cart.toJSON({virtuals: true, user: req.user})
    })
  }).catch(function (err) {
    console.log(err)
    return res.sendStatus(500)
  })
}

Body:
I would recommend you to slightly modify your cartSchema and store products in the form of an array of embedded documents:

const cartSchema = new mongoose.Schema({
    products: [{
        name: { type: String },
        price: { type: Number }
        ...
    }]
    ...
});

If you do this you can simply use the $pull update operator to remove products from your cart:

{ $pull: { <field1>: <value|condition>, <field2>: <value|condition>, ... } }

In your case the query should then look like this:

Cart.update(
    { _id: req.user.cartId },
    { $pull: { products: { '_id': req.body.cart.product } }}
);

As the embedded documents will have their own ObjectId there will only be one document matching the query.


答:
Your syntax is a little off. Firstly you can use find() alone without calling children() first, hasClass returns a boolean not a jQuery object, and text() is used to set a value, not find an element.

To do what you require you should put the class on the selector in the find() call, then use :contains to search for the element with the relevant text content. Try this:

```<code>$(el).find("div.selected:contains('hello')")
</code>```

Title: JQuery find a div with a certain classname and specific text

Body:
Your syntax is a little off. Firstly you can use find() alone without calling children() first, hasClass returns a boolean not a jQuery object, and text() is used to set a value, not find an element.

To do what you require you should put the class on the selector in the find() call, then use :contains to search for the element with the relevant text content. Try this:

$(el).find("div.selected:contains('hello')")


问:
How do i upload an image to my mysql database with php?
I know that i should use LONGBLOB, and i've written this code so far that uploads text to my server. How do i upload images instead of text?.

```<code>//if(isset...)
$connectionText = mysql_connect("localhost", "root");

if(!$connectionText){
die("Noget gik galt?". mysql_connect_error());
}
mysql_select_db("textbox", $connectionText);

$t = $_POST['tekst'];

$sqlScript = "INSERT INTO form (tekst) VALUES ('$t')";

mysql_query($sqlScript, $connectionText);
mysql_close($connectionText);
</code>```

It should save the path to the mysql database. The image should be stored on the servers' computer.

答:
You don't need to store image directly into to database. Just store the image name in the database and fetch it when you want to show.
For e.g.</p>

```<code>$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    if($check !== false) {
        echo "File is an image - " . $check["mime"] . ".";
        $uploadOk = 1;
    } else {
        echo "File is not an image.";
        $uploadOk = 0;
    }
}
// Check if file already exists
if (file_exists($target_file)) {
    echo "Sorry, file already exists.";
    $uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
    echo "Sorry, your file is too large.";
    $uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
    echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
    $uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        // execute your insert query here
       $sqlScript = "INSERT INTO form (image) VALUES ('".basename( $_FILES["fileToUpload"]["name"])."')";

    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}
</code>```

Body:
I know that i should use LONGBLOB, and i've written this code so far that uploads text to my server. How do i upload images instead of text?.

//if(isset...)
$connectionText = mysql_connect("localhost", "root");

if(!$connectionText){
die("Noget gik galt?". mysql_connect_error());
}
mysql_select_db("textbox", $connectionText);

$t = $_POST['tekst'];

$sqlScript = "INSERT INTO form (tekst) VALUES ('$t')";

mysql_query($sqlScript, $connectionText);
mysql_close($connectionText);

It should save the path to the mysql database. The image should be stored on the servers' computer.

Body:
You don't need to store image directly into to database. Just store the image name in the database and fetch it when you want to show.
For e.g.

$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    if($check !== false) {
        echo "File is an image - " . $check["mime"] . ".";
        $uploadOk = 1;
    } else {
        echo "File is not an image.";
        $uploadOk = 0;
    }
}
// Check if file already exists
if (file_exists($target_file)) {
    echo "Sorry, file already exists.";
    $uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
    echo "Sorry, your file is too large.";
    $uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
    echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
    $uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        // execute your insert query here
       $sqlScript = "INSERT INTO form (image) VALUES ('".basename( $_FILES["fileToUpload"]["name"])."')";

    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}


问:
Regular expression: if three letters are included
I've got a number of word:
hello, poison, world, search, echo ...
And I've got some letters e, h, o
Now I need to find all words that includes this letters. Like search, echo for e, h, o

I can search this way:

```<code>words = %w[hello poison world search echo]
matched = words.select do |w|
  %w[e,h,o].all?{ |l| w =~ /#{l}/ }
end
</code>```

The problem is that if letters are o, o, o, or l, b, l this search will return true for words like open or boil, but I need to search words that includes three of o or two of l and one b

upd:

```<code>leters = "abc"
words.select{ |w| w.count(letters) >= 3 }
</code>```

upd 2

Bad solution, example:

```<code>"lllllll".count("lua") #=> 5
</code>```

答:
It's probably best not to use regular expressions for this, but it can be done:

All three letters different:

```<code>/^(?=.*a)(?=.*b).*c/
</code>```

Two the same and one different:

```<code>/^(?=.*a.*a).*b/
</code>```

All three the same:

```<code>/^.*a.*a.*a/
</code>```

Body:
I've got a number of word:
hello, poison, world, search, echo ...
And I've got some letters e, h, o
Now I need to find all words that includes this letters. Like search, echo for e, h, o

I can search this way:

words = %w[hello poison world search echo]
matched = words.select do |w|
  %w[e,h,o].all?{ |l| w =~ /#{l}/ }
end

The problem is that if letters are o, o, o, or l, b, l this search will return true for words like open or boil, but I need to search words that includes three of o or two of l and one b

upd:

leters = "abc"
words.select{ |w| w.count(letters) >= 3 }

upd 2

Bad solution, example:

"lllllll".count("lua") #=> 5

Body:
It's probably best not to use regular expressions for this, but it can be done:

All three letters different:

/^(?=.*a)(?=.*b).*c/

Two the same and one different:

/^(?=.*a.*a).*b/

All three the same:

/^.*a.*a.*a/


问:
Why my php header() is not working?
My simple header() function not working.

login.php

```<code><html>
<head>
    <link rel="stylesheet" href="../css/bootstrap.css">
        <link rel="stylesheet" href="../css/style.css">
</head>
<body>
<div class="container ">
<div class="row">
    <div class="input-form">
        <h2 align="center" style="padding-top: 10px;">Log In</h2>
        <form action="logincheck.php" method="post">
        <div class="form-group">
            <label class="label1">UserName</label>
            <input name="username" type="text" class="form-control" id="" placeholder="username">
        </div>
        <div class="form-group">
            <label class="label2">Password</label>
            <input name="password" type="password" class="form-control" id="" placeholder="********">
        </div>
        <input type="submit" name="submit" class="btn btn-default" value="LOG IN">
        <?php /*
            if($errormsg != ""){
                    echo '<label class="label3 alert alert-danger">'.$errormsg.'</label>';
            } */
        ?>
        </form>
    </div>
</div>
</div>
</code>```

And my logincheck.php is

```<code><?php
    $username = $_POST['username'];
    $password = $_POST['password'];
    header("location : login.php");
?>
</code>```

And I got " The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there was an error in a CGI script.
If you think this is a server error, please contact the webmaster. "

答:
Case sensitivity issue

```<code>header("Location: login.php");
</code>```

Title: Why my php header() is not working?

Body:
My simple header() function not working.

login.php

    <link rel="stylesheet" href="../css/bootstrap.css">
        <link rel="stylesheet" href="../css/style.css">

Log In

        <form action="logincheck.php" method="post">

            UserName
            <input name="username" type="text" class="form-control" id="" placeholder="username">

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

        <input type="submit" name="submit" class="btn btn-default" value="LOG IN">
        <?php /*
            if($errormsg != ""){
                    echo ''.$errormsg.'';
            } */
        ?>
        </form>

And my logincheck.php is

<?php
    $username = $_POST['username'];
    $password = $_POST['password'];
    header("location : login.php");
?>

And I got " The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there was an error in a CGI script.
If you think this is a server error, please contact the webmaster. "

Body:
Case sensitivity issue

header("Location: login.php");


问:
PyCharm: Storing variables in memory to be able to run code from a "checkpoint"
I've been searching everywhere for an answer to this but to no avail. I want to be able to run my code and have the variables stored in memory so that I can perhaps set a "checkpoint" which I can run from in the future. The reason is that I have a fairly expensive function that takes some time to compute (as well as user input) and it would be nice if I didn't have to wait for it to finish every time I run after I change something downstream.

I'm sure a feature like this exists in PyCharm but I have no idea what it's called and the documentation isn't very clear to me at my level of experience. It would save me a lot of time if someone could point me in the right direction.

答: This feature is not implement in Pycharm (see pycharm forum) but seems implemented in Spyder.</p>


问:
Can I undo a checkout FETCH_HEAD?
I accidentally overwritten unstaged files on server by:</p>

```<code>git fetch origin [branch_name]
git checkout FETCH_HEAD -- [branch_name]
</code>```

答: Your changes are lost. To avoid these situations in the future, use git stash before making moves that you are not sure of.</p>

Title: Can I undo a checkout FETCH_HEAD?

Body:
I accidentally overwritten unstaged files on server by:

git fetch origin [branch_name]
git checkout FETCH_HEAD -- [branch_name]


问:
Android hooking of abstract class method calls using Frida
I am trying to learn Frida and have experimented with a little so far. Things have mostly worked as thankfully I could find enough examples and tutorials to help me through.
However, at this point in time, I am stuck with a very specific task at hand.

So let's say below is the Frida hook I am referring to:

```<code>Java.perform(function () {

var Activity = Java.use("myPack.myClass");

Activity.methodM1.overload('[B', 'java.lang.String').implementation = function (a, str) {

    var retval = this.methodM1(a, str);

    console.log("[*] return value4: "+retval);

    return retval;
};
});
</code>```

Now as per my understanding so far, with Java.use above, I am saying that whenever an Object of myPackage.myClass is made and if that object calls the method, methodM1, get the control to my javascript function instead and do whatever is mentioned in there.

Which does the job as expected. However, the point (of interest for the sake of this discussion) was: IF the object gets made then this would happen.

Similarly, instead of Java.use, if we were talking about Java.choose() also, the situation would have been the same. So even in that case, we are saying that IF the object gets made, then call my callback.

Now, what would happen if I am trying to hook into a method of an abstract class So let's say I am trying to hook into the method

'static getInstance(String)'
  of
  java.security.KeyPairGenerator (which is an abstract class).

This class being abstract, it's object never really gets made at all. And the method being static, it is directly called using the class name itself. So in this case, neither Java.use() nor Java.choose() will be able to help (if my understanding above is correct).

So how do I hook into the getInstance() at all in such a situation?

Here's something that I have already tried:

```<code>Java.perform(
  function()
  {
    Java.enumerateLoadedClasses(
    {
      onMatch: function(className)
      {
        if(className == "java.security.KeyPairGenerator")
        {
          var item = Java.use(className);

          console.log("the PrivateKey class was just loaded");
          item.getInstance.overload('java.lang.String').implementation = function(str)
          {
            console.log("[*] This got called ");
            var ret = item.getInstance(str);
            console.log("[*] return value4: "+retval);
            return retval;
          }
        }
      },
      onComplete:function(){}
    });
  }
);
</code>```

But this does not work. Again, my assumption here is that whenever the Object gets made and the getInstance() gets called, hook it. But here, KeyPairGenerator being an abstract class, it never really gets instantiated in the first place itself. I have also tried :

className.getInstance()

instead of

item.getInstance()

and that does not work either.

答:
Since Frida 10.1.2, early instrumentation works pretty well and can be used in your case to reach your target.

I tried your code on my device (Huwaei P8 lite \w Android 6.0). I am using latest Frida (10.1.4). As a result, using Java.enumerateLoadedClass (in your case) makes the application hang, and after a couple of seconds, frida crashes.

```<code>Error: abort was called
at u (frida/node_modules/frida-java/lib/android.js:512)
at p (java.js:2054)
at frida/node_modules/frida-java/index.js:105
at [anon] (repl1.js:28)
at frida/node_modules/frida-java/lib/vm.js:39
at y (frida/node_modules/frida-java/index.js:325)
at frida/node_modules/frida-java/index.js:305
at call (native)
at getPackageInfoNoCheck (Input:1)
[...]
</code>```

The working solution is to rely on the early instrumentation capability of Frida:

```<code>/*
Working code.
No need of Java.enumerateLoadedClasses
The following application https://github.com/obaro/SimpleKeystoreApp has been installed  on the target device for testing.

Call the current javascript script like so:
frida -U -f com.sample.foo.simplekeystoreapp -l myscript.js --no-pause
*/

function monitorKPG2()
{
    console.log("Starting early instrumentation test...");

    Java.perform(function () {
        var target = Java.use("java.security.KeyPairGenerator");

        console.log("Target = " + target);

        target.getInstance.overload("java.lang.String", "java.lang.String").implementation = function(alg, prov) {
            console.log("getInstance " + alg);

            this.getInstance(alg, prov);
        };
    });
}

console.log("Call me may be");
monitorKPG2();
</code>```

Body:
I am trying to learn Frida and have experimented with a little so far. Things have mostly worked as thankfully I could find enough examples and tutorials to help me through.
However, at this point in time, I am stuck with a very specific task at hand.

So let's say below is the Frida hook I am referring to:

Java.perform(function () {

var Activity = Java.use("myPack.myClass");

Activity.methodM1.overload('[B', 'java.lang.String').implementation = function (a, str) {

    var retval = this.methodM1(a, str);

    console.log("[*] return value4: "+retval);

    return retval;
};
});

Now as per my understanding so far, with Java.use above, I am saying that whenever an Object of myPackage.myClass is made and if that object calls the method, methodM1, get the control to my javascript function instead and do whatever is mentioned in there.

Which does the job as expected. However, the point (of interest for the sake of this discussion) was: IF the object gets made then this would happen.

Similarly, instead of Java.use, if we were talking about Java.choose() also, the situation would have been the same. So even in that case, we are saying that IF the object gets made, then call my callback.

Now, what would happen if I am trying to hook into a method of an abstract class So let's say I am trying to hook into the method

'static getInstance(String)'
  of
  java.security.KeyPairGenerator (which is an abstract class).

This class being abstract, it's object never really gets made at all. And the method being static, it is directly called using the class name itself. So in this case, neither Java.use() nor Java.choose() will be able to help (if my understanding above is correct).

So how do I hook into the getInstance() at all in such a situation?

Here's something that I have already tried:

Java.perform(
  function()
  {
    Java.enumerateLoadedClasses(
    {
      onMatch: function(className)
      {
        if(className == "java.security.KeyPairGenerator")
        {
          var item = Java.use(className);

          console.log("the PrivateKey class was just loaded");
          item.getInstance.overload('java.lang.String').implementation = function(str)
          {
            console.log("[*] This got called ");
            var ret = item.getInstance(str);
            console.log("[*] return value4: "+retval);
            return retval;
          }
        }
      },
      onComplete:function(){}
    });
  }
);

But this does not work. Again, my assumption here is that whenever the Object gets made and the getInstance() gets called, hook it. But here, KeyPairGenerator being an abstract class, it never really gets instantiated in the first place itself. I have also tried :

className.getInstance()

instead of

item.getInstance()

and that does not work either.

Body:
Since Frida 10.1.2, early instrumentation works pretty well and can be used in your case to reach your target.

I tried your code on my device (Huwaei P8 lite \w Android 6.0). I am using latest Frida (10.1.4). As a result, using Java.enumerateLoadedClass (in your case) makes the application hang, and after a couple of seconds, frida crashes.

Error: abort was called
at u (frida/node_modules/frida-java/lib/android.js:512)
at p (java.js:2054)
at frida/node_modules/frida-java/index.js:105
at [anon] (repl1.js:28)
at frida/node_modules/frida-java/lib/vm.js:39
at y (frida/node_modules/frida-java/index.js:325)
at frida/node_modules/frida-java/index.js:305
at call (native)
at getPackageInfoNoCheck (Input:1)
[...]

The working solution is to rely on the early instrumentation capability of Frida:

/*
Working code.
No need of Java.enumerateLoadedClasses
The following application https://github.com/obaro/SimpleKeystoreApp has been installed  on the target device for testing.

Call the current javascript script like so:
frida -U -f com.sample.foo.simplekeystoreapp -l myscript.js --no-pause
*/

function monitorKPG2()
{
    console.log("Starting early instrumentation test...");

    Java.perform(function () {
        var target = Java.use("java.security.KeyPairGenerator");

        console.log("Target = " + target);

        target.getInstance.overload("java.lang.String", "java.lang.String").implementation = function(alg, prov) {
            console.log("getInstance " + alg);

            this.getInstance(alg, prov);
        };
    });
}

console.log("Call me may be");
monitorKPG2();


问:
Docker: Docker-compose ruby + postgres - PG::ConnectionBadcould not connect to server
I created Dockerfile to ruby from official docker-compose website. I used docker compose to integrate this with Postgres. When docker-compose up, then PostgreSQL starts but I cannot connect to this. The main problem is in ruby database config because I can't change to listen to another host and set the default user. I don't know how to connect these two containers without changing the ruby database config.

Dockerfile

```<code>FROM ruby:2.3.4
RUN apt-get update -qq && apt-get install -y build-essential libpq-dev nodejs
RUN mkdir /myapp
WORKDIR /myapp
ADD Gemfile /myapp/Gemfile
ADD Gemfile.lock /myapp/Gemfile.lock
RUN bundle install
ADD . /myapp
</code>```

Docker-compose

```<code>version: '3'
services:
  db:
    image: postgres:9.6
    ports:
      - "5432:5432"
  web:
    build: .
    ports:
      - "4000:4000"
    depends_on:
      - db
</code>```

Ruby database.yml

```<code>default: &default
  adapter: postgresql
  encoding: unicode
  pool: 5

development:
  <<: *default
  database: project_development
</code>```

If i run inside web conatiner "bundle exec rake db:create I get error:

```<code>psql: could not connect to server: No such file or directory
Is the server running locally and accepting
connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?
</code>```

I don't know what env set that will connect together.

答:
You didn't specify database host in your database.yml. Set it to db or just try this database.yml

```<code>development: &default
  adapter: postgresql
  encoding: unicode
  database: project_development
  pool: 5
  username: postgres
  password:
  host: db

test:
  <<: *default
  database: project_test
</code>```

Body:
I created Dockerfile to ruby from official docker-compose website. I used docker compose to integrate this with Postgres. When docker-compose up, then PostgreSQL starts but I cannot connect to this. The main problem is in ruby database config because I can't change to listen to another host and set the default user. I don't know how to connect these two containers without changing the ruby database config.

Dockerfile

FROM ruby:2.3.4
RUN apt-get update -qq && apt-get install -y build-essential libpq-dev nodejs
RUN mkdir /myapp
WORKDIR /myapp
ADD Gemfile /myapp/Gemfile
ADD Gemfile.lock /myapp/Gemfile.lock
RUN bundle install
ADD . /myapp

Docker-compose

version: '3'
services:
  db:
    image: postgres:9.6
    ports:
      - "5432:5432"
  web:
    build: .
    ports:
      - "4000:4000"
    depends_on:
      - db

Ruby database.yml

default: &default
  adapter: postgresql
  encoding: unicode
  pool: 5

development:
  <<: *default
  database: project_development

If i run inside web conatiner "bundle exec rake db:create I get error:

psql: could not connect to server: No such file or directory
Is the server running locally and accepting
connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?

I don't know what env set that will connect together.

Body:
You didn't specify database host in your database.yml. Set it to db or just try this database.yml

development: &default
  adapter: postgresql
  encoding: unicode
  database: project_development
  pool: 5
  username: postgres
  password:
  host: db

test:
  <<: *default
  database: project_test