问:
cant get the uitextview height dynamically correct
I am having issue in getting the correct size of uitextview.In my application i am fetching the data from webservice  and i set the height of uitextview as per the data from webservice .But whenever there is space in first 35 letters(frame of my textview is (20,0,255,2000)). then the hjeight calculated is always one line less then correct  height and even the uitext view starts to print the line after space in the new line (may be word is big thats why ??).

So i am getting the wrong text view height.

The text view apears somwethibng like this :

firstword
spacesspacesspacesspaces
spacesspacesspacesspaces
spacesspacesspacesspaces
spacesspacesspacesspaces
spacesspacesspacesspaces

When i enter text which is say without spaces it gives me correct height suppose say the data is  "ttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttt"
Then in the above scenerio Cgsize will generate proper result for me .

Here i am not using UILabel is because i want link detection thats why .
If anyone has anyother suggestions it is highly welcomed.

Regards
Mrugen

答:
You can measure the height of the text with this function and set your frame according to the returned height.

```<code>   -(CGSize)sizeOfText:(NSString *)textToMesure widthOfTextView:(CGFloat)width withFont:(UIFont*)font
    {
        CGSize ts = [textToMesure sizeWithFont:font constrainedToSize:CGSizeMake(width-20.0, FLT_MAX) lineBreakMode:UILineBreakModeWordWrap];
        return ts;
    }
</code>```

you use it like that:

```<code> CGSize size =   [self sizeOfText:@"the string you want to present" widthOfTextView:255 withFont:fontYouAreUsing];
</code>```

And then you pass it to the text view:

```<code>   textView.frame = CGRectMake(20,0,255,size.height);
</code>```

Good luck

shani

Body:
You can measure the height of the text with this function and set your frame according to the returned height.

   -(CGSize)sizeOfText:(NSString *)textToMesure widthOfTextView:(CGFloat)width withFont:(UIFont*)font
    {
        CGSize ts = [textToMesure sizeWithFont:font constrainedToSize:CGSizeMake(width-20.0, FLT_MAX) lineBreakMode:UILineBreakModeWordWrap];
        return ts;
    }

you use it like that:

 CGSize size =   [self sizeOfText:@"the string you want to present" widthOfTextView:255 withFont:fontYouAreUsing];

And then you pass it to the text view:

   textView.frame = CGRectMake(20,0,255,size.height);

Good luck

shani


来源: stackexchange

问:
I have created a custom post type. single page for that custom post showing blank page
I have created a custom post type. Single posts for that custom post type is not working. showing white page but html are loading properly. Here is the url https://bestswiss.ch/vendorpartner/formforum</p>

```<code>   ////code

 $labels = array(
            'name'               => __( 'Partner' ),
            'singular_name'      => __( 'vendorpartner' ),
            'add_new'            => __( 'Add New vendorpartner' ),
            'add_new_item'       => __( 'Add New vendorpartner' ),
            'edit_item'          => __( 'Edit vendorpartner' ),
            'new_item'           => __( 'Add New vendorpartner' ),
            'view_item'          => __( 'View vendorpartner' ),
            'search_items'       => __( 'Search vendorpartner' ),
            'not_found'          => __( 'No events found' ),
            'not_found_in_trash' => __( 'No events found in trash' )
        );
        $supports = array(
            'title',
            'editor',
            'thumbnail',
            'comments',
            'revisions',
            'page-attributes'
        );
        $args = array(
            'labels'               => $labels,
            'supports'             => $supports,
            'public'               => true,
            'capability_type'      => 'post',
            'rewrite'              => array( 'slug' => 'vendorpartner' ),
            'has_archive'          => true,
            'menu_position'        => 30,
            'menu_icon'            => 'dashicons-calendar-alt',
            'register_meta_box_cb' => 'wpt_add_event_metaboxes',
        );
        register_post_type( 'vendorpartner', $args );
</code>```

答:
create single-vendorpartner.php and paste the following codes

<?php get_header('');?>

<?php while ( have_posts() ) : the_post(); ?>

      <?php the_title(); ?>

      <?php the_content(); ?>

<?php endwhile ?>

<?php get_footer() ?>```

change permalinks, and see the changes.

ContentLicense: CC BY-SA 4.0

Body:
I have created a custom post type. Single posts for that custom post type is not working. showing white page but html are loading properly. Here is the url https://bestswiss.ch/vendorpartner/formforum

   ////code

 $labels = array(
            'name'               => __( 'Partner' ),
            'singular_name'      => __( 'vendorpartner' ),
            'add_new'            => __( 'Add New vendorpartner' ),
            'add_new_item'       => __( 'Add New vendorpartner' ),
            'edit_item'          => __( 'Edit vendorpartner' ),
            'new_item'           => __( 'Add New vendorpartner' ),
            'view_item'          => __( 'View vendorpartner' ),
            'search_items'       => __( 'Search vendorpartner' ),
            'not_found'          => __( 'No events found' ),
            'not_found_in_trash' => __( 'No events found in trash' )
        );
        $supports = array(
            'title',
            'editor',
            'thumbnail',
            'comments',
            'revisions',
            'page-attributes'
        );
        $args = array(
            'labels'               => $labels,
            'supports'             => $supports,
            'public'               => true,
            'capability_type'      => 'post',
            'rewrite'              => array( 'slug' => 'vendorpartner' ),
            'has_archive'          => true,
            'menu_position'        => 30,
            'menu_icon'            => 'dashicons-calendar-alt',
            'register_meta_box_cb' => 'wpt_add_event_metaboxes',
        );
        register_post_type( 'vendorpartner', $args );

Body:
create single-vendorpartner.php and paste the following codes

<?php get_header('');?>
<!--start container-->
<?php while ( have_posts() ) : the_post(); ?>
<div class="container">
  <div class="row">
    <div class="col-12 col-sm-12 col-md-12">

      <?php the_title(); ?>

      <?php the_content(); ?>

    </div>
  </div>
</div>
<?php endwhile ?>
<!--end container-->
<?php get_footer() ?>

change permalinks, and see the changes.


问:
Regex for multi-line data in MySQL column
I have a column which has XML in it and I want to use regex to list ids based on a condition.

Part of my XML data which copied to outfile :

```<code>  <definitions>^M\
    <definition id=
</code>```

I want to list a column based on the xmldata which has <definitions> followed by <definition id="1"

So far I have tried different combinations of regex but no success

where <col> REGEXP '.*<definitions>\r.\s+<definition id="1"'

答:
Note that REGEXP can match anywhere inside a string, not necessarily at the start (unlike LIKE), thus you need no .* at the start.

MySQL versions before 8.x did not support Perl-like shorthand classes, and \s is invalid there. In MySQL 8.x, the ICU regex library supports \s.

You may use in any MySQL:

```<code>where col REGEXP '<definitions>[[:space:]]+<definition id="1"'
</code>```

Or, if the whitespace can be missing between the elements:

```<code>where col REGEXP '<definitions>[[:space:]]*<definition id="1"'
</code>```

The [[:space:]] bracket expression containing [:space:] POSIX character class matches any whitespace chars, and + mathces 1 or more repetitions of the chars while * matches 0 or more of them.

Body:
I have a column which has XML in it and I want to use regex to list ids based on a condition.

Part of my XML data which copied to outfile :

  <definitions>^M\
    <definition id=

I want to list a column based on the xmldata which has <definitions> followed by <definition id="1"

So far I have tried different combinations of regex but no success

where <col> REGEXP '.*<definitions>\r.\s+<definition id="1"'

Body:
Note that REGEXP can match anywhere inside a string, not necessarily at the start (unlike LIKE), thus you need no .* at the start.

MySQL versions before 8.x did not support Perl-like shorthand classes, and \s is invalid there. In MySQL 8.x, the ICU regex library supports \s.

You may use in any MySQL:

where col REGEXP '<definitions>[[:space:]]+<definition id="1"'

Or, if the whitespace can be missing between the elements:

where col REGEXP '<definitions>[[:space:]]*<definition id="1"'

The [[:space:]] bracket expression containing [:space:] POSIX character class matches any whitespace chars, and + mathces 1 or more repetitions of the chars while * matches 0 or more of them.


问:
How to escape double quotes for Primefaces SelectOneMenu in Application level?
Using PrimeFaces, when the content of itemLabel of a p:selectOneMenu has the char double quote ("), the selectOneMenu stop working (can't select the item).
For example, in the code below is not possible to select: Item "2"

Is there a way to escape or replace the double quotes in every selectOneMenu from the entire application?

Maybe using a tag decorator or a tag handler?

@Named(value = "bb")
@ViewScoped
@Getter @Setter
public class BB implements Serializable {

    List<String> items;
    String selectedItem;

    @PostConstruct
    public void init() {
        items = new ArrayList<>();
        items.add("Item 1");
        items.add("Item \"2\""); // <= note the double quotes here.
        items.add("Item 3");
    }

    public void logSelected() {
        System.out.println(selectedItem);
    }
}
```

```    <h:form>

            <f:selectItems value="#{bb.items}"/>

    </h:form>

```

<p>When I try to select 'Item "2"', the following error is shown on console log:</p>

<pre class="lang-html prettyprint-override"><code>Uncaught Error: Syntax error, unrecognized expression: [data-label="Item "2""]
    at Function.ga.error (eNptjUsOgzAMRE9E2XMbEwwkcmxjJ6qQenh-i6qF1UhvnmbUYsYRAnqXloq2tle8kn_02wUxvKGswsjF_4qfnUapTpFPp1KJGRqCVWrpkrcMLB5MiNAeBX9HPX9n8HmAAgecSHqgnW7lbUr_.js.xhtml?ln=omnifaces.combined&v=1558274343370:2)
    at ga.tokenize (eNptjUsOgzAMRE9E2XMbEwwkcmxjJ6qQenh-i6qF1UhvnmbUYsYRAnqXloq2tle8kn_02wUxvKGswsjF_4qfnUapTpFPp1KJGRqCVWrpkrcMLB5MiNAeBX9HPX9n8HmAAgecSHqgnW7lbUr_.js.xhtml?ln=omnifaces.combined&v=1558274343370:2)
    at ga.compile (eNptjUsOgzAMRE9E2XMbEwwkcmxjJ6qQenh-i6qF1UhvnmbUYsYRAnqXloq2tle8kn_02wUxvKGswsjF_4qfnUapTpFPp1KJGRqCVWrpkrcMLB5MiNAeBX9HPX9n8HmAAgecSHqgnW7lbUr_.js.xhtml?ln=omnifaces.combined&v=1558274343370:2)
    at ga.select (eNptjUsOgzAMRE9E2XMbEwwkcmxjJ6qQenh-i6qF1UhvnmbUYsYRAnqXloq2tle8kn_02wUxvKGswsjF_4qfnUapTpFPp1KJGRqCVWrpkrcMLB5MiNAeBX9HPX9n8HmAAgecSHqgnW7lbUr_.js.xhtml?ln=omnifaces.combined&v=1558274343370:2)
    at ga (eNptjUsOgzAMRE9E2XMbEwwkcmxjJ6qQenh-i6qF1UhvnmbUYsYRAnqXloq2tle8kn_02wUxvKGswsjF_4qfnUapTpFPp1KJGRqCVWrpkrcMLB5MiNAeBX9HPX9n8HmAAgecSHqgnW7lbUr_.js.xhtml?ln=omnifaces.combined&v=1558274343370:2)
    at Function.ga.matches (eNptjUsOgzAMRE9E2XMbEwwkcmxjJ6qQenh-i6qF1UhvnmbUYsYRAnqXloq2tle8kn_02wUxvKGswsjF_4qfnUapTpFPp1KJGRqCVWrpkrcMLB5MiNAeBX9HPX9n8HmAAgecSHqgnW7lbUr_.js.xhtml?ln=omnifaces.combined&v=1558274343370:2)
    at Function.r.filter (eNptjUsOgzAMRE9E2XMbEwwkcmxjJ6qQenh-i6qF1UhvnmbUYsYRAnqXloq2tle8kn_02wUxvKGswsjF_4qfnUapTpFPp1KJGRqCVWrpkrcMLB5MiNAeBX9HPX9n8HmAAgecSHqgnW7lbUr_.js.xhtml?ln=omnifaces.combined&v=1558274343370:2)
    at E (eNptjUsOgzAMRE9E2XMbEwwkcmxjJ6qQenh-i6qF1UhvnmbUYsYRAnqXloq2tle8kn_02wUxvKGswsjF_4qfnUapTpFPp1KJGRqCVWrpkrcMLB5MiNAeBX9HPX9n8HmAAgecSHqgnW7lbUr_.js.xhtml?ln=omnifaces.combined&v=1558274343370:2)
    at r.fn.init.filter (eNptjUsOgzAMRE9E2XMbEwwkcmxjJ6qQenh-i6qF1UhvnmbUYsYRAnqXloq2tle8kn_02wUxvKGswsjF_4qfnUapTpFPp1KJGRqCVWrpkrcMLB5MiNAeBX9HPX9n8HmAAgecSHqgnW7lbUr_.js.xhtml?ln=omnifaces.combined&v=1558274343370:2)
    at c.setLabel (eNptjUsOgzAMRE9E2XMbEwwkcmxjJ6qQenh-i6qF1UhvnmbUYsYRAnqXloq2tle8kn_02wUxvKGswsjF_4qfnUapTpFPp1KJGRqCVWrpkrcMLB5MiNAeBX9HPX9n8HmAAgecSHqgnW7lbUr_.js.xhtml?ln=omnifaces.combined&v=1558274343370:38)
</code>```

答:
Verified as fixed in PrimeFaces 7.0.

However, it may also be fixed in 6.2.X depending on which fix was applied.

6.2.9: https://github.com/primefaces/primefaces/issues/3982

7.0: https://github.com/primefaces/primefaces/issues/3466

It appears this isse was reintroduced in PrimeFaces 10.0.0 and fixed in version 10.0.9:

10.0: https://github.com/primefaces/primefaces/issues/7878

Body:
Using PrimeFaces, when the content of itemLabel of a p:selectOneMenu has the char double quote ("), the selectOneMenu stop working (can't select the item).
For example, in the code below is not possible to select: Item "2"

Is there a way to escape or replace the double quotes in every selectOneMenu from the entire application?

Maybe using a tag decorator or a tag handler?

@Named(value = "bb")
@ViewScoped
@Getter @Setter
public class BB implements Serializable {

    List<String> items;
    String selectedItem;

    @PostConstruct
    public void init() {
        items = new ArrayList<>();
        items.add("Item 1");
        items.add("Item \"2\""); // <= note the double quotes here.
        items.add("Item 3");
    }

    public void logSelected() {
        System.out.println(selectedItem);
    }
}

    <h:form>

            <f:selectItems value="#{bb.items}"/>

    </h:form>

When I try to select 'Item "2"', the following error is shown on console log:

Uncaught Error: Syntax error, unrecognized expression: [data-label="Item "2""]
    at Function.ga.error (eNptjUsOgzAMRE9E2XMbEwwkcmxjJ6qQenh-i6qF1UhvnmbUYsYRAnqXloq2tle8kn_02wUxvKGswsjF_4qfnUapTpFPp1KJGRqCVWrpkrcMLB5MiNAeBX9HPX9n8HmAAgecSHqgnW7lbUr_.js.xhtml?ln=omnifaces.combined&v=1558274343370:2)
    at ga.tokenize (eNptjUsOgzAMRE9E2XMbEwwkcmxjJ6qQenh-i6qF1UhvnmbUYsYRAnqXloq2tle8kn_02wUxvKGswsjF_4qfnUapTpFPp1KJGRqCVWrpkrcMLB5MiNAeBX9HPX9n8HmAAgecSHqgnW7lbUr_.js.xhtml?ln=omnifaces.combined&v=1558274343370:2)
    at ga.compile (eNptjUsOgzAMRE9E2XMbEwwkcmxjJ6qQenh-i6qF1UhvnmbUYsYRAnqXloq2tle8kn_02wUxvKGswsjF_4qfnUapTpFPp1KJGRqCVWrpkrcMLB5MiNAeBX9HPX9n8HmAAgecSHqgnW7lbUr_.js.xhtml?ln=omnifaces.combined&v=1558274343370:2)
    at ga.select (eNptjUsOgzAMRE9E2XMbEwwkcmxjJ6qQenh-i6qF1UhvnmbUYsYRAnqXloq2tle8kn_02wUxvKGswsjF_4qfnUapTpFPp1KJGRqCVWrpkrcMLB5MiNAeBX9HPX9n8HmAAgecSHqgnW7lbUr_.js.xhtml?ln=omnifaces.combined&v=1558274343370:2)
    at ga (eNptjUsOgzAMRE9E2XMbEwwkcmxjJ6qQenh-i6qF1UhvnmbUYsYRAnqXloq2tle8kn_02wUxvKGswsjF_4qfnUapTpFPp1KJGRqCVWrpkrcMLB5MiNAeBX9HPX9n8HmAAgecSHqgnW7lbUr_.js.xhtml?ln=omnifaces.combined&v=1558274343370:2)
    at Function.ga.matches (eNptjUsOgzAMRE9E2XMbEwwkcmxjJ6qQenh-i6qF1UhvnmbUYsYRAnqXloq2tle8kn_02wUxvKGswsjF_4qfnUapTpFPp1KJGRqCVWrpkrcMLB5MiNAeBX9HPX9n8HmAAgecSHqgnW7lbUr_.js.xhtml?ln=omnifaces.combined&v=1558274343370:2)
    at Function.r.filter (eNptjUsOgzAMRE9E2XMbEwwkcmxjJ6qQenh-i6qF1UhvnmbUYsYRAnqXloq2tle8kn_02wUxvKGswsjF_4qfnUapTpFPp1KJGRqCVWrpkrcMLB5MiNAeBX9HPX9n8HmAAgecSHqgnW7lbUr_.js.xhtml?ln=omnifaces.combined&v=1558274343370:2)
    at E (eNptjUsOgzAMRE9E2XMbEwwkcmxjJ6qQenh-i6qF1UhvnmbUYsYRAnqXloq2tle8kn_02wUxvKGswsjF_4qfnUapTpFPp1KJGRqCVWrpkrcMLB5MiNAeBX9HPX9n8HmAAgecSHqgnW7lbUr_.js.xhtml?ln=omnifaces.combined&v=1558274343370:2)
    at r.fn.init.filter (eNptjUsOgzAMRE9E2XMbEwwkcmxjJ6qQenh-i6qF1UhvnmbUYsYRAnqXloq2tle8kn_02wUxvKGswsjF_4qfnUapTpFPp1KJGRqCVWrpkrcMLB5MiNAeBX9HPX9n8HmAAgecSHqgnW7lbUr_.js.xhtml?ln=omnifaces.combined&v=1558274343370:2)
    at c.setLabel (eNptjUsOgzAMRE9E2XMbEwwkcmxjJ6qQenh-i6qF1UhvnmbUYsYRAnqXloq2tle8kn_02wUxvKGswsjF_4qfnUapTpFPp1KJGRqCVWrpkrcMLB5MiNAeBX9HPX9n8HmAAgecSHqgnW7lbUr_.js.xhtml?ln=omnifaces.combined&v=1558274343370:38)


问:
I can't connect a java application with a python application using MQTT
I have created a python application that posts messages every 3 seconds. This message is sent to an MQTT mosquitto broker. On the other hand, I have a Java application that is subscribed to the topic of the message.
When I launch the two applications, the Java application never receives anything.

The mqtt broker shown in the code is not correct, I modified it for confidentiality.

However, when I use mosquitto to publish a message the Java application receives a message.

```<code>import paho.mqtt.client as mqtt
import time
import logging

# Enable logging
logging.basicConfig(
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    level=logging.INFO)

logger = logging.getLogger(__name__)

broker='100.100.100.100'
port=1883

def on_log(client, userdata, level, buf):
    logger.info(buf)

def on_connect(client, userdata, flags, rc):
    if rc==0:
        client.connected_flag=True # set flag
        logger.info("Conexion establecida")
    else:
        logger.info("Conexion no establecida code = "+ str(rc))
        client.loop_stop()

def on_disconnect(client, userdata, rc):
    logger.info("Se desconecta el publicador \n")

def on_publish(client, userdata, mid):
    logger.info("Se publica un dato, mid "+ str(mid))

mqtt.Client.connected_flag=False #Crea un flag en la clase

client = mqtt.Client("jmacias_pub")     #Se crea una nueva instancia
client.on_log = on_log
client.on_connect = on_connect
client.on_disconnect = on_disconnect
client.on_publish = on_publish

client.connect(host=broker, port=port)
client.loop_start()

while not client.connected_flag: #wait in loop
    logger.info("In wait loop")
    time.sleep(1)

while True:
    time.sleep(3)
    logger.info('Publicando')
    ret = client.publish('rtu/delete','0|[192.168.1.1-866e]', 0)
    ret = client.publish('rtu/delete','0|[192.168.1.2-866e]', 1)
    ret = client.publish('rtu/delete','0|[192.168.1.3-866e]', 2)

client.loop_stop()
client.disconnect()
</code>```

```<code>package com.speedforge.mqtt;

import java.util.concurrent.TimeUnit;

import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

/**
 * A sample application that demonstrates how to use the Paho MQTT v3.1 Client blocking API.
 */
public class Subscriber implements MqttCallback {
    //Subscribe topics
    static final String TOPIC_ALL="/rtu/delete";
    //Publish topics
    static final String TOPIC_DELETE="/rtu/delete";
    static final String TOPIC_INFO="/rtu/info";
    static final String TOPIC_DESPLOY="/rtu/desploy";

    private final int qos = 2;
    private static MqttClient client;
    //private static MqttClient replay_client;

    public Subscriber(String broker) throws MqttException {
        String host = String.format(broker);
        String clientId = "MQTT-Java-Example";

        MqttConnectOptions conOpt = new MqttConnectOptions();
        conOpt.setCleanSession(true);

        Subscriber.client = new MqttClient(host, clientId, new MemoryPersistence());
        Subscriber.client.setCallback(this);
        Subscriber.client.connect(conOpt);
        Subscriber.client.subscribe(Subscriber.TOPIC_ALL, qos);
    }

    /*
    public void sendMessage(String payload) throws MqttException {
        MqttMessage message = new MqttMessage(payload.getBytes());
        message.setQos(qos);
        this.client.publish(this.topic, message); // Blocking publish
    }
    */

    /**
     * @see MqttCallback#connectionLost(Throwable)
     */
    public void connectionLost(Throwable cause) {
        System.out.println("Connection lost because: " + cause);
        System.exit(1);
    }

    /**
     * @see MqttCallback#deliveryComplete(IMqttDeliveryToken)
     */
    public void deliveryComplete(IMqttDeliveryToken token) {

    }

    /**
     * @see MqttCallback#messageArrived(String, MqttMessage)
     */
    public void messageArrived(String topic, MqttMessage message) throws MqttException {
        System.out.println("Se recibe un nuevo mensaje del topic: "+ topic);
        String msg = new String(message.getPayload());
        System.out.println("Payload: " + msg);
    }

    public static void main(String[] args) throws MqttException {
        String broker       = "tcp://100.100.100.100:1883";
        System.out.println("Comienza la subscripcion");
        Subscriber s = new Subscriber(broker);

        try {
            TimeUnit.SECONDS.sleep(60);
            //Thread.sleep(10000);
        } catch (InterruptedException e) {
            System.out.println("Se obtiene una excepcion del temporizador "+e);
        }

        Subscriber.client.disconnect();
        Subscriber.client.close();
        System.out.println("Finaliza");
    }
}
</code>```

I have to get the data sent by the python application to the java application

答:
Solved, the topic that used in python was

```<code>rtu / delete
</code>```

and in java

```<code>/ rtu / delete
</code>```

Simply a aissing character '/'

Body:
I have created a python application that posts messages every 3 seconds. This message is sent to an MQTT mosquitto broker. On the other hand, I have a Java application that is subscribed to the topic of the message.
When I launch the two applications, the Java application never receives anything.

The mqtt broker shown in the code is not correct, I modified it for confidentiality.

However, when I use mosquitto to publish a message the Java application receives a message.

import paho.mqtt.client as mqtt
import time
import logging

# Enable logging
logging.basicConfig(
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    level=logging.INFO)

logger = logging.getLogger(__name__)

broker='100.100.100.100'
port=1883

def on_log(client, userdata, level, buf):
    logger.info(buf)

def on_connect(client, userdata, flags, rc):
    if rc==0:
        client.connected_flag=True # set flag
        logger.info("Conexion establecida")
    else:
        logger.info("Conexion no establecida code = "+ str(rc))
        client.loop_stop()

def on_disconnect(client, userdata, rc):
    logger.info("Se desconecta el publicador \n")

def on_publish(client, userdata, mid):
    logger.info("Se publica un dato, mid "+ str(mid))

mqtt.Client.connected_flag=False #Crea un flag en la clase

client = mqtt.Client("jmacias_pub")     #Se crea una nueva instancia
client.on_log = on_log
client.on_connect = on_connect
client.on_disconnect = on_disconnect
client.on_publish = on_publish

client.connect(host=broker, port=port)
client.loop_start()

while not client.connected_flag: #wait in loop
    logger.info("In wait loop")
    time.sleep(1)

while True:
    time.sleep(3)
    logger.info('Publicando')
    ret = client.publish('rtu/delete','0|[192.168.1.1-866e]', 0)
    ret = client.publish('rtu/delete','0|[192.168.1.2-866e]', 1)
    ret = client.publish('rtu/delete','0|[192.168.1.3-866e]', 2)

client.loop_stop()
client.disconnect()

package com.speedforge.mqtt;

import java.util.concurrent.TimeUnit;

import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

/**
 * A sample application that demonstrates how to use the Paho MQTT v3.1 Client blocking API.
 */
public class Subscriber implements MqttCallback {
    //Subscribe topics
    static final String TOPIC_ALL="/rtu/delete";
    //Publish topics
    static final String TOPIC_DELETE="/rtu/delete";
    static final String TOPIC_INFO="/rtu/info";
    static final String TOPIC_DESPLOY="/rtu/desploy";

    private final int qos = 2;
    private static MqttClient client;
    //private static MqttClient replay_client;

    public Subscriber(String broker) throws MqttException {
        String host = String.format(broker);
        String clientId = "MQTT-Java-Example";

        MqttConnectOptions conOpt = new MqttConnectOptions();
        conOpt.setCleanSession(true);

        Subscriber.client = new MqttClient(host, clientId, new MemoryPersistence());
        Subscriber.client.setCallback(this);
        Subscriber.client.connect(conOpt);
        Subscriber.client.subscribe(Subscriber.TOPIC_ALL, qos);
    }

    /*
    public void sendMessage(String payload) throws MqttException {
        MqttMessage message = new MqttMessage(payload.getBytes());
        message.setQos(qos);
        this.client.publish(this.topic, message); // Blocking publish
    }
    */

    /**
     * @see MqttCallback#connectionLost(Throwable)
     */
    public void connectionLost(Throwable cause) {
        System.out.println("Connection lost because: " + cause);
        System.exit(1);
    }

    /**
     * @see MqttCallback#deliveryComplete(IMqttDeliveryToken)
     */
    public void deliveryComplete(IMqttDeliveryToken token) {

    }

    /**
     * @see MqttCallback#messageArrived(String, MqttMessage)
     */
    public void messageArrived(String topic, MqttMessage message) throws MqttException {
        System.out.println("Se recibe un nuevo mensaje del topic: "+ topic);
        String msg = new String(message.getPayload());
        System.out.println("Payload: " + msg);
    }

    public static void main(String[] args) throws MqttException {
        String broker       = "tcp://100.100.100.100:1883";
        System.out.println("Comienza la subscripcion");
        Subscriber s = new Subscriber(broker);

        try {
            TimeUnit.SECONDS.sleep(60);
            //Thread.sleep(10000);
        } catch (InterruptedException e) {
            System.out.println("Se obtiene una excepcion del temporizador "+e);
        }

        Subscriber.client.disconnect();
        Subscriber.client.close();
        System.out.println("Finaliza");
    }
}

I have to get the data sent by the python application to the java application

Body:
Solved, the topic that used in python was

rtu / delete

and in java

/ rtu / delete

Simply a aissing character '/'


问:
Ignore Git commits when pull. Skip commits and continue from latest commit
I pushed the code twice on my repo and pulled it on the server, It had some issues so I had to go back and hard reset to a previous commit. Can I only get changes from last commit ?

Command I used to go back to commit 'C'

git reset --hard C

Visual representation:

commits on repo:

A-B-C-D-E-F

git on server side:

A-B-C'

Locally I only want to push some changes that are in commit 'F'. Now i want to pull changes only from the commit 'F' and skip 'D,E'. On server it tells me I am three commits behind and when I pull it gets files from all the commits. I only want files updated in 'F' commit or any other latest commit.

(Sorry for bad english)

答: To pull changes from F git cherry-pick origin/F then you need to push out your new changes. git push -f origin. This will remove D and E from your branch on the server side.


问:
Cannot find Chrome binary when executing a selenium (testng) test in jenkins on windows 7
I have a basic login test with selenium and testng. When executed from eclipse, it works as expected and invoke Google Chrome. If executed from TESTNG command line, it works fine too.

This is my @Before:

```<code>@BeforeMethod
public void setUp() throws Exception {
 File file = new File("C:/Selenium-driver/chromedriver.exe");
 System.setProperty("webdriver.chrome.driver", file.getAbsolutePath());
 driver = new ChromeDriver();
 driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
 }
</code>```

However, if I execute the same test thru Jenkins it says:

```<code>Building in workspace C:\EclipsePortable\Data\workspace\GS_TESTNG
[G_TESTNG] $ cmd /c call C:\Windows\TEMP\hudson9049518275115936054.bat

C:\EclipsePortable\Data\workspace\G_TESTNG>_test_login_cmd.bat

C:\EclipsePortable\Data\workspace\G_TESTNG>cd C:\EclipsePortable\Data\workspace\G_TESTNG

C:\EclipsePortable\Data\workspace\G_TESTNG>java -cp C:\EclipsePortable\Data\workspace\G_TESTNG\lib\*;C:\EclipsePortable\Data\workspace\G_TESTNG\bin org.testng.TestNG testng.xml
...
... TestNG 6.9.9 by Cédric Beust (cedric@beust.com)
...

[TestNG] Running:
  C:\EclipsePortable\Data\workspace\G_TESTNG\testng.xml

Starting ChromeDriver 2.26.436362 (5476ec6bf7ccbada1734a0cdec7d570bb042aa30) on port 36257
Only local connections are allowed.
FAILED CONFIGURATION: @BeforeMethod setUp
org.openqa.selenium.WebDriverException: unknown error: cannot find Chrome binary
  (Driver info: chromedriver=2.26.436362 (5476ec6bf7ccbada1734a0cdec7d570bb042aa30),platform=Windows NT 6.1.7601 SP1 x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 664 milliseconds
Build info: version: '2.51.0', revision: '1af067d', time: '2016-02-05 19:15:17'
System info: host: 'NMTLA12810', ip: '192.168.0.179', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0_102'
Driver info: org.openqa.selenium.chrome.ChromeDriver
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
        at java.lang.reflect.Constructor.newInstance(Unknown Source)
        at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:206)
        at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:158)
        at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:678)
        at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:249)
        at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:131)
        at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:144)
        at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:170)
        at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:159)
        at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:116)
        at com.test.TestA.setUp(TestA.java:33)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
        at java.lang.reflect.Method.invoke(Unknown Source)
        at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:85)
        at org.testng.internal.Invoker.invokeConfigurationMethod(Invoker.java:510)
        at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:211)
        at org.testng.internal.Invoker.invokeMethod(Invoker.java:585)
        at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:816)
        at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1124)
        at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:125)
        at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:108)
        at org.testng.TestRunner.privateRun(TestRunner.java:774)
        at org.testng.TestRunner.run(TestRunner.java:624)
        at org.testng.SuiteRunner.runTest(SuiteRunner.java:359)
        at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:354)
        at org.testng.SuiteRunner.privateRun(SuiteRunner.java:312)
        at org.testng.SuiteRunner.run(SuiteRunner.java:261)
        at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
        at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
        at org.testng.TestNG.runSuitesSequentially(TestNG.java:1215)
        at org.testng.TestNG.runSuitesLocally(TestNG.java:1140)
        at org.testng.TestNG.run(TestNG.java:1048)
        at org.testng.TestNG.privateMain(TestNG.java:1355)
        at org.testng.TestNG.main(TestNG.java:1324)

SKIPPED CONFIGURATION: @AfterClass tearDown
SKIPPED: testGooglePageTitleInChrome

===============================================
    TestNG Test Group
    Tests run: 1, Failures: 0, Skips: 1
    Configuration Failures: 1, Skips: 1
===============================================

===============================================
Main Test Suite
Total tests run: 1, Failures: 0, Skips: 1
Configuration Failures: 1, Skips: 1
===============================================

[TestNG] Time taken by org.testng.reporters.JUnitReportReporter@7fbe847c: 16 ms
[TestNG] Time taken by org.testng.reporters.jq.Main@759ebb3d: 78 ms
[TestNG] Time taken by org.testng.reporters.SuiteHTMLReporter@ba8a1dc: 59 ms
[TestNG] Time taken by org.testng.reporters.XMLReporter@1c655221: 5 ms
[TestNG] Time taken by org.testng.reporters.EmailableReporter2@1edf1c96: 16 ms
[TestNG] Time taken by [FailedReporter passed=0 failed=0 skipped=0]: 0 ms
Build step 'Exécuter une ligne de commande batch Windows' marked build as failure
Finished: FAILURE
</code>```

答:
I had the same problem, I was able to execute selenium scripts through local but when tried executing on Jenkins got error "unknown error: cannot find Chrome binary".

Here is my solution which worked on Jenkins server:
1. Download and enable Xvfb before start of selenium script on jenkins. For more info read here https://wiki.jenkins.io/display/JENKINS/Xvfb+Plugin
2. I am having ubuntu 16.xx os on local and jenkins server.
3. Try to keep chromedriver in "usr/bin" folder only otherwise you may get error.

```<code>try {

            if(service == null){
                service = new ChromeDriverService.Builder()
                        .usingDriverExecutable(new File("/usr/bin/chromedriver"))// set the chromedriver path
                       .usingAnyFreePort()
                        .withEnvironment(ImmutableMap.of("DISPLAY", ":15"))
                        .withSilent(true)
                        .build();
                service.start();
            }

            System.out.println("Reading chrome driver");
            System.setProperty("webdriver.chrome.driver","/usr/bin/chromedriver");
            ChromeOptions chromeOptions = new ChromeOptions();
            chromeOptions.addArguments("--headless");
            WebDriver driver = new ChromeDriver(chromeOptions);
            driver.get("https://google.com");
            driver.quit();
 }
        catch(Exception ex){
        System.out.println(ex.getMessage());
        }

</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a basic login test with selenium and testng. When executed from eclipse, it works as expected and invoke Google Chrome. If executed from TESTNG command line, it works fine too.

This is my @Before:

@BeforeMethod
public void setUp() throws Exception {
 File file = new File("C:/Selenium-driver/chromedriver.exe");
 System.setProperty("webdriver.chrome.driver", file.getAbsolutePath());
 driver = new ChromeDriver();
 driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
 }

However, if I execute the same test thru Jenkins it says:

Building in workspace C:\EclipsePortable\Data\workspace\GS_TESTNG
[G_TESTNG] $ cmd /c call C:\Windows\TEMP\hudson9049518275115936054.bat

C:\EclipsePortable\Data\workspace\G_TESTNG>_test_login_cmd.bat

C:\EclipsePortable\Data\workspace\G_TESTNG>cd C:\EclipsePortable\Data\workspace\G_TESTNG

C:\EclipsePortable\Data\workspace\G_TESTNG>java -cp C:\EclipsePortable\Data\workspace\G_TESTNG\lib\*;C:\EclipsePortable\Data\workspace\G_TESTNG\bin org.testng.TestNG testng.xml
...
... TestNG 6.9.9 by Cédric Beust (cedric@beust.com)
...

[TestNG] Running:
  C:\EclipsePortable\Data\workspace\G_TESTNG\testng.xml

Starting ChromeDriver 2.26.436362 (5476ec6bf7ccbada1734a0cdec7d570bb042aa30) on port 36257
Only local connections are allowed.
FAILED CONFIGURATION: @BeforeMethod setUp
org.openqa.selenium.WebDriverException: unknown error: cannot find Chrome binary
  (Driver info: chromedriver=2.26.436362 (5476ec6bf7ccbada1734a0cdec7d570bb042aa30),platform=Windows NT 6.1.7601 SP1 x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 664 milliseconds
Build info: version: '2.51.0', revision: '1af067d', time: '2016-02-05 19:15:17'
System info: host: 'NMTLA12810', ip: '192.168.0.179', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0_102'
Driver info: org.openqa.selenium.chrome.ChromeDriver
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
        at java.lang.reflect.Constructor.newInstance(Unknown Source)
        at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:206)
        at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:158)
        at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:678)
        at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:249)
        at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:131)
        at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:144)
        at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:170)
        at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:159)
        at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:116)
        at com.test.TestA.setUp(TestA.java:33)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
        at java.lang.reflect.Method.invoke(Unknown Source)
        at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:85)
        at org.testng.internal.Invoker.invokeConfigurationMethod(Invoker.java:510)
        at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:211)
        at org.testng.internal.Invoker.invokeMethod(Invoker.java:585)
        at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:816)
        at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1124)
        at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:125)
        at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:108)
        at org.testng.TestRunner.privateRun(TestRunner.java:774)
        at org.testng.TestRunner.run(TestRunner.java:624)
        at org.testng.SuiteRunner.runTest(SuiteRunner.java:359)
        at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:354)
        at org.testng.SuiteRunner.privateRun(SuiteRunner.java:312)
        at org.testng.SuiteRunner.run(SuiteRunner.java:261)
        at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
        at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
        at org.testng.TestNG.runSuitesSequentially(TestNG.java:1215)
        at org.testng.TestNG.runSuitesLocally(TestNG.java:1140)
        at org.testng.TestNG.run(TestNG.java:1048)
        at org.testng.TestNG.privateMain(TestNG.java:1355)
        at org.testng.TestNG.main(TestNG.java:1324)

SKIPPED CONFIGURATION: @AfterClass tearDown
SKIPPED: testGooglePageTitleInChrome

===============================================
    TestNG Test Group
    Tests run: 1, Failures: 0, Skips: 1
    Configuration Failures: 1, Skips: 1
===============================================

===============================================
Main Test Suite
Total tests run: 1, Failures: 0, Skips: 1
Configuration Failures: 1, Skips: 1
===============================================

[TestNG] Time taken by org.testng.reporters.JUnitReportReporter@7fbe847c: 16 ms
[TestNG] Time taken by org.testng.reporters.jq.Main@759ebb3d: 78 ms
[TestNG] Time taken by org.testng.reporters.SuiteHTMLReporter@ba8a1dc: 59 ms
[TestNG] Time taken by org.testng.reporters.XMLReporter@1c655221: 5 ms
[TestNG] Time taken by org.testng.reporters.EmailableReporter2@1edf1c96: 16 ms
[TestNG] Time taken by [FailedReporter passed=0 failed=0 skipped=0]: 0 ms
Build step 'Exécuter une ligne de commande batch Windows' marked build as failure
Finished: FAILURE

Body:
I had the same problem, I was able to execute selenium scripts through local but when tried executing on Jenkins got error "unknown error: cannot find Chrome binary".

Here is my solution which worked on Jenkins server:
1. Download and enable Xvfb before start of selenium script on jenkins. For more info read here https://wiki.jenkins.io/display/JENKINS/Xvfb+Plugin
2. I am having ubuntu 16.xx os on local and jenkins server.
3. Try to keep chromedriver in "usr/bin" folder only otherwise you may get error.

try {

            if(service == null){
                service = new ChromeDriverService.Builder()
                        .usingDriverExecutable(new File("/usr/bin/chromedriver"))// set the chromedriver path
                       .usingAnyFreePort()
                        .withEnvironment(ImmutableMap.of("DISPLAY", ":15"))
                        .withSilent(true)
                        .build();
                service.start();
            }

            System.out.println("Reading chrome driver");
            System.setProperty("webdriver.chrome.driver","/usr/bin/chromedriver");
            ChromeOptions chromeOptions = new ChromeOptions();
            chromeOptions.addArguments("--headless");
            WebDriver driver = new ChromeDriver(chromeOptions);
            driver.get("https://google.com");
            driver.quit();
 }
        catch(Exception ex){
        System.out.println(ex.getMessage());
        }


问:
What's the best way to perform a differential between a list of directories?
I am interested in looking at a list of directories and comparing the previous list with a current list of directories and setting up a script to do so. Maybe in perl or as a shell script.

Should I use something like diff? Programatically, what would be an ideal way to do this? For example let say I output the diff to an output file, if there is no diff then exit, if there is results, I want to see it.

Let's for example I have the following directories today:

```<code>/foo/bar/staging/abc
/foo/bar/staging/def
/foo/bar/staging/a1b2c3
</code>```

Next day would look like this where a directory is either added, or renamed:

```<code>/foo/bar/staging/abc
/foo/bar/staging/def
/foo/bar/staging/ghi
/foo/bar/staging/a1b2c4
</code>```

答:
There might be better ways, but the way I typically do something like this is to run a find command in each directory root, and pipe the output to separate files.  You can then diff the files using the diff tool of your choice.  If you want to filter out certain directories or files, you can throw in some grep or grep -v commands in the pipeline, or you can experiment with options on the find command.

The other main option is to find a diff tool that offers directory/folder comparisons.  Most of the goods ones support this, but I like the command line method, because you get more control over what you're diffing.

```<code>cd /my/directory/one
find . -print | sort > /temp/one.txt

cd /my/directory/two
find . -print | sort > /temp/two.txt

diff /temp/one.txt /temp/two.txt
</code>```

Body:
I am interested in looking at a list of directories and comparing the previous list with a current list of directories and setting up a script to do so. Maybe in perl or as a shell script.

Should I use something like diff? Programatically, what would be an ideal way to do this? For example let say I output the diff to an output file, if there is no diff then exit, if there is results, I want to see it.

Let's for example I have the following directories today:

/foo/bar/staging/abc
/foo/bar/staging/def
/foo/bar/staging/a1b2c3

Next day would look like this where a directory is either added, or renamed:

/foo/bar/staging/abc
/foo/bar/staging/def
/foo/bar/staging/ghi
/foo/bar/staging/a1b2c4

Body:
There might be better ways, but the way I typically do something like this is to run a find command in each directory root, and pipe the output to separate files.  You can then diff the files using the diff tool of your choice.  If you want to filter out certain directories or files, you can throw in some grep or grep -v commands in the pipeline, or you can experiment with options on the find command.

The other main option is to find a diff tool that offers directory/folder comparisons.  Most of the goods ones support this, but I like the command line method, because you get more control over what you're diffing.

cd /my/directory/one
find . -print | sort > /temp/one.txt

cd /my/directory/two
find . -print | sort > /temp/two.txt

diff /temp/one.txt /temp/two.txt


问:
VBA create CSV with varying row lenght
i am very new to VBA or programmin in general.
Nevertheless, I need to create a code for exporting a csv file.
My issue is that I have several rows with varying lenght in my file.
The file looks as following:

```<code>3,6,8
3,9,4,7,8
1
2,4
7,9,4,5,6,8,1
3
</code>```

My codes gives me:

```<code>"3","6","8","","","",""
"3","9","4","7","8","",""
"1","","","","","",""
"2","4","","","","",""
"7","9","4","5","6","8","1"
"3","","","","","",""
</code>```

I need:

```<code>"3","6","8"
"3","9","4","7","8"
"1"
"2","4"
"7","9","4","5","6","8","1"
"3"
</code>```

Can anyone please help me?

```<code>Sub CIF_Katalog_2()

Dim i As Long, lngZeile As Long
Dim myCSVFileName As String
    Dim myWB As Workbook

Set myWB = ThisWorkbook

myCSVFileName = myWB.Path & "\" & "CSV Katalog Export_" & VBA.Format(VBA.Now, "dd-MMM-yyyy hh-mm") & ".csv"
lngZeile = Range("A" & Rows.Count).End(xlUp).Row

Open myCSVFileName For Output As #1

For i = 1 To lngZeile

    If i = 1 Then

        Print #1, Chr(34) & Cells(i, 1).Value & Chr(34)

    ElseIf i = 2 Then

        Print #1, Chr(34) & Cells(i, 1).Value & Chr(34) & "," & Chr(34) & Cells(i, 2).Value & Chr(34)

    Else

        Print #1, Chr(34) & Cells(i, 1).Value & Chr(34) & "," & Chr(34) & Cells(i, 2).Value & Chr(34) & "," & Chr(34) & Cells(i, 3).Value & Chr(34) & "," & Chr(34) & Cells(i, 4).Value & Chr(34) & "," & Chr(34) & Cells(i, 5).Value & Chr(34) & "," & Chr(34) & Cells(i, 6).Value & Chr(34) & "," & Chr(34) & Cells(i, 7).Value & Chr(34) & "," & Chr(34) & Cells(i, 8).Value & Chr(34) & "," & Chr(34) & Cells(i, 9).Value & Chr(34) & "," & Chr(34) & Cells(i, 10).Value & Chr(34) & "," & Chr(34) & Cells(i, 11).Value & Chr(34) & "," & Chr(34) & Cells(i, 12).Value & Chr(34) & "," & Chr(34) & Cells(i, 13).Value _
        & Chr(34) & "," & Chr(34) & Cells(i, 14).Value & Chr(34) & "," & Chr(34) & Cells(i, 15).Value & Chr(34) & "," & Chr(34) & Cells(i, 16).Value & Chr(34) & "," & Chr(34) & Cells(i, 17).Value & Chr(34) & "," & Chr(34) & Cells(i, 18).Value & Chr(34) & "," & Chr(34) & Cells(i, 19).Value & Chr(34) & "," & Chr(34) & Cells(i, 20).Value & Chr(34) & _
        "," & Chr(34) & Cells(i, 21).Value & Chr(34) & "," & Chr(34) & Cells(i, 22).Value & Chr(34) & "," & Chr(34) & Cells(i, 23).Value & Chr(34) & "," & Cells(i, 24).Value & Chr(34) & "," & Chr(34) & Cells(i, 25).Value & Chr(34) & "," & Chr(34) & Cells(i, 26).Value & Chr(34) & "," & Chr(34) & Cells(i, 27).Value & Chr(34) & "," & Chr(34) & Cells(i, 28).Value & Chr(34) & "," & Chr(34) & Cells(i, 29).Value & Chr(34) & "," & Cells(i, 30).Value & "," & Chr(34) & Cells(i, 31).Value & Chr(34) & "," & Chr(34) & Cells(i, 32).Value & Chr(34) & "," & Chr(34) & Cells(i, 33).Value & Chr(34) & "," & Chr(34) & Cells(i, 34).Value & Chr(34) & "," & Chr(34) & Cells(i, 35).Value & Chr(34)

End If

Next i

Close #1

MsgBox "Erledigt"

End Sub

</code>```

答:
Give this a try... just reusing your code:

Sub CIF_Katalog_2()

Dim i As Long, x As Long, lngZeile As Long
Dim myCSVFileName As String, strTemp As String
Dim myWB As Workbook: Set myWB = ThisWorkbook

myCSVFileName = myWB.Path & "\" & "CSV Katalog Export_" & VBA.Format(VBA.Now, "dd-MMM-yyyy hh-mm") & ".csv"
lngZeile = Range("A" & Rows.Count).End(xlUp).Row

Open myCSVFileName For Output As #1

    For i = 1 To lngZeile
        For x = 1 To 35
            If Cells(i, x) <> "" Then
                strTemp = strTemp & Chr(34) & Cells(i, x).Value & Chr(34) & ","
            End If
        Next x
        Print #1, Left(strTemp, Len(strTemp) - 1)
        strTemp = ""
    Next i

Close #1

MsgBox "Erledigt"

End Sub
```

Title: VBA create CSV with varying row lenght

Body:
i am very new to VBA or programmin in general.
Nevertheless, I need to create a code for exporting a csv file.
My issue is that I have several rows with varying lenght in my file.
The file looks as following:

3,6,8
3,9,4,7,8
1
2,4
7,9,4,5,6,8,1
3

My codes gives me:

"3","6","8","","","",""
"3","9","4","7","8","",""
"1","","","","","",""
"2","4","","","","",""
"7","9","4","5","6","8","1"
"3","","","","","",""

I need:

"3","6","8"
"3","9","4","7","8"
"1"
"2","4"
"7","9","4","5","6","8","1"
"3"

Can anyone please help me?

Sub CIF_Katalog_2()

Dim i As Long, lngZeile As Long
Dim myCSVFileName As String
    Dim myWB As Workbook

Set myWB = ThisWorkbook

myCSVFileName = myWB.Path & "\" & "CSV Katalog Export_" & VBA.Format(VBA.Now, "dd-MMM-yyyy hh-mm") & ".csv"
lngZeile = Range("A" & Rows.Count).End(xlUp).Row

Open myCSVFileName For Output As #1

For i = 1 To lngZeile

    If i = 1 Then

        Print #1, Chr(34) & Cells(i, 1).Value & Chr(34)

    ElseIf i = 2 Then

        Print #1, Chr(34) & Cells(i, 1).Value & Chr(34) & "," & Chr(34) & Cells(i, 2).Value & Chr(34)

    Else

        Print #1, Chr(34) & Cells(i, 1).Value & Chr(34) & "," & Chr(34) & Cells(i, 2).Value & Chr(34) & "," & Chr(34) & Cells(i, 3).Value & Chr(34) & "," & Chr(34) & Cells(i, 4).Value & Chr(34) & "," & Chr(34) & Cells(i, 5).Value & Chr(34) & "," & Chr(34) & Cells(i, 6).Value & Chr(34) & "," & Chr(34) & Cells(i, 7).Value & Chr(34) & "," & Chr(34) & Cells(i, 8).Value & Chr(34) & "," & Chr(34) & Cells(i, 9).Value & Chr(34) & "," & Chr(34) & Cells(i, 10).Value & Chr(34) & "," & Chr(34) & Cells(i, 11).Value & Chr(34) & "," & Chr(34) & Cells(i, 12).Value & Chr(34) & "," & Chr(34) & Cells(i, 13).Value _
        & Chr(34) & "," & Chr(34) & Cells(i, 14).Value & Chr(34) & "," & Chr(34) & Cells(i, 15).Value & Chr(34) & "," & Chr(34) & Cells(i, 16).Value & Chr(34) & "," & Chr(34) & Cells(i, 17).Value & Chr(34) & "," & Chr(34) & Cells(i, 18).Value & Chr(34) & "," & Chr(34) & Cells(i, 19).Value & Chr(34) & "," & Chr(34) & Cells(i, 20).Value & Chr(34) & _
        "," & Chr(34) & Cells(i, 21).Value & Chr(34) & "," & Chr(34) & Cells(i, 22).Value & Chr(34) & "," & Chr(34) & Cells(i, 23).Value & Chr(34) & "," & Cells(i, 24).Value & Chr(34) & "," & Chr(34) & Cells(i, 25).Value & Chr(34) & "," & Chr(34) & Cells(i, 26).Value & Chr(34) & "," & Chr(34) & Cells(i, 27).Value & Chr(34) & "," & Chr(34) & Cells(i, 28).Value & Chr(34) & "," & Chr(34) & Cells(i, 29).Value & Chr(34) & "," & Cells(i, 30).Value & "," & Chr(34) & Cells(i, 31).Value & Chr(34) & "," & Chr(34) & Cells(i, 32).Value & Chr(34) & "," & Chr(34) & Cells(i, 33).Value & Chr(34) & "," & Chr(34) & Cells(i, 34).Value & Chr(34) & "," & Chr(34) & Cells(i, 35).Value & Chr(34)

End If

Next i

Close #1

MsgBox "Erledigt"

End Sub


问:
React Native wrapping Text oddly
I am trying to render a line of text inside a view in my component. But the text is not wrapping correctly on word level but randomly going to new line. I think it is trying to fit a longer line on a new line but that is not what I want. This is an Expo app.

If standard Text tag is not good for this then is there some other alternative?

This is my component:

Request Item

```<code>import React from "react";
import { Text, View } from "react-native";
import { MarkdownView } from "react-native-markdown-view";
import Tag from "../common/Tag";
import Colors from "../../constants/Colors";
import styles from "./Styles";

const RequestItem = ({ type, title, priority, creator, rid, createDate, dueDate }) => {
  return (
    <View style={styles.RequestContainer}>
      <View>
        <Tag title={type} color={type === "S" ? Colors.BlueAccent : Colors.GreenAccent} />
      </View>
      <View style={styles.RequestTitleContainer}>
        <View>
          <Text style={styles.RequestTitle}>
            {`${title} `}
            <Tag
              title={priority}
              color={
                // eslint-disable-next-line no-nested-ternary
                priority === "High"
                  ? Colors.RedAccent
                  : priority === "Medium"
                  ? Colors.BlueAccent
                  : Colors.GreenAccent
              }
            />
          </Text>
        </View>
        <View>
          <Text style={{ borderWidth: 2, borderColor: "red" }}>
            {`**${creator}** created the request with id: **${rid}** on
              **${createDate}** due on **${dueDate}**`}
          </Text>
        </View>
      </View>
    </View>
  );
};

export default RequestItem;
</code>```

Styles

```<code>import { StyleSheet } from "react-native";
import Colors from "../../constants/Colors";

const styles = StyleSheet.create({
  RequestContainer: {
    borderColor: Colors.GrayAccent,
    borderRadius: 5,
    borderWidth: 1,
    flexDirection: "row",
    margin: 10,
    padding: 4,
  },
  RequestTitle: {
    fontWeight: "bold",
  },
  RequestTitleContainer: {
    flexDirection: "column",
    flexWrap: "wrap",
    marginLeft: 5,
  },
});

export default styles;
</code>```

As you can see here, the line of text Aug 7, 2018 can easily fit on the previous line. Still starting from it, the content was wrapped to a new line. Why is this?

I tried usig flex-wrap: "wrap", but that did not help.

I wanted to wrap the text at word level. How do I go about it?

答:
Because you have a new line inside the string you are trying to print. Tapping ENTER inside backticks (``) will trigger a new line. So what's following next will be displayed on a new line.

Example:

```<code>console.log(`something
    else`);
</code>```

Will print on 2 lines.

Title: React Native wrapping Text oddly

Body:
I am trying to render a line of text inside a view in my component. But the text is not wrapping correctly on word level but randomly going to new line. I think it is trying to fit a longer line on a new line but that is not what I want. This is an Expo app.

If standard Text tag is not good for this then is there some other alternative?

This is my component:

Request Item

import React from "react";
import { Text, View } from "react-native";
import { MarkdownView } from "react-native-markdown-view";
import Tag from "../common/Tag";
import Colors from "../../constants/Colors";
import styles from "./Styles";

const RequestItem = ({ type, title, priority, creator, rid, createDate, dueDate }) => {
  return (
    <View style={styles.RequestContainer}>
      <View>
        <Tag title={type} color={type === "S" ? Colors.BlueAccent : Colors.GreenAccent} />
      </View>
      <View style={styles.RequestTitleContainer}>
        <View>
          <Text style={styles.RequestTitle}>
            {`${title} `}
            <Tag
              title={priority}
              color={
                // eslint-disable-next-line no-nested-ternary
                priority === "High"
                  ? Colors.RedAccent
                  : priority === "Medium"
                  ? Colors.BlueAccent
                  : Colors.GreenAccent
              }
            />
          </Text>
        </View>
        <View>
          <Text style={{ borderWidth: 2, borderColor: "red" }}>
            {`**${creator}** created the request with id: **${rid}** on
              **${createDate}** due on **${dueDate}**`}
          </Text>
        </View>
      </View>
    </View>
  );
};

export default RequestItem;

Styles

import { StyleSheet } from "react-native";
import Colors from "../../constants/Colors";

const styles = StyleSheet.create({
  RequestContainer: {
    borderColor: Colors.GrayAccent,
    borderRadius: 5,
    borderWidth: 1,
    flexDirection: "row",
    margin: 10,
    padding: 4,
  },
  RequestTitle: {
    fontWeight: "bold",
  },
  RequestTitleContainer: {
    flexDirection: "column",
    flexWrap: "wrap",
    marginLeft: 5,
  },
});

export default styles;

As you can see here, the line of text Aug 7, 2018 can easily fit on the previous line. Still starting from it, the content was wrapped to a new line. Why is this?

I tried usig flex-wrap: "wrap", but that did not help.

I wanted to wrap the text at word level. How do I go about it?

Body:
Because you have a new line inside the string you are trying to print. Tapping ENTER inside backticks (``) will trigger a new line. So what's following next will be displayed on a new line.

Example:

console.log(`something
    else`);

Will print on 2 lines.


问:
Problem with mysqli_real_escape_string (and magic quotes is off)
I am having a problem with mysqli_real_escape_string and single quotes.

Anytime an insert takes a value that includes a ' mysqli_real_escape_string replaces it with \' causing the insert to fail.

I do not have magic quotes enabled, which seems to be a common cause of this problem, but still find I get \' and not \' or even \\'

Can anyone tell me what might have gone wrong here?

答:
taking this to an answer since comments are a bit limiting.

So you're generating the query like

```<code>$a = mysqli_real_escape_string(... something ...);
$b = mysqli_real_escape_string(... something else ...);

$sql = "INSERT ... VALUES ('$a', '$b')";
</code>```

?

ok. so let's say this:

```<code>$a = "'"; // a is now a single quote: '
$escaped_a = mysql_real_escape_string($a); // should be \' now

$sql1 = "INSERT ... VALUES ('$a' ..."
$sql2 = "INSERT ... VALUES ('$escaped_a' ..."
</code>```

you should end up with

```<code>INSERT ... vALUES (''' ...
INSERT ... VALUES ('\'' ...
</code>```

The first one is "bad". because of the extra quote. The second is valid.

Body:
taking this to an answer since comments are a bit limiting.

So you're generating the query like

$a = mysqli_real_escape_string(... something ...);
$b = mysqli_real_escape_string(... something else ...);

$sql = "INSERT ... VALUES ('$a', '$b')";

?

ok. so let's say this:

$a = "'"; // a is now a single quote: '
$escaped_a = mysql_real_escape_string($a); // should be \' now

$sql1 = "INSERT ... VALUES ('$a' ..."
$sql2 = "INSERT ... VALUES ('$escaped_a' ..."

you should end up with

INSERT ... vALUES (''' ...
INSERT ... VALUES ('\'' ...

The first one is "bad". because of the extra quote. The second is valid.


问:
Adding text formatting to CSV file text
I'm creating one CSV file using csv_table_view(Code copied below). I want to prefix CSV data with some text message. This message should be in red color and bold. Is there any way by which I can specify text color and bold property in the message string. Here is my code-

```<code>def render_csv(view)
    ctv = CsvTableView.new(view)
    csv = ctv.render
    render_csv_content(csv, ctv)
end

def render_csv_content(csv, ctv)
    headers['Content-Type'] = "application/vnd.ms-excel"
    headers['Content-Length'] = csv.size
    headers['Cache-Control'] = ''
    headers['Content-Disposition'] = %{attachment; filename="#{ctv.filename}"; size=#{csv.size}}
    render :text => csv
  end

def render
    @table.prepare(true)
    @ret = []
    @ret ="Hello this message should be red and bold \n"
    @ret +=  @table.columns.map do |col|
      col.split ? col.split.map { |c| "#{col.name} #{c}" }.join(",") : csv_escape(col.name)
    end.join(",") + "\n" +
            @table.all_rows.map { |row| row.map { |col| csv_escape(col)
            }.join(",") }.join("\n")
end
</code>```

I read in one article that with content type application/vnd.ms-excel, we can not add formatting to the text. Any idea on that? Thanks in advance.

答:
There is no way to add formatting to CSV file. It can only ever be text.

It looks as though you're wanting an excel file. One suggestion is to use the spreadsheet gem. This allows for formatting and output as an XLS file. The guide is useful to see how to do this.

Title: Adding text formatting to CSV file text

Body:
I'm creating one CSV file using csv_table_view(Code copied below). I want to prefix CSV data with some text message. This message should be in red color and bold. Is there any way by which I can specify text color and bold property in the message string. Here is my code-

def render_csv(view)
    ctv = CsvTableView.new(view)
    csv = ctv.render
    render_csv_content(csv, ctv)
end

def render_csv_content(csv, ctv)
    headers['Content-Type'] = "application/vnd.ms-excel"
    headers['Content-Length'] = csv.size
    headers['Cache-Control'] = ''
    headers['Content-Disposition'] = %{attachment; filename="#{ctv.filename}"; size=#{csv.size}}
    render :text => csv
  end

def render
    @table.prepare(true)
    @ret = []
    @ret ="Hello this message should be red and bold \n"
    @ret +=  @table.columns.map do |col|
      col.split ? col.split.map { |c| "#{col.name} #{c}" }.join(",") : csv_escape(col.name)
    end.join(",") + "\n" +
            @table.all_rows.map { |row| row.map { |col| csv_escape(col)
            }.join(",") }.join("\n")
end

I read in one article that with content type application/vnd.ms-excel, we can not add formatting to the text. Any idea on that? Thanks in advance.


问:
Math.Random always setting random number to 0
Creating a program where a random number is generated using math.random which i have put into a function and called this function in the program to make things tidier but the random number that gets outputted is always what the integer secret_number is set to, and i am not sure how to fix this to create a random number. I would like to keep the math.random in the function and use parameters

```<code>package guessinggame3;
import java.util.Scanner; //imports scanner to read from keyboard
import java.util.ArrayList;

public class GuessingGame3 { //start of public class

static Scanner kboard = new Scanner(System.in); //calls scanner

public static void main(String args[]) //start of main
{

System.out.println("Welcome to the guessing game, the computer will
generate a random number that you have to guess, good luck!"); //opening
message explaining how to play

int secret_number = 0;
int number_of_guesses = 0;
int user_guess ;
ArrayList<Integer> entered_numbers = new ArrayList<Integer>();

generate_random_number(secret_number); //calls he function
generate_random_number to say the random number has been generated

for(int i=0; i<20;i++) { // start of for loop sets user attempts to 20

System.out.println("Please make your guess"); //asks user to enter make
their guess
user_guess = kboard.nextInt();
number_of_guesses++; // adds on to the counter after each user guess

if(entered_numbers.contains(user_guess)) //checks if entered number =
number stored in array
{
System.out.println("You have already entered this number"); //displays
error message if user enters same number again
continue;
}

else
{
entered_numbers.add(user_guess);
if (user_guess == secret_number)
System.out.println("Your guess is corret you win!");
}

if (user_guess < secret_number)
{
System.out.println("Guess is too low");
}

if (user_guess > secret_number)
{
System.out.println("Your guess is too high");
}

System.out.println (20 - number_of_guesses + " Guesses remaining");
//Tells the user how many guesses they have remaining

} //end of for loop

} //end of main

static void generate_random_number(int secret_number)  //start of function
generate_random_number function passing secret_number as a parameter
{
secret_number = (int)(Math.random()*100) + 1; //generates random number
between 0 and 100
System.out.println("The computer has generated it's number"); //lets the
user know that the random number has been generated
} //end of function generate_random_number
</code>```

} //end of public class

答: When you pass secret_number to the function generate_random_number, secret_number is copied. Thus, when you assign secret_number to (int)(Math.random()*100) + 1 inside your function, you are just changing its copy.

Body:
Creating a program where a random number is generated using math.random which i have put into a function and called this function in the program to make things tidier but the random number that gets outputted is always what the integer secret_number is set to, and i am not sure how to fix this to create a random number. I would like to keep the math.random in the function and use parameters

package guessinggame3;
import java.util.Scanner; //imports scanner to read from keyboard
import java.util.ArrayList;

public class GuessingGame3 { //start of public class

static Scanner kboard = new Scanner(System.in); //calls scanner

public static void main(String args[]) //start of main
{

System.out.println("Welcome to the guessing game, the computer will
generate a random number that you have to guess, good luck!"); //opening
message explaining how to play

int secret_number = 0;
int number_of_guesses = 0;
int user_guess ;
ArrayList<Integer> entered_numbers = new ArrayList<Integer>();

generate_random_number(secret_number); //calls he function
generate_random_number to say the random number has been generated

for(int i=0; i<20;i++) { // start of for loop sets user attempts to 20

System.out.println("Please make your guess"); //asks user to enter make
their guess
user_guess = kboard.nextInt();
number_of_guesses++; // adds on to the counter after each user guess

if(entered_numbers.contains(user_guess)) //checks if entered number =
number stored in array
{
System.out.println("You have already entered this number"); //displays
error message if user enters same number again
continue;
}

else
{
entered_numbers.add(user_guess);
if (user_guess == secret_number)
System.out.println("Your guess is corret you win!");
}

if (user_guess < secret_number)
{
System.out.println("Guess is too low");
}

if (user_guess > secret_number)
{
System.out.println("Your guess is too high");
}

System.out.println (20 - number_of_guesses + " Guesses remaining");
//Tells the user how many guesses they have remaining

} //end of for loop

} //end of main

static void generate_random_number(int secret_number)  //start of function
generate_random_number function passing secret_number as a parameter
{
secret_number = (int)(Math.random()*100) + 1; //generates random number
between 0 and 100
System.out.println("The computer has generated it's number"); //lets the
user know that the random number has been generated
} //end of function generate_random_number

} //end of public class


问:
Im getting "JavaScript critical error at line 692" in internet explorer
I have a problem in IE with my forEach, it is working in Google Chrome and Microsoft Edge but IE is giving me this error.

Code :

```<code>function jsFiltreleme(GelenDeger) {
                    $('#myDiv').html('');
                    var cnt = 1;
                    $.ajax({
                        type: 'GET',
                        url: '/Ajax/ContractedServiceAdd2?serviceName=' + GelenDeger.serviceName + '&&cityCode=' + GelenDeger.cityCode + '&&countryCode=' + GelenDeger.countryCode + '&&markCode=' + GelenDeger.markCode + '',
                        dataType: "json",
                        success: function (response) {
                            response.forEach(acente => {  //Problem is Here line 692
                                const $div = $('<div></div>').addClass("well well-sm").attr('style', 'border-style:ridge;');
                                $div.html(`
                           <div class = "numberCircle"> ` + cnt++ + ` </div> <strong>Acente Adı : </strong>  ` + acente.name + `<br>
                            <strong>Yetki :</strong>  ` + acente.category + `<br>
                            <strong>Adresi : </strong> ` + acente.address + `<br>
                            <strong>Telefon  :</strong> ` + acente.phone + `<br>
                            <a href=\"mailto:`+ acente.email + `\"><strong> >E-Mail Gönder</strong><br>
                            <a href=\"https://maps.google.com/maps?q= `+ acente.lat + "," + acente.lng + `\"><strong> >Yol tarifi al</strong>
                       `);
                                $("#myDiv").append($div);
                            });
                            if (response.length == 0) {
                                alert("Kayıt Bulunamadı");

                            }
                        },
                    });

                }
</code>```

答:
The arrow function expression doesn't support IE browser, you could change your code as below:

```<code>        response.forEach(function (acente) { //Problem is Here line 692

        });
        if (response.length == 0) {
            alert("Kayıt Bulunamadı");

        }
</code>```

Edit:

not change this time is say javascript critical error at line 693

This issue is related to the code about the dynamically add html elements. You could build the DOMString first, then insert the string into a div container using the append method. Code like this:

```<code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="output">

</div>
<script>
    var response= [your response array];
    var cnt = 1;
    response.forEach(function (acente) {
        var textnode = document.createTextNode(acente);
        document.getElementById("output").appendChild(textnode);
        var newdiv = "<div class = 'well well-sm' style='border-style:ridge;'><div class = 'numberCircle'> " + cnt++ + " </div> <strong>Acente Adı : </strong> " + acente.name + "<br />" +
            "<strong>Yetki :</strong>  " + acente.category + "<br>" +
            "<strong>Adresi : </strong> " + acente.address + "<br>" +
            "<strong>Telefon  :</strong> " + acente.phone + "<br>" +
            "<a href='mailto:" + acente.email + "'><strong> >E-Mail Gönder</strong>" + "<br/>" +
            "<a href='https://maps.google.com/maps?q= " + acente.lat + "," + acente.lng + "'><strong> >Yol tarifi al</strong>" +
            "</div>"
        $("#output").append(newdiv);
    });
</script>
</code>```

Body:
I have a problem in IE with my forEach, it is working in Google Chrome and Microsoft Edge but IE is giving me this error.

Code :

function jsFiltreleme(GelenDeger) {
                    $('#myDiv').html('');
                    var cnt = 1;
                    $.ajax({
                        type: 'GET',
                        url: '/Ajax/ContractedServiceAdd2?serviceName=' + GelenDeger.serviceName + '&&cityCode=' + GelenDeger.cityCode + '&&countryCode=' + GelenDeger.countryCode + '&&markCode=' + GelenDeger.markCode + '',
                        dataType: "json",
                        success: function (response) {
                            response.forEach(acente => {  //Problem is Here line 692
                                const $div = $('

').addClass("well well-sm").attr('style', 'border-style:ridge;');
                                $div.html(`

 ` + cnt++ + `
 Acente Adı :   ` + acente.name + `

                            Yetki :  ` + acente.category + `

                            Adresi :  ` + acente.address + `

                            Telefon  : ` + acente.phone + `

                            <a href=\"mailto:`+ acente.email + `\"> >E-Mail Gönder

                            <a href=\"https://maps.google.com/maps?q= `+ acente.lat + "," + acente.lng + `\"> >Yol tarifi al
                       `);
                                $("#myDiv").append($div);
                            });
                            if (response.length == 0) {
                                alert("Kayıt Bulunamadı");

                            }
                        },
                    });

                }

Body:
The arrow function expression doesn't support IE browser, you could change your code as below:

        response.forEach(function (acente) { //Problem is Here line 692

        });
        if (response.length == 0) {
            alert("Kayıt Bulunamadı");

        }

Edit:

not change this time is say javascript critical error at line 693

This issue is related to the code about the dynamically add html elements. You could build the DOMString first, then insert the string into a div container using the append method. Code like this:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="output">

</div>
<script>
    var response= [your response array];
    var cnt = 1;
    response.forEach(function (acente) {
        var textnode = document.createTextNode(acente);
        document.getElementById("output").appendChild(textnode);
        var newdiv = "<div class = 'well well-sm' style='border-style:ridge;'><div class = 'numberCircle'> " + cnt++ + " </div> <strong>Acente Adı : </strong> " + acente.name + "<br />" +
            "<strong>Yetki :</strong>  " + acente.category + "<br>" +
            "<strong>Adresi : </strong> " + acente.address + "<br>" +
            "<strong>Telefon  :</strong> " + acente.phone + "<br>" +
            "<a href='mailto:" + acente.email + "'><strong> >E-Mail Gönder</strong>" + "<br/>" +
            "<a href='https://maps.google.com/maps?q= " + acente.lat + "," + acente.lng + "'><strong> >Yol tarifi al</strong>" +
            "</div>"
        $("#output").append(newdiv);
    });
</script>


问:
write function not working properly in python
I wrote a code to produce the following output. It works fine when I use append function in marked line in code but when i use ''w' write function it, it only prints one line in the new created text file. Problem to use append function is if we run the code again it copies same output twice. I am not able to understand this . Please Help  Thanks in advance

Code I used:

```<code>import os
with open("input5.csv", 'r+') as fd:
    lines = fd.readlines()
    fd.seek(0)
    fd.writelines(line for line in lines if line.strip())
    fd.truncate()

lines = open('input5.csv').readlines()
open('output1.txt', 'w').writelines(lines[1:-2])

with open('output1.txt', 'r+') as m:
    newText = m.read()
    while ',' in newText:
        newText = newText.replace(',', '_')
with open('output1.txt', "w") as m:
    m.write(newText)

with open("output1.txt","r+") as fp:
    for cnt, line in enumerate(fp):
        line=line.replace('_',',',3)
        print(line)
        f = open('output7.txt', 'a') #THIS LINE
        for i in range(len(line)):
            f.write((line[i]))
        f.close()
os.remove("output1.txt")
</code>```

Input:

```<code>id,name,amount,subject
1,abc,55,"s1,s2,s3"
1,abc1,56,"s4,s5,s6"
1,abc2,57,"s7,s8,s9"
1,abc3,58,"s10,s11,s12"
1,abc4,59,"s13,s14,s15"
1,abc5,59,"s16,s17,s18"
1,abc6,59,"s13,s14,s15"
1,abc7,59,"s13,s14,s15"
1,abc8,59,"s13,s14,s15"
1,abc9,59,"s13,s14,s15"
this file is done
time taken; 22nd
</code>```

expected output:(This is the code i get when use append function marked line of the code)

```<code>1,abc,55,"s1_s2_s3"
1,abc1,56,"s4_s5_s6"
1,abc2,57,"s7_s8_s9"
1,abc3,58,"s10_s11_s12"
1,abc4,59,"s13_s14_s15"
1,abc5,59,"s16_s17_s18"
1,abc6,59,"s13_s14_s15"
1,abc7,59,"s13_s14_s15"
1,abc8,59,"s13_s14_s15"
1,abc9,59,"s13_s14_s15"
</code>```

Output i get when I replace append with write function in marked line of code:

```<code>1,abc9,59,"s13_s14_s15"
</code>```

答:
Something like this (not tested), where the file open and close is outside the loop:</p>

```<code>import os
with open("input5.csv", 'r+') as fd:
    lines = fd.readlines()
    fd.seek(0)
    fd.writelines(line for line in lines if line.strip())
    fd.truncate()

lines = open('input5.csv').readlines()
open('output1.txt', 'w').writelines(lines[1:-2])

with open('output1.txt', 'r+') as m:
    newText = m.read()
    while ',' in newText:
        newText = newText.replace(',', '_')
with open('output1.txt', "w") as m:
    m.write(newText)

with open("output1.txt","r+") as fp:
    f = open('output7.txt', 'w') #THIS LINE
    for cnt, line in enumerate(fp):
        line=line.replace('_',',',3)
        print(line)

        for i in range(len(line)):
            f.write((line[i]))
    f.close()
os.remove("output1.txt")
</code>```

Body:
I wrote a code to produce the following output. It works fine when I use append function in marked line in code but when i use ''w' write function it, it only prints one line in the new created text file. Problem to use append function is if we run the code again it copies same output twice. I am not able to understand this . Please Help  Thanks in advance

Code I used:

import os
with open("input5.csv", 'r+') as fd:
    lines = fd.readlines()
    fd.seek(0)
    fd.writelines(line for line in lines if line.strip())
    fd.truncate()

lines = open('input5.csv').readlines()
open('output1.txt', 'w').writelines(lines[1:-2])

with open('output1.txt', 'r+') as m:
    newText = m.read()
    while ',' in newText:
        newText = newText.replace(',', '_')
with open('output1.txt', "w") as m:
    m.write(newText)

with open("output1.txt","r+") as fp:
    for cnt, line in enumerate(fp):
        line=line.replace('_',',',3)
        print(line)
        f = open('output7.txt', 'a') #THIS LINE
        for i in range(len(line)):
            f.write((line[i]))
        f.close()
os.remove("output1.txt")

Input:

id,name,amount,subject
1,abc,55,"s1,s2,s3"
1,abc1,56,"s4,s5,s6"
1,abc2,57,"s7,s8,s9"
1,abc3,58,"s10,s11,s12"
1,abc4,59,"s13,s14,s15"
1,abc5,59,"s16,s17,s18"
1,abc6,59,"s13,s14,s15"
1,abc7,59,"s13,s14,s15"
1,abc8,59,"s13,s14,s15"
1,abc9,59,"s13,s14,s15"
this file is done
time taken; 22nd

expected output:(This is the code i get when use append function marked line of the code)

1,abc,55,"s1_s2_s3"
1,abc1,56,"s4_s5_s6"
1,abc2,57,"s7_s8_s9"
1,abc3,58,"s10_s11_s12"
1,abc4,59,"s13_s14_s15"
1,abc5,59,"s16_s17_s18"
1,abc6,59,"s13_s14_s15"
1,abc7,59,"s13_s14_s15"
1,abc8,59,"s13_s14_s15"
1,abc9,59,"s13_s14_s15"

Output i get when I replace append with write function in marked line of code:

1,abc9,59,"s13_s14_s15"

Body:
Something like this (not tested), where the file open and close is outside the loop:

import os
with open("input5.csv", 'r+') as fd:
    lines = fd.readlines()
    fd.seek(0)
    fd.writelines(line for line in lines if line.strip())
    fd.truncate()

lines = open('input5.csv').readlines()
open('output1.txt', 'w').writelines(lines[1:-2])

with open('output1.txt', 'r+') as m:
    newText = m.read()
    while ',' in newText:
        newText = newText.replace(',', '_')
with open('output1.txt', "w") as m:
    m.write(newText)

with open("output1.txt","r+") as fp:
    f = open('output7.txt', 'w') #THIS LINE
    for cnt, line in enumerate(fp):
        line=line.replace('_',',',3)
        print(line)

        for i in range(len(line)):
            f.write((line[i]))
    f.close()
os.remove("output1.txt")


答:
I got it, the problem was with this line:

{**${creator}** created the request with id: **${rid}** on
  **${createDate}** due on **${dueDate}**}

Since I broke it down in 2 parts with enter this was happening.

Title: React Native wrapping Text oddly


问:
Silverlight 3 class library
I'm currently working on a UI development project and it was decided to implement it in Silvelight. I understand that Microsoft developers try to minimize size of the distribution and that's why some (lots) of the classes in regular .NET Framework are not included. Is it expected to see more classes included in Silverlight 3 library?</p>

答:
I hope not, and I doubt it.

Scott Guthrie who apparently runs the project for Microsoft is on the record as saying that he doesn't want to put "nice to haves" in, in case there's no room left for any future "must haves".

I think they've got the balance right - there's not much they've left out which you can't write yourself.

OwnerDisplayName: buckethead

ContentLicense: CC BY-SA 2.5

Title: Silverlight 3 class library

LastEditorDisplayName: buckethead

OwnerDisplayName: Phil Bachmann


问:
Remove match word from file
The Data in the File1.txt is

```<code>Raj cmd
Rahul cmd
Pooja cmd
Vilas cmd
Vikram cmd
</code>```

I want the Output to be Printed like this below

```<code>Raj
Rahul
Pooja
Vilas
Vikram
</code>```

The Word I want to remove is "cmd"

答:
try this:

```<code>sed 's/\s*cmd//' File1.txt
</code>```

explanation

```<code>s/   # substitute
\s*  # ignore blanks
cmd  # your pattern
//   # replace with nothing
</code>```

Title: Remove match word from file

Body:
The Data in the File1.txt is

Raj cmd
Rahul cmd
Pooja cmd
Vilas cmd
Vikram cmd

I want the Output to be Printed like this below

Raj
Rahul
Pooja
Vilas
Vikram

The Word I want to remove is "cmd"

Body:
try this:

sed 's/\s*cmd//' File1.txt

explanation

s/   # substitute
\s*  # ignore blanks
cmd  # your pattern
//   # replace with nothing


问:
FatalExecutionEngineError after restarting debug session
Since a few weeks (months?) I've been sometimes getting the following exception after restarting my ASP.NET application inside Visual Studio 2017 / 2019 Enterprise. It only happens when IIS Express was already running my application and I needed to start a new debug session after recompiling.

Whenever this happens, I have to kill IIS Express (taskkill /f /im iisexpress.exe) and start a new debug session in VS. I can't figure out what triggers this issue. It started happening on VS 2017 Enterprise some day. Maybe because I received some Win10 update? Upgrading to VS 2019 Enterprise didn't solve the problem.

Managed Debugging Assistant 'FatalExecutionEngineError'

  Message=Managed Debugging Assistant 'FatalExecutionEngineError' : 'The runtime has encountered a fatal error. The address of the error was at 0x45b30496, on thread 0x16b8. The error code is 0xc0000005. This error may be a bug in the CLR or in the unsafe or non-verifiable portions of user code. Common sources of this bug include user marshaling errors for COM-interop or PInvoke, which may corrupt the stack.'

There are some similar issues reported, but either don't resolve my problem or don't apply:

Managed Debugging Assistant 'FatalExecutionEngineError'

I'm not using Use Managed Compatibility Mode.

Managed Debugging Assistant 'FatalExecutionEngineError' 0xc0000005

IISExpress is set to x64 as the solution is build for x64.

https://developercommunity.visualstudio.com/content/problem/29782/managed-debugging-assistant-fatalexecutionengineer.html

Solution targets .Net Framework 4.6.1, not .Net core.

We don't use EntityFramework.

答:
I had the same exception on VS17, solved it running the IDE as administrator. I know this is not an ideal solution but in my case it was the only one working. Everything else I tried failed.
Hope it helps</p>


问:
I want the four different footer on last page, first-page, odd-page, even-page using XSL-FO
I am making an XSL:FO file which contains four pages where first-page header contains the title of the chapter, and the odd and even pages has the footer of page numbers and last-page contains the footer of small table</p>

答:
Look at fo:page-sequence-master (see https://www.w3.org/TR/xsl11/#fo_page-sequence-master) and particularly at fo:repeatable-page-master-alternatives (see https://www.w3.org/TR/xsl11/#fo_repeatable-page-master-alternatives).

You essentially want to set up your alternatives in the sequence 'first', 'last', 'rest'. (You could also set it up to have different page masters for odd and even pages if you wanted.)

See, for example:

"Switching between right and left page layouts (<fo:page-sequence-master>)" in "Comprehensive XSL-FO Tutorials and Samples Collection" at https://www.antennahouse.com/comprehensive-xsl-fo-tutorials-and-samples-collection/

How to place content at the bottom of the last page of my document

https://stackoverflow.com/a/28382375/4092205

https://stackoverflow.com/a/17651048/4092205