问:
How to pass parameters in tensorflow
I want to train a network using tensorflow, I choose the "Inception_resnet_v2" as the net(from here), here is my train code,

```<code>def train(train_dir, annotations, max_step, checkpoint_dir='./checkpoint2/'):
# train the model
features = tf.placeholder("float32", shape=[None, IMAGE_SIZE, IMAGE_SIZE, IMAGE_CHANNEL], name="features")
labels = tf.placeholder("float32", [None], name="labels")
one_hot_labels = tf.one_hot(indices=tf.cast(labels, tf.int32), depth=80)
keep_prob = tf.placeholder("float32")
isTraining = tf.placeholder("bool")
#train_step, cross_entropy, logits, keep_prob = network.inference(features, one_hot_labels)
logits, _=inception_resnet_v2.inception_resnet_v2(features,80,isTraining,keep_prob)
# calculate loss
cross_entropy = tf.reduce_mean(
    tf.nn.softmax_cross_entropy_with_logits(labels=one_hot_labels, logits=logits))

train_step = tf.train.AdamOptimizer(LEARNINGRATE).minimize(cross_entropy)

correct_prediction = tf.equal(tf.argmax(logits, 1), tf.argmax(one_hot_labels, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))

image_list, label_list = scene_input2.get_files(train_dir, annotations)
image_batch, label_batch = scene_input2.get_batch(image_list, label_list, IMAGE_SIZE, IMAGE_SIZE, BATCH_SIZE)

with tf.Session() as sess:
    saver = tf.train.Saver()
    ckpt = tf.train.get_checkpoint_state(checkpoint_dir)
    if ckpt and ckpt.model_checkpoint_path:
        print('Restore the model from checkpoint %s' % ckpt.model_checkpoint_path)
        # Restores from checkpoint
        saver.restore(sess, ckpt.model_checkpoint_path)
        start_step = int(ckpt.model_checkpoint_path.split('/')[-1].split('-')[-1])
    else:
        sess.run(tf.global_variables_initializer())
        start_step = 0
        print('start training from new state')
    logger = scene_input.train_log(LOGNAME)

    coord = tf.train.Coordinator()
    threads = tf.train.start_queue_runners(coord=coord)

    try:
        #        Check if stop was requested.
        step=start_step
        while not coord.should_stop() and step<start_step + max_step:
            start_time = time.time()
            x, y = sess.run([image_batch, label_batch])
            #y = tf.one_hot(indices=tf.cast(y, tf.int32), depth=80)
            #y = sess.run(y)
            sess.run(train_step, feed_dict={features: x, labels: y, isTraining: True, keep_prob: 0.5})
            if step % 50 == 0:
                train_accuracy = sess.run(accuracy, feed_dict={features: x, labels: y, isTraining: False, keep_prob: 1})
                train_loss = sess.run(cross_entropy, feed_dict={features: x, labels: y, isTraining:False, keep_prob: 1})
                duration = time.time() - start_time
                logger.info("step %d: training accuracy %g, loss is %g (%0.3f sec)" % (step, train_accuracy, train_loss, duration))
            if step % 1000 == 1:
                saver.save(sess, CHECKFILE, global_step=step)
                print('writing checkpoint at step %s' % step)
            step=step+1

    except tf.errors.OutOfRangeError:
        print('done!')
    finally:
        #Request that the threads stop.After this is called, calls to should_stop() will return True.
        coord.request_stop()
    coord.join(threads)
</code>```

but when i train the net, i meet an error:

```<code>    Traceback (most recent call last):
  File "scene2.py", line 245, in <module>
    train(FLAGS.train_dir, FLAGS. annotations, FLAGS.max_step)
  File "scene2.py", line 82, in train
    logits, _=inception_resnet_v2.inception_resnet_v2(features,80,isTraining,keep_prob)
  File "/home/vision/inception_resnet_v2.py", line 357, in inception_resnet_v2
    scope='Dropout')
  File "/usr/local/lib/python3.4/dist-packages/tensorflow/contrib/framework/python/ops/arg_scope.py", line 181, in func_with_args
    return func(*args, **current_args)
  File "/usr/local/lib/python3.4/dist-packages/tensorflow/contrib/layers/python/layers/layers.py", line 1216, in dropout
    _scope=sc)
  File "/usr/local/lib/python3.4/dist-packages/tensorflow/python/layers/core.py", line 247, in __init__
    self.rate = min(1., max(0., rate))
  File "/usr/local/lib/python3.4/dist-packages/tensorflow/python/framework/ops.py", line 564, in __bool__
    raise TypeError("Using a `tf.Tensor` as a Python `bool` is not allowed. "
TypeError: Using a `tf.Tensor` as a Python `bool` is not allowed. Use `if t is not None:` instead of `if t:` to test if a tensor is defined, and use TensorFlow ops such as tf.cond to execute subgraphs conditioned on the value of a tensor.
vision@Hjl:~/$ CUDA_VISIBLE_DEVICES=0 python3 scene2.py --mode train
Traceback (most recent call last):
  File "scene2.py", line 245, in <module>
    train(FLAGS.train_dir, FLAGS. annotations, FLAGS.max_step)
  File "scene2.py", line 82, in train
    logits, _=inception_resnet_v2.inception_resnet_v2(features,80,isTraining,keep_prob)
  File "/home/vision/inception_resnet_v2.py", line 357, in inception_resnet_v2
    scope='Dropout')
  File "/usr/local/lib/python3.4/dist-packages/tensorflow/contrib/framework/python/ops/arg_scope.py", line 181, in func_with_args
    return func(*args, **current_args)
  File "/usr/local/lib/python3.4/dist-packages/tensorflow/contrib/layers/python/layers/layers.py", line 1216, in dropout
    _scope=sc)
  File "/usr/local/lib/python3.4/dist-packages/tensorflow/python/layers/core.py", line 247, in __init__
    self.rate = min(1., max(0., rate))
  File "/usr/local/lib/python3.4/dist-packages/tensorflow/python/framework/ops.py", line 564, in __bool__
    raise TypeError("Using a `tf.Tensor` as a Python `bool` is not allowed. "
TypeError: Using a `tf.Tensor` as a Python `bool` is not allowed. Use `if t is not None:` instead of `if t:` to test if a tensor is defined, and use TensorFlow ops such as tf.cond to execute subgraphs conditioned on the value of a tensor.
</code>```

when i pass keep_prob and keep_prob to inception_resnet_v2.inception_resnet_v2(features,80,isTraining,keep_prob), the error occurred. How can I solve this problem?

when i train the network, i want to set keep_prob = 0.5, isTraining = True, but at the same time , every 50 step, i want to watch the model's train_accuracy and train_loss, so i should set keep_prob = 1.0, isTraining = False, am I right? How can I implement it?

答:
If your ultimate objective is to perform training and evaluation concurrently, and you are using the neural network implementations provided with the tf-slim library, then it may be easiest to follow the methodology prescribed by tf-slim co-author Nathan Silberman.

In short, training and evaluation are performed by two separate processes, with the evaluation process pointing to a checkpoint directory, waiting (infinitely) for a new checkpoint to be written to that directory by the training process, and then automatically performing evaluation on the newly written checkpoint and writing summaries to a specified eval output directory.

To get started, you should take a look at the train_image_classifier.py and eval_image_classifier.py scripts provided in the TensorFlow-Slim image classification model library.

In eval_image_classifier.py, you will want to replace the code:

```<code>if tf.gfile.IsDirectory(FLAGS.checkpoint_path):
  checkpoint_path = tf.train.latest_checkpoint(FLAGS.checkpoint_path)
else:
  checkpoint_path = FLAGS.checkpoint_path

tf.logging.info('Evaluating %s' % checkpoint_path)

slim.evaluation.evaluate_once(
    master=FLAGS.master,
    checkpoint_path=checkpoint_path,
    logdir=FLAGS.eval_dir,
    num_evals=num_batches,
    eval_op=list(names_to_updates.values()),
    variables_to_restore=variables_to_restore)
</code>```

with the code:

```<code>tf.logging.info('Evaluating %s' % FLAGS.checkpoint_path)

slim.evaluation.evaluation_loop(
    master=FLAGS.master,
    checkpoint_dir=FLAGS.checkpoint_path,
    logdir=FLAGS.eval_dir,
    num_evals=num_batches,
    eval_op=list(names_to_updates.values()),
    variables_to_restore=variables_to_restore)
</code>```

If you want both processes to utilize your GPU(s) without running into OOM errors, you can allocate a fraction of GPU memory to each process by creating a ConfigProto object and passing it as the argument of the session_config parameter of slim.learning.train() or slim.evaluation.evaluation_loop(). See the "Allowing GPU memory growth" section of this tensorflow.org article for reference.

Regarding the parameterization of is_training, you will notice that the train and eval scripts pass True and False respectively as their arguments to the is_training parameter of nets_factory.get_netowrk_fn().

Regarding the parameterization of keep_prob, nets_factory does not expose the dropout_keep_prob parameter of the slim nets. Instead, slim.dropout() accepts is_training as a parameter and replaces the computations that constitute dropout with the identity function. In other words, tf-slim is so awesome that it automatically "disables" dropout when you pass is_training=False to nets_factory.get_netowrk_fn(), as is the case in eval_image_classifier.py.

If you want to expose dropout_keep_prob to train_image_classifier.py directly (e.g. for hyperparameter tuning purposes), you will have to fiddle with the implementation of nets_factory.get_network_fn().

Title: How to pass parameters in tensorflow

Body:
I want to train a network using tensorflow, I choose the "Inception_resnet_v2" as the net(from here), here is my train code,

def train(train_dir, annotations, max_step, checkpoint_dir='./checkpoint2/'):
# train the model
features = tf.placeholder("float32", shape=[None, IMAGE_SIZE, IMAGE_SIZE, IMAGE_CHANNEL], name="features")
labels = tf.placeholder("float32", [None], name="labels")
one_hot_labels = tf.one_hot(indices=tf.cast(labels, tf.int32), depth=80)
keep_prob = tf.placeholder("float32")
isTraining = tf.placeholder("bool")
#train_step, cross_entropy, logits, keep_prob = network.inference(features, one_hot_labels)
logits, _=inception_resnet_v2.inception_resnet_v2(features,80,isTraining,keep_prob)
# calculate loss
cross_entropy = tf.reduce_mean(
    tf.nn.softmax_cross_entropy_with_logits(labels=one_hot_labels, logits=logits))

train_step = tf.train.AdamOptimizer(LEARNINGRATE).minimize(cross_entropy)

correct_prediction = tf.equal(tf.argmax(logits, 1), tf.argmax(one_hot_labels, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))

image_list, label_list = scene_input2.get_files(train_dir, annotations)
image_batch, label_batch = scene_input2.get_batch(image_list, label_list, IMAGE_SIZE, IMAGE_SIZE, BATCH_SIZE)

with tf.Session() as sess:
    saver = tf.train.Saver()
    ckpt = tf.train.get_checkpoint_state(checkpoint_dir)
    if ckpt and ckpt.model_checkpoint_path:
        print('Restore the model from checkpoint %s' % ckpt.model_checkpoint_path)
        # Restores from checkpoint
        saver.restore(sess, ckpt.model_checkpoint_path)
        start_step = int(ckpt.model_checkpoint_path.split('/')[-1].split('-')[-1])
    else:
        sess.run(tf.global_variables_initializer())
        start_step = 0
        print('start training from new state')
    logger = scene_input.train_log(LOGNAME)

    coord = tf.train.Coordinator()
    threads = tf.train.start_queue_runners(coord=coord)

    try:
        #        Check if stop was requested.
        step=start_step
        while not coord.should_stop() and step<start_step + max_step:
            start_time = time.time()
            x, y = sess.run([image_batch, label_batch])
            #y = tf.one_hot(indices=tf.cast(y, tf.int32), depth=80)
            #y = sess.run(y)
            sess.run(train_step, feed_dict={features: x, labels: y, isTraining: True, keep_prob: 0.5})
            if step % 50 == 0:
                train_accuracy = sess.run(accuracy, feed_dict={features: x, labels: y, isTraining: False, keep_prob: 1})
                train_loss = sess.run(cross_entropy, feed_dict={features: x, labels: y, isTraining:False, keep_prob: 1})
                duration = time.time() - start_time
                logger.info("step %d: training accuracy %g, loss is %g (%0.3f sec)" % (step, train_accuracy, train_loss, duration))
            if step % 1000 == 1:
                saver.save(sess, CHECKFILE, global_step=step)
                print('writing checkpoint at step %s' % step)
            step=step+1

    except tf.errors.OutOfRangeError:
        print('done!')
    finally:
        #Request that the threads stop.After this is called, calls to should_stop() will return True.
        coord.request_stop()
    coord.join(threads)

but when i train the net, i meet an error:

    Traceback (most recent call last):
  File "scene2.py", line 245, in <module>
    train(FLAGS.train_dir, FLAGS. annotations, FLAGS.max_step)
  File "scene2.py", line 82, in train
    logits, _=inception_resnet_v2.inception_resnet_v2(features,80,isTraining,keep_prob)
  File "/home/vision/inception_resnet_v2.py", line 357, in inception_resnet_v2
    scope='Dropout')
  File "/usr/local/lib/python3.4/dist-packages/tensorflow/contrib/framework/python/ops/arg_scope.py", line 181, in func_with_args
    return func(*args, **current_args)
  File "/usr/local/lib/python3.4/dist-packages/tensorflow/contrib/layers/python/layers/layers.py", line 1216, in dropout
    _scope=sc)
  File "/usr/local/lib/python3.4/dist-packages/tensorflow/python/layers/core.py", line 247, in __init__
    self.rate = min(1., max(0., rate))
  File "/usr/local/lib/python3.4/dist-packages/tensorflow/python/framework/ops.py", line 564, in __bool__
    raise TypeError("Using a `tf.Tensor` as a Python `bool` is not allowed. "
TypeError: Using a `tf.Tensor` as a Python `bool` is not allowed. Use `if t is not None:` instead of `if t:` to test if a tensor is defined, and use TensorFlow ops such as tf.cond to execute subgraphs conditioned on the value of a tensor.
vision@Hjl:~/$ CUDA_VISIBLE_DEVICES=0 python3 scene2.py --mode train
Traceback (most recent call last):
  File "scene2.py", line 245, in <module>
    train(FLAGS.train_dir, FLAGS. annotations, FLAGS.max_step)
  File "scene2.py", line 82, in train
    logits, _=inception_resnet_v2.inception_resnet_v2(features,80,isTraining,keep_prob)
  File "/home/vision/inception_resnet_v2.py", line 357, in inception_resnet_v2
    scope='Dropout')
  File "/usr/local/lib/python3.4/dist-packages/tensorflow/contrib/framework/python/ops/arg_scope.py", line 181, in func_with_args
    return func(*args, **current_args)
  File "/usr/local/lib/python3.4/dist-packages/tensorflow/contrib/layers/python/layers/layers.py", line 1216, in dropout
    _scope=sc)
  File "/usr/local/lib/python3.4/dist-packages/tensorflow/python/layers/core.py", line 247, in __init__
    self.rate = min(1., max(0., rate))
  File "/usr/local/lib/python3.4/dist-packages/tensorflow/python/framework/ops.py", line 564, in __bool__
    raise TypeError("Using a `tf.Tensor` as a Python `bool` is not allowed. "
TypeError: Using a `tf.Tensor` as a Python `bool` is not allowed. Use `if t is not None:` instead of `if t:` to test if a tensor is defined, and use TensorFlow ops such as tf.cond to execute subgraphs conditioned on the value of a tensor.

when i pass keep_prob and keep_prob to inception_resnet_v2.inception_resnet_v2(features,80,isTraining,keep_prob), the error occurred. How can I solve this problem?

when i train the network, i want to set keep_prob = 0.5, isTraining = True, but at the same time , every 50 step, i want to watch the model's train_accuracy and train_loss, so i should set keep_prob = 1.0, isTraining = False, am I right? How can I implement it?

Body:
If your ultimate objective is to perform training and evaluation concurrently, and you are using the neural network implementations provided with the tf-slim library, then it may be easiest to follow the methodology prescribed by tf-slim co-author Nathan Silberman.

In short, training and evaluation are performed by two separate processes, with the evaluation process pointing to a checkpoint directory, waiting (infinitely) for a new checkpoint to be written to that directory by the training process, and then automatically performing evaluation on the newly written checkpoint and writing summaries to a specified eval output directory.

To get started, you should take a look at the train_image_classifier.py and eval_image_classifier.py scripts provided in the TensorFlow-Slim image classification model library.

In eval_image_classifier.py, you will want to replace the code:

if tf.gfile.IsDirectory(FLAGS.checkpoint_path):
  checkpoint_path = tf.train.latest_checkpoint(FLAGS.checkpoint_path)
else:
  checkpoint_path = FLAGS.checkpoint_path

tf.logging.info('Evaluating %s' % checkpoint_path)

slim.evaluation.evaluate_once(
    master=FLAGS.master,
    checkpoint_path=checkpoint_path,
    logdir=FLAGS.eval_dir,
    num_evals=num_batches,
    eval_op=list(names_to_updates.values()),
    variables_to_restore=variables_to_restore)

with the code:

tf.logging.info('Evaluating %s' % FLAGS.checkpoint_path)

slim.evaluation.evaluation_loop(
    master=FLAGS.master,
    checkpoint_dir=FLAGS.checkpoint_path,
    logdir=FLAGS.eval_dir,
    num_evals=num_batches,
    eval_op=list(names_to_updates.values()),
    variables_to_restore=variables_to_restore)

If you want both processes to utilize your GPU(s) without running into OOM errors, you can allocate a fraction of GPU memory to each process by creating a ConfigProto object and passing it as the argument of the session_config parameter of slim.learning.train() or slim.evaluation.evaluation_loop(). See the "Allowing GPU memory growth" section of this tensorflow.org article for reference.

Regarding the parameterization of is_training, you will notice that the train and eval scripts pass True and False respectively as their arguments to the is_training parameter of nets_factory.get_netowrk_fn().

Regarding the parameterization of keep_prob, nets_factory does not expose the dropout_keep_prob parameter of the slim nets. Instead, slim.dropout() accepts is_training as a parameter and replaces the computations that constitute dropout with the identity function. In other words, tf-slim is so awesome that it automatically "disables" dropout when you pass is_training=False to nets_factory.get_netowrk_fn(), as is the case in eval_image_classifier.py.

If you want to expose dropout_keep_prob to train_image_classifier.py directly (e.g. for hyperparameter tuning purposes), you will have to fiddle with the implementation of nets_factory.get_network_fn().


来源: stackexchange

问:
openldap: is dn an alias for distinguishedName?
If I run ldapsearch (CentOS 7.4, slapd 2.4.44) command against an Active Directory Windows 2012 server:

```<code>[root@myserver ~]# ldapsearch -LLL -x -h openldap.company.com -D "Administrator@company.com" -w mypassword -s sub -b 'dc=company,dc=com' "(cn=Administrator)"
</code>```

I get:

```<code>dn: CN=Administrator,CN=Users,DC=company,DC=com
</code>```

But if I run the equivalent in Softerra LDAP Browser, I don't see dn but distinguishedName:

```<code>distinguishedName: CN=Users,DC=company,DC=com
</code>```

To determine if dn was an alias of distinguishedName or vice-versa, I checked the definition in openLDAP, and I see this:

```<code>[root@openldap schema]# grep -r 'NAME '"'"'distinguished' /etc/openldap/schema
./core.ldif:#olcAttributeTypes: ( 2.5.4.49 NAME 'distinguishedName'
./core.schema:#attributetype ( 2.5.4.49 NAME 'distinguishedName'
</code>```

but both of those results are commented out anyway:

```<code># system schema
#attributetype ( 2.5.4.49 NAME 'distinguishedName'
#       EQUALITY distinguishedNameMatch
#       SYNTAX 1.3.6.1.4.1.1466.115.121.1.12 )
</code>```

So, some basic questions:

Why is distinguishedName commented out?

How can we use a dn attribute in an LDIF file if dn is not defined in any schema?

Is dn an alias of distinguishedName or vice-versa?

答:
Why is distinguishedName commented out?

It's probably hard-wired into the server.

How can we use a dn attribute in an LDIF file if dn is not defined in any schema?

See (1).

Is dn an alias of distinguishedName or vice-versa?

Both.

ContentLicense: CC BY-SA 3.0

Body:
If I run ldapsearch (CentOS 7.4, slapd 2.4.44) command against an Active Directory Windows 2012 server:

[root@myserver ~]# ldapsearch -LLL -x -h openldap.company.com -D "Administrator@company.com" -w mypassword -s sub -b 'dc=company,dc=com' "(cn=Administrator)"

I get:

dn: CN=Administrator,CN=Users,DC=company,DC=com

But if I run the equivalent in Softerra LDAP Browser, I don't see dn but distinguishedName:

distinguishedName: CN=Users,DC=company,DC=com

To determine if dn was an alias of distinguishedName or vice-versa, I checked the definition in openLDAP, and I see this:

[root@openldap schema]# grep -r 'NAME '"'"'distinguished' /etc/openldap/schema
./core.ldif:#olcAttributeTypes: ( 2.5.4.49 NAME 'distinguishedName'
./core.schema:#attributetype ( 2.5.4.49 NAME 'distinguishedName'

but both of those results are commented out anyway:

# system schema
#attributetype ( 2.5.4.49 NAME 'distinguishedName'
#       EQUALITY distinguishedNameMatch
#       SYNTAX 1.3.6.1.4.1.1466.115.121.1.12 )

So, some basic questions:

Why is distinguishedName commented out?

How can we use a dn attribute in an LDIF file if dn is not defined in any schema?

Is dn an alias of distinguishedName or vice-versa?


问:
How can I combine two components in a Bigcommerce theme
Ok so I am editing a Bigcommerce theme for a client. I don't have a lot of experience with Bigcommerce and only a little php. The current theme header is set up so that you can have the logo justified to the Left, center or right. Then depending on where the logo is, the search bar and Social Links take up the other 2 spaces.

I.E. is you have the logo to the left the search bar goes to the center and the social links go to the right.

The client would like to add another "logo" to the header and would like to combine the search bar and social links.

I'm looking at the markup for the header, it is set up like this

```<code>{{#if theme_settings.logo-position '==' 'left'}}
    <div class="header-logo header-logo--{{theme_settings.logo-position}} container">
        {{> components/common/store-logo}}
        {{> components/common/quick-search}}
        {{> components/common/social-links-header}}
    </div>
{{/if}}

{{#if theme_settings.logo-position '==' 'center'}}
    <div class="header-logo header-logo--{{theme_settings.logo-position}} container">
        {{> components/common/social-links-header}}
        {{> components/common/store-logo}}
        {{> components/common/quick-search}}
    </div>
{{/if}}

{{#if theme_settings.logo-position '==' 'right'}}
    <div class="header-logo header-logo--{{theme_settings.logo-position}} container">
        {{> components/common/social-links-header}}
        {{> components/common/quick-search}}
        {{> components/common/store-logo}}
    </div>
{{/if}}
</code>```

I'm thinking I can just use the {#if theme_settings.logo-position '==' 'left'}   to set up the layout I am trying to get by just adding the additional logo and combining the quick-search and social-links-header components. How can I combine those components?

答: Each component has a separate template file, so you could add the second logo to store-logo.html, and then copy the content from quick-search.html and paste it into social-links-header.html to combine those elements. You can also use CSS to adjust the layout--it really depends on the position you're trying to achieve.</p>

Body:
Ok so I am editing a Bigcommerce theme for a client. I don't have a lot of experience with Bigcommerce and only a little php. The current theme header is set up so that you can have the logo justified to the Left, center or right. Then depending on where the logo is, the search bar and Social Links take up the other 2 spaces.

I.E. is you have the logo to the left the search bar goes to the center and the social links go to the right.

The client would like to add another "logo" to the header and would like to combine the search bar and social links.

I'm looking at the markup for the header, it is set up like this

{{#if theme_settings.logo-position '==' 'left'}}

        {{> components/common/store-logo}}
        {{> components/common/quick-search}}
        {{> components/common/social-links-header}}

{{/if}}

{{#if theme_settings.logo-position '==' 'center'}}

        {{> components/common/social-links-header}}
        {{> components/common/store-logo}}
        {{> components/common/quick-search}}

{{/if}}

{{#if theme_settings.logo-position '==' 'right'}}

        {{> components/common/social-links-header}}
        {{> components/common/quick-search}}
        {{> components/common/store-logo}}

{{/if}}

I'm thinking I can just use the {#if theme_settings.logo-position '==' 'left'}   to set up the layout I am trying to get by just adding the additional logo and combining the quick-search and social-links-header components. How can I combine those components?


问:
ASP.NET: Having common Page title in master page with each page adding page-specific title?
My master page looks like:

```<code><head runat="server">
    <title>
        <asp:ContentPlaceHolder ID="PageTitlePlaceHolder" runat="server" />
    </title>
</code>```

Content pages look like:

```<code><asp:Content ID="TitleContent1"
     ContentPlaceHolderID="PageTitlePlaceHolder" runat="Server">
    My Page
</asp:Content>
</code>```

This works by placing the content page specific title on the page ("My Page" in this example).  Now I want to add a global prefix to the title in my master page for the site name.  So I want:

```<code><head runat="server">
    <title>
        Example.com:
        <asp:ContentPlaceHolder ID="PageTitlePlaceHolder" runat="server" />
    </title>
</code>```

However, when I do this content pages are still rendered without "Example.com" in the tile, it's like it's ignored.

Why is this happening and how can I achieve this?

答:
The work around I found most acceptable is to use multiple ContentPlaceHolder controls.

    <title>
        <asp:ContentPlaceHolder ID="cphMasterTitle" runat="server">Example.com: </asp:ContentPlaceHolder>
        <asp:ContentPlaceHolder ID="cphSubtitle" runat="server" />
    </title>

```

Note that any other content inside <title>, including whitespace, is stripped away. Any spacing between the ContentPlaceHolder content needs to be done inside the controls.

I've also used <asp:Literal runat="server">Example.com: </asp:Literal> when I don't want to expose a placeholder to the content pages.

ContentLicense: CC BY-SA 2.5

Body:
My master page looks like:

    <title>
        <asp:ContentPlaceHolder ID="PageTitlePlaceHolder" runat="server" />
    </title>

Content pages look like:

<asp:Content ID="TitleContent1"
     ContentPlaceHolderID="PageTitlePlaceHolder" runat="Server">
    My Page
</asp:Content>

This works by placing the content page specific title on the page ("My Page" in this example).  Now I want to add a global prefix to the title in my master page for the site name.  So I want:

    <title>
        Example.com:
        <asp:ContentPlaceHolder ID="PageTitlePlaceHolder" runat="server" />
    </title>

However, when I do this content pages are still rendered without "Example.com" in the tile, it's like it's ignored.

Why is this happening and how can I achieve this?

Body:
The work around I found most acceptable is to use multiple ContentPlaceHolder controls.

<head runat="server">
    <title>
        <asp:ContentPlaceHolder ID="cphMasterTitle" runat="server">Example.com: </asp:ContentPlaceHolder>
        <asp:ContentPlaceHolder ID="cphSubtitle" runat="server" />
    </title>
</head>

Note that any other content inside <title>, including whitespace, is stripped away. Any spacing between the ContentPlaceHolder content needs to be done inside the controls.

I've also used <asp:Literal runat="server">Example.com: </asp:Literal> when I don't want to expose a placeholder to the content pages.


问:
How can I detect any unicode characters which have descenders, using .NET
I am trying to minimize the vertical distance between controls on a programmatically constructed Windows Form (using C#).  This involves setting the Height property appropriately.

I have found that if the text of the control does not contain any letters with descenders in them (i.e. does not have any of the characters j, g, p, q or y) then the control Height can be smaller than when it does contain such letters (if it does contain letters with descenders then the descenders are chopped off if the Height isn't enough).

It will work fine to test for any of the above 5 characters as long as the language is English, or English - like, but I need to be able to cater for (just about) any language.

Is there a way, given some arbitrary Unicode character (and perhaps a font) to determine if that Unicode character has a descender or not?

答: In Windows, you call GetPath() to get an array containing the X/Y coordinates of every point making up the perimeter or outline of the string of glyphs. Search the array for min/max, which will get you the rectangle exactly enclosing the string. Right to the edge of the letters.


问:
jQuery Drag and Drop table row ordering?
Are there any good tutorials for Drag-and-Drop table row ordering with jQuery-UI
or some other plugin? I have been searching and cant seem to find any useful samples.

Of course the order of the items would also need to be persisted to my database in some way...

答:
With this plugin: [link text][1] you can order the column and manipulate data from a source with the union of plugin jEditable, you can see a example in Examples > API > Editable Rows (with jEditable).

You can use  draggable with the event Stop

```<code>$( ".selector" ).bind( "sortstop", function(event, ui) {
</code>```

...
});

with the method .sortable( "toArray" ) to get the new order of elements.

You can find examples in the official documentation in: http://jqueryui.com/demos/sortable/#event-stop =)

Body:
With this plugin: [link text][1] you can order the column and manipulate data from a source with the union of plugin jEditable, you can see a example in Examples > API > Editable Rows (with jEditable).

You can use  draggable with the event Stop

$( ".selector" ).bind( "sortstop", function(event, ui) {

...
});

with the method .sortable( "toArray" ) to get the new order of elements.

You can find examples in the official documentation in: http://jqueryui.com/demos/sortable/#event-stop =)


问:
Use type derived from GetType() without using Switch
I am using Entity Framework and LINQ. I want to create a reusable method in a "helper" class for GridViews.

The method will return a DataSource as a List of entities based off the type of entity passed.

So GridView1 will show [Entity1]'s so the call will look like:

```<code>GridView1.DataSource = helperClass.GetDataSource(new Entity1());
</code>```

Note* If I should pass the entity type I want as a string in the method I am open for suggestion. I just don't want to have to use a switch case between the ~40 entity types this method could return

The reusable method will be simple and look similar to:

```<code>public static object GetDataSource(object type)
{
    using (DatabaseContext dc = new DatabaseContext())
    {
        if (dc.[how do I get the entity type here].Count() > 0)
        {
            var modelList = dc.[how do I get the entity type here also].ToList();
        }
    }
}
</code>```

This will sound silly, but obviously I wasn't able to do:

```<code>var modelList = dc.(type.GetType()).ToList();
</code>```

but that is basically what I want to accomplish.

答:
If you want to bind the type at compile-time, you can pass the type as a generic argument, and use this type of method:

```<code>        public DbSet<T> GetDataSource<T>()
        {
            var targetType = typeof(DbSet<T>);

            return _db
                .GetType()
                .GetMethods()
                .Where( m => m.ReturnType == targetType)
                .Single()
                .Invoke(_db, null) as DbSet<T>;
        }
</code>```

How does it work? Well, we don't know the name of the method that returns the entity that is being requested, but we do know that the return type has to be a DbSet<T>. So we scan the DatabaseContext for any method that returns that type, and invoke it. This assumes there is exactly one method that has that return type.

If you need true run-time binding (you can't supply the <T> parameter) you can use this sort of method. Note that the return type is just a general IEnumerable because you can't have a specific return type if it's not known at compile time. You can always cast it back to a DbSet<T> if needed.

```<code>        public IEnumerable GetDataSource(Type type)
        {
            var targetType = typeof(DbSet<>).MakeGenericType(new Type[] { type });

            return _db
                .GetType()
                .GetMethods()
                .Where( m => m.ReturnType == targetType)
                .Single()
                .Invoke(_db, null) as IEnumerable;
        }
</code>```

Here is a full example. Note that I stubbed out the EF objects, but this example should still work with a real DbSet and DatabaseContext.

```<code>using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;

public class Program
{

    public class DbSet<T> : List<T>
    {
    }

    public class User
    {
        public string Name { get; set; }
        public override string ToString()
        {
            return "User " + Name;
        }
    }

    public class Transaction
    {
        public decimal Amount { get; set; }
        public override string ToString()
        {
            return "Transaction " + Amount.ToString("0.00");
        }
    }

    public class DatabaseContext
    {
        public DbSet<User> GetUsers()
        {
            return new DbSet<User>()
            {
                new User { Name = "Bob" },
                new User { Name = "Alice" }
            };
        }
        public DbSet<Transaction> GetTransactions()
        {
            return new DbSet<Transaction>()
            {
                new Transaction { Amount = 12.34M },
                new Transaction { Amount = 56.78M }
            };
        }

    }

    public class HelperClass
    {
        private readonly DatabaseContext _db;

        public HelperClass(DatabaseContext db)
        {
            _db = db;
        }

        public DbSet<T> GetDataSource<T>()
        {
            var targetType = typeof(DbSet<T>);

            return _db
                .GetType()
                .GetMethods()
                .Where( m => m.ReturnType == targetType)
                .Single()
                .Invoke(_db, null) as DbSet<T>;
        }

        public IEnumerable GetDataSource(Type type)
        {
            var targetType = typeof(DbSet<>).MakeGenericType(new Type[] { type });

            return _db
                .GetType()
                .GetMethods()
                .Where( m => m.ReturnType == targetType)
                .Single()
                .Invoke(_db, null) as IEnumerable;
        }
    }

    public static void Main()
    {
        var helperClass = new HelperClass(new DatabaseContext());

        foreach (var u in helperClass.GetDataSource<User>())
        {
            Console.WriteLine(u);
        }

        foreach (var t in helperClass.GetDataSource(typeof(Transaction)))
        {
            Console.WriteLine(t);
        }

    }
}
</code>```

Output:

```<code>User Bob
User Alice
Transaction 12.34
Transaction 56.78
</code>```

Full code on DotNetFiddle

Body:
I am using Entity Framework and LINQ. I want to create a reusable method in a "helper" class for GridViews.

The method will return a DataSource as a List of entities based off the type of entity passed.

So GridView1 will show [Entity1]'s so the call will look like:

GridView1.DataSource = helperClass.GetDataSource(new Entity1());

Note* If I should pass the entity type I want as a string in the method I am open for suggestion. I just don't want to have to use a switch case between the ~40 entity types this method could return

The reusable method will be simple and look similar to:

public static object GetDataSource(object type)
{
    using (DatabaseContext dc = new DatabaseContext())
    {
        if (dc.[how do I get the entity type here].Count() > 0)
        {
            var modelList = dc.[how do I get the entity type here also].ToList();
        }
    }
}

This will sound silly, but obviously I wasn't able to do:

var modelList = dc.(type.GetType()).ToList();

but that is basically what I want to accomplish.

Body:
If you want to bind the type at compile-time, you can pass the type as a generic argument, and use this type of method:

        public DbSet<T> GetDataSource<T>()
        {
            var targetType = typeof(DbSet<T>);

            return _db
                .GetType()
                .GetMethods()
                .Where( m => m.ReturnType == targetType)
                .Single()
                .Invoke(_db, null) as DbSet<T>;
        }

How does it work? Well, we don't know the name of the method that returns the entity that is being requested, but we do know that the return type has to be a DbSet<T>. So we scan the DatabaseContext for any method that returns that type, and invoke it. This assumes there is exactly one method that has that return type.

If you need true run-time binding (you can't supply the <T> parameter) you can use this sort of method. Note that the return type is just a general IEnumerable because you can't have a specific return type if it's not known at compile time. You can always cast it back to a DbSet<T> if needed.

        public IEnumerable GetDataSource(Type type)
        {
            var targetType = typeof(DbSet<>).MakeGenericType(new Type[] { type });

            return _db
                .GetType()
                .GetMethods()
                .Where( m => m.ReturnType == targetType)
                .Single()
                .Invoke(_db, null) as IEnumerable;
        }

Here is a full example. Note that I stubbed out the EF objects, but this example should still work with a real DbSet and DatabaseContext.

using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;

public class Program
{

    public class DbSet<T> : List<T>
    {
    }

    public class User
    {
        public string Name { get; set; }
        public override string ToString()
        {
            return "User " + Name;
        }
    }

    public class Transaction
    {
        public decimal Amount { get; set; }
        public override string ToString()
        {
            return "Transaction " + Amount.ToString("0.00");
        }
    }

    public class DatabaseContext
    {
        public DbSet<User> GetUsers()
        {
            return new DbSet<User>()
            {
                new User { Name = "Bob" },
                new User { Name = "Alice" }
            };
        }
        public DbSet<Transaction> GetTransactions()
        {
            return new DbSet<Transaction>()
            {
                new Transaction { Amount = 12.34M },
                new Transaction { Amount = 56.78M }
            };
        }

    }

    public class HelperClass
    {
        private readonly DatabaseContext _db;

        public HelperClass(DatabaseContext db)
        {
            _db = db;
        }

        public DbSet<T> GetDataSource<T>()
        {
            var targetType = typeof(DbSet<T>);

            return _db
                .GetType()
                .GetMethods()
                .Where( m => m.ReturnType == targetType)
                .Single()
                .Invoke(_db, null) as DbSet<T>;
        }

        public IEnumerable GetDataSource(Type type)
        {
            var targetType = typeof(DbSet<>).MakeGenericType(new Type[] { type });

            return _db
                .GetType()
                .GetMethods()
                .Where( m => m.ReturnType == targetType)
                .Single()
                .Invoke(_db, null) as IEnumerable;
        }
    }

    public static void Main()
    {
        var helperClass = new HelperClass(new DatabaseContext());

        foreach (var u in helperClass.GetDataSource<User>())
        {
            Console.WriteLine(u);
        }

        foreach (var t in helperClass.GetDataSource(typeof(Transaction)))
        {
            Console.WriteLine(t);
        }

    }
}

Output:

User Bob
User Alice
Transaction 12.34
Transaction 56.78

Full code on DotNetFiddle


问:
Using a variable for a range
I am writing a macro and am having issues with using a range variable. I think I am setting the range properly, but I cannot do anything with the range. Pseudocode below:

```<code>Dim rng As Range
Set rng = Report(1)      'A function which will be defined below

trackWkbk.Sheets(strFY).rng = 10       <--'THIS IS WHERE I am getting the error.

'trackWbkb is a workbook that is defined properly; I use it elsewhere with no errors.
'strFY is defined and working properly, I use it to call sheets in trackWbkb elsewhere with no errors.
</code>```

The sub function code is:

```<code>Function Report(a) As Range
    Select Case intMonth
        Case intMonth = 7
        Select Case a
            Case a = 1
                Set Report = Range("B2")
        End Select
    End Select
End Function
</code>```

I know my select case statements are gonna get pretty convoluted (this is just a testing sample), but I don't think the issue is there.

Let me know if I should include more code. My code compiles. I think this is something simple that I am missing, but I have been looking online for the past half hour and can't seem to find anything that will resolve this. Does anyone know how to resolve this? Thanks

答:
Your function already returns a Range object. It's not clear to me whether you're trying to obtain a range on another worksheet that is at the same address as a range on the active worksheet. However, you could directly obtain the desired range if you passed the worksheet reference to your function:

```<code>Function Report(ByVal poParentWorksheet As Excel.Worksheet, ByVal a As Integer) As Range
    Select Case intMonth
        Case intMonth = 7
        Select Case a
            Case a = 1
                Set Report = poParentWorksheet.Range("B2")
        End Select
    End Select
End Function
</code>```

Then you could use:

```<code>Set rng = Report(trackWkbk.Sheets(strFY), 1)
rng.Value = 10
</code>```

Title: Using a variable for a range

Body:
I am writing a macro and am having issues with using a range variable. I think I am setting the range properly, but I cannot do anything with the range. Pseudocode below:

Dim rng As Range
Set rng = Report(1)      'A function which will be defined below

trackWkbk.Sheets(strFY).rng = 10       <--'THIS IS WHERE I am getting the error.

'trackWbkb is a workbook that is defined properly; I use it elsewhere with no errors.
'strFY is defined and working properly, I use it to call sheets in trackWbkb elsewhere with no errors.

The sub function code is:

Function Report(a) As Range
    Select Case intMonth
        Case intMonth = 7
        Select Case a
            Case a = 1
                Set Report = Range("B2")
        End Select
    End Select
End Function

I know my select case statements are gonna get pretty convoluted (this is just a testing sample), but I don't think the issue is there.

Let me know if I should include more code. My code compiles. I think this is something simple that I am missing, but I have been looking online for the past half hour and can't seem to find anything that will resolve this. Does anyone know how to resolve this? Thanks

Body:
Your function already returns a Range object. It's not clear to me whether you're trying to obtain a range on another worksheet that is at the same address as a range on the active worksheet. However, you could directly obtain the desired range if you passed the worksheet reference to your function:

Function Report(ByVal poParentWorksheet As Excel.Worksheet, ByVal a As Integer) As Range
    Select Case intMonth
        Case intMonth = 7
        Select Case a
            Case a = 1
                Set Report = poParentWorksheet.Range("B2")
        End Select
    End Select
End Function

Then you could use:

Set rng = Report(trackWkbk.Sheets(strFY), 1)
rng.Value = 10


问:
How to make a folder a non Git directory?
One day I was messing around with Git and I accidentally made a folder Git repository so now it looks like this:

```<code>⌘ ~/sites/ (master)
</code>```

How can I change it back to a regular folder?

答:
```<code>rm -rf .git
</code>```

Removing this folder will make it a non git directory. Maybe accidentally someone previously by doing git init initialized a git repository here.

Body:
One day I was messing around with Git and I accidentally made a folder Git repository so now it looks like this:

⌘ ~/sites/ (master)

How can I change it back to a regular folder?

Body:
rm -rf .git

Removing this folder will make it a non git directory. Maybe accidentally someone previously by doing git init initialized a git repository here.


问:
How to paint a displaced bar in ASP.NET Chart
I am using System.Web.UI.DataVisualization.Charting.Chart and trying to paint displaced bars, but instead of this way:

this other way:

I mean, I would like to paint the bar starting in the point 1 and displaced 55px to the right.

I have achieved this:

with the following code:

```<code>Chart1.Series.Clear();

    int[,] horas = new int[,] { { 0, 1 }, { 1, 1 }, { 2, 0 }, { 3, 1 }, { 4, 0 }, { 5, 1 }, { 6, 0 }, { 7, 0 }, { 8, 1 }, { 9, 1 } };
    Chart1.DataSource = horas;
    var series1 = new Series
    {
        Color = System.Drawing.Color.Green,
        IsVisibleInLegend = false,
        IsXValueIndexed = true,
        ChartType = SeriesChartType.RangeColumn,
    };
    series1["PixelPointWidth"] = "1";

    int[,] horas1 = new int[,] { { 0, 1 }, { 1, 1 }, { 2, 0 }, { 3, 1 }, { 4, 0 }, { 5, 1 }, { 6, 0 }, { 7, 0 }, { 8, 1 }, { 9, 1 } };
    var series2 = new Series
    {
        Color = System.Drawing.Color.Green,
        IsVisibleInLegend = false,
        IsXValueIndexed = true,
        ChartType = SeriesChartType.RangeColumn
    };
    series2["PixelPointWidth"] = "110";

    for (int i = 0; i < horas.GetLength(0); i++)
    {
        series1.Points.AddXY(horas[i, 0], horas[i, 1]);
    }
    for (int i = 0; i < horas.GetLength(0); i++)
    {
        series2.Points.AddXY(horas1[i, 0], horas1[i, 1]);
    }

    int b = 0;
    foreach (var label in Chart1.ChartAreas[0].AxisX.CustomLabels)
    {
        label.Text = b.ToString();
        b++;
    }

    Chart1.Series.Add(series1);
    Chart1.Series.Add(series2);

    Chart1.ChartAreas[0].AxisY.Interval = 0;
    Chart1.ChartAreas[0].AxisX.Interval = 1;
    Chart1.ChartAreas[0].AxisY.Maximum = 1;
    Chart1.ChartAreas[0].AxisY.Minimum = 0;

    Chart1.ChartAreas[0].AxisX.MajorGrid.LineWidth = 0;
    Chart1.ChartAreas[0].AxisY.MajorGrid.LineWidth = 0;
    Chart1.DataBind();
</code>```

But this is not an optimal solution as I must paint at least 1 pixel in the side I don't want.

I would appreciate any solution or suggestion on how to achieve my goal.
Thx in advance.

Edit. This is working in a Windows Server 2012 under IIS 6.0 developed with VS 2015 Professional in the NET 4.5 Framework

Edit: I mean 55 px to the right, but the best solution would be to the next point in the X axis

Edit: this is the content of web.config.

    <configuration>
  <appSettings>
    <add key="ChartImageHandler" value="storage=file;timeout=20;dir=c:\TempImageFiles\;" />
  </appSettings>
  <system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
    <handlers>
      <remove name="ChartImageHandler" />
      <add name="ChartImageHandler" preCondition="integratedMode" verb="GET,HEAD,POST"
        path="ChartImg.axd" type="System.Web.UI.DataVisualization.Charting.ChartHttpHandler, System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
    </handlers>
  </system.webServer>
  <system.web>
    <httpHandlers>
      <add path="ChartImg.axd" verb="GET,HEAD,POST" type="System.Web.UI.DataVisualization.Charting.ChartHttpHandler, System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
        validate="false" />
    </httpHandlers>
    <pages>
      <controls>
        <add tagPrefix="asp" namespace="System.Web.UI.DataVisualization.Charting"
          assembly="System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
      </controls>
    </pages>
    <compilation debug="true" targetFramework="4.5">
      <assemblies>
        <add assembly="System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
      </assemblies>
    </compilation>
    <httpRuntime targetFramework="4.5"/>
  </system.web>
</configuration>```

答:
Rather than trying to paint displaced chart bars, you should simply shift the axis labels by using CustomLabels.

ASPX:

```<code><!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:Chart ID="Chart1" runat="server" Height="600px" Width="800px" >
                <ChartAreas>
                    <asp:ChartArea Name="ChartArea1">
                        <AxisY>
                            <MajorGrid LineColor="DarkGray" LineDashStyle="Dot" />
                        </AxisY>
                        <AxisX>
                            <MajorGrid LineColor="DarkGray" LineDashStyle="Dot" />
                        </AxisX>
                    </asp:ChartArea>
                </ChartAreas>
            </asp:Chart>
        </div>
    </form>
</body>
</html>
</code>```

CS:

```<code>public partial class WebForm1 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        int[,] horas = new int[,] { { 0, 1 }, { 1, 1 }, { 2, 0 }, { 3, 1 }, { 4, 0 }, { 5, 1 }, { 6, 0 }, { 7, 0 }, { 8, 1 }, { 9, 1 } };

        var series1 = new Series
        {
            Color = Color.Green,
            IsVisibleInLegend = false,
            IsXValueIndexed = true,
            ChartType = SeriesChartType.RangeColumn,
            CustomProperties = "PointWidth=0.8"
        };

        for (int i = 0; i < horas.GetLength(0); i++)
        {
            series1.Points.AddXY(horas[i, 0], horas[i, 1]);
        }

        Chart1.Series.Add(series1);

        Chart1.ChartAreas[0].AxisX.Interval = 1;

        Chart1.ChartAreas[0].AxisX.CustomLabels.Add(new CustomLabel { FromPosition = 0, ToPosition = 1, Text = "0", GridTicks = GridTickTypes.All });
        Chart1.ChartAreas[0].AxisX.CustomLabels.Add(new CustomLabel { FromPosition = 1, ToPosition = 2, Text = "1", GridTicks = GridTickTypes.All });
        Chart1.ChartAreas[0].AxisX.CustomLabels.Add(new CustomLabel { FromPosition = 2, ToPosition = 3, Text = "2", GridTicks = GridTickTypes.All });
        Chart1.ChartAreas[0].AxisX.CustomLabels.Add(new CustomLabel { FromPosition = 3, ToPosition = 4, Text = "3", GridTicks = GridTickTypes.All });
        Chart1.ChartAreas[0].AxisX.CustomLabels.Add(new CustomLabel { FromPosition = 4, ToPosition = 5, Text = "4", GridTicks = GridTickTypes.All });
        Chart1.ChartAreas[0].AxisX.CustomLabels.Add(new CustomLabel { FromPosition = 5, ToPosition = 6, Text = "5", GridTicks = GridTickTypes.All });
        Chart1.ChartAreas[0].AxisX.CustomLabels.Add(new CustomLabel { FromPosition = 6, ToPosition = 7, Text = "6", GridTicks = GridTickTypes.All });
        Chart1.ChartAreas[0].AxisX.CustomLabels.Add(new CustomLabel { FromPosition = 7, ToPosition = 8, Text = "7", GridTicks = GridTickTypes.All });
        Chart1.ChartAreas[0].AxisX.CustomLabels.Add(new CustomLabel { FromPosition = 8, ToPosition = 9, Text = "8", GridTicks = GridTickTypes.All });
        Chart1.ChartAreas[0].AxisX.CustomLabels.Add(new CustomLabel { FromPosition = 9, ToPosition = 10, Text = "9", GridTicks = GridTickTypes.All });
        Chart1.ChartAreas[0].AxisX.CustomLabels.Add(new CustomLabel { FromPosition = 10, ToPosition = 11, Text = "10", GridTicks = GridTickTypes.All });
    }
}
</code>```

Body:
I am using System.Web.UI.DataVisualization.Charting.Chart and trying to paint displaced bars, but instead of this way:

this other way:

I mean, I would like to paint the bar starting in the point 1 and displaced 55px to the right.

I have achieved this:

with the following code:

Chart1.Series.Clear();

    int[,] horas = new int[,] { { 0, 1 }, { 1, 1 }, { 2, 0 }, { 3, 1 }, { 4, 0 }, { 5, 1 }, { 6, 0 }, { 7, 0 }, { 8, 1 }, { 9, 1 } };
    Chart1.DataSource = horas;
    var series1 = new Series
    {
        Color = System.Drawing.Color.Green,
        IsVisibleInLegend = false,
        IsXValueIndexed = true,
        ChartType = SeriesChartType.RangeColumn,
    };
    series1["PixelPointWidth"] = "1";

    int[,] horas1 = new int[,] { { 0, 1 }, { 1, 1 }, { 2, 0 }, { 3, 1 }, { 4, 0 }, { 5, 1 }, { 6, 0 }, { 7, 0 }, { 8, 1 }, { 9, 1 } };
    var series2 = new Series
    {
        Color = System.Drawing.Color.Green,
        IsVisibleInLegend = false,
        IsXValueIndexed = true,
        ChartType = SeriesChartType.RangeColumn
    };
    series2["PixelPointWidth"] = "110";

    for (int i = 0; i < horas.GetLength(0); i++)
    {
        series1.Points.AddXY(horas[i, 0], horas[i, 1]);
    }
    for (int i = 0; i < horas.GetLength(0); i++)
    {
        series2.Points.AddXY(horas1[i, 0], horas1[i, 1]);
    }

    int b = 0;
    foreach (var label in Chart1.ChartAreas[0].AxisX.CustomLabels)
    {
        label.Text = b.ToString();
        b++;
    }

    Chart1.Series.Add(series1);
    Chart1.Series.Add(series2);

    Chart1.ChartAreas[0].AxisY.Interval = 0;
    Chart1.ChartAreas[0].AxisX.Interval = 1;
    Chart1.ChartAreas[0].AxisY.Maximum = 1;
    Chart1.ChartAreas[0].AxisY.Minimum = 0;

    Chart1.ChartAreas[0].AxisX.MajorGrid.LineWidth = 0;
    Chart1.ChartAreas[0].AxisY.MajorGrid.LineWidth = 0;
    Chart1.DataBind();

But this is not an optimal solution as I must paint at least 1 pixel in the side I don't want.

I would appreciate any solution or suggestion on how to achieve my goal.
Thx in advance.

Edit. This is working in a Windows Server 2012 under IIS 6.0 developed with VS 2015 Professional in the NET 4.5 Framework

Edit: I mean 55 px to the right, but the best solution would be to the next point in the X axis

Edit: this is the content of web.config.

    <configuration>
  <appSettings>
    <add key="ChartImageHandler" value="storage=file;timeout=20;dir=c:\TempImageFiles\;" />
  </appSettings>
  <system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
    <handlers>
      <remove name="ChartImageHandler" />
      <add name="ChartImageHandler" preCondition="integratedMode" verb="GET,HEAD,POST"
        path="ChartImg.axd" type="System.Web.UI.DataVisualization.Charting.ChartHttpHandler, System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
    </handlers>
  </system.webServer>
  <system.web>
    <httpHandlers>
      <add path="ChartImg.axd" verb="GET,HEAD,POST" type="System.Web.UI.DataVisualization.Charting.ChartHttpHandler, System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
        validate="false" />
    </httpHandlers>
    <pages>
      <controls>
        <add tagPrefix="asp" namespace="System.Web.UI.DataVisualization.Charting"
          assembly="System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
      </controls>
    </pages>
    <compilation debug="true" targetFramework="4.5">
      <assemblies>
        <add assembly="System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
      </assemblies>
    </compilation>
    <httpRuntime targetFramework="4.5"/>
  </system.web>
</configuration>

Body:
Rather than trying to paint displaced chart bars, you should simply shift the axis labels by using CustomLabels.

ASPX:

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:Chart ID="Chart1" runat="server" Height="600px" Width="800px" >
                <ChartAreas>
                    <asp:ChartArea Name="ChartArea1">
                        <AxisY>
                            <MajorGrid LineColor="DarkGray" LineDashStyle="Dot" />
                        </AxisY>
                        <AxisX>
                            <MajorGrid LineColor="DarkGray" LineDashStyle="Dot" />
                        </AxisX>
                    </asp:ChartArea>
                </ChartAreas>
            </asp:Chart>
        </div>
    </form>
</body>
</html>

CS:

public partial class WebForm1 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        int[,] horas = new int[,] { { 0, 1 }, { 1, 1 }, { 2, 0 }, { 3, 1 }, { 4, 0 }, { 5, 1 }, { 6, 0 }, { 7, 0 }, { 8, 1 }, { 9, 1 } };

        var series1 = new Series
        {
            Color = Color.Green,
            IsVisibleInLegend = false,
            IsXValueIndexed = true,
            ChartType = SeriesChartType.RangeColumn,
            CustomProperties = "PointWidth=0.8"
        };

        for (int i = 0; i < horas.GetLength(0); i++)
        {
            series1.Points.AddXY(horas[i, 0], horas[i, 1]);
        }

        Chart1.Series.Add(series1);

        Chart1.ChartAreas[0].AxisX.Interval = 1;

        Chart1.ChartAreas[0].AxisX.CustomLabels.Add(new CustomLabel { FromPosition = 0, ToPosition = 1, Text = "0", GridTicks = GridTickTypes.All });
        Chart1.ChartAreas[0].AxisX.CustomLabels.Add(new CustomLabel { FromPosition = 1, ToPosition = 2, Text = "1", GridTicks = GridTickTypes.All });
        Chart1.ChartAreas[0].AxisX.CustomLabels.Add(new CustomLabel { FromPosition = 2, ToPosition = 3, Text = "2", GridTicks = GridTickTypes.All });
        Chart1.ChartAreas[0].AxisX.CustomLabels.Add(new CustomLabel { FromPosition = 3, ToPosition = 4, Text = "3", GridTicks = GridTickTypes.All });
        Chart1.ChartAreas[0].AxisX.CustomLabels.Add(new CustomLabel { FromPosition = 4, ToPosition = 5, Text = "4", GridTicks = GridTickTypes.All });
        Chart1.ChartAreas[0].AxisX.CustomLabels.Add(new CustomLabel { FromPosition = 5, ToPosition = 6, Text = "5", GridTicks = GridTickTypes.All });
        Chart1.ChartAreas[0].AxisX.CustomLabels.Add(new CustomLabel { FromPosition = 6, ToPosition = 7, Text = "6", GridTicks = GridTickTypes.All });
        Chart1.ChartAreas[0].AxisX.CustomLabels.Add(new CustomLabel { FromPosition = 7, ToPosition = 8, Text = "7", GridTicks = GridTickTypes.All });
        Chart1.ChartAreas[0].AxisX.CustomLabels.Add(new CustomLabel { FromPosition = 8, ToPosition = 9, Text = "8", GridTicks = GridTickTypes.All });
        Chart1.ChartAreas[0].AxisX.CustomLabels.Add(new CustomLabel { FromPosition = 9, ToPosition = 10, Text = "9", GridTicks = GridTickTypes.All });
        Chart1.ChartAreas[0].AxisX.CustomLabels.Add(new CustomLabel { FromPosition = 10, ToPosition = 11, Text = "10", GridTicks = GridTickTypes.All });
    }
}


问:
Kubernetes Cluster per app?
I have a two-cluster multi-region HA enabled in production working in MS Azure.

I was asked to reuse the same cluster to manage several new projects using Microservices.

What is the best practice here ? Should I create a cluster per app ? Is it better to isolate every project in different clusters and cloud account subcriptions?

Looking forward for opinions.

Thanks.

答:
I would suggest you slice and dice your cluster by using Namespaces.You can easily create a namespace by using the following command.

```<code>kubectl create namespace my-project
</code>```

Now you can feed your all manifest files (deployment, services, secrets, PersistentVolumeClaims) to API Server to that my-project namespace. for instance,

```<code>kubectl create -f my-deployment.yaml --namespace my-project
</code>```

Do not forget to use namespace flag otherwise these manifest would be applied to the default namespace.

If you want to delete your project. you just need to delete the namespace.It will delete all of the resources related to that project.

```<code>kubectl delete namespace my-project
</code>```

furthermore, You can limit the quota to each namespace for resources utilization.

you can further dig up with Namespace

Edited

Namespaces are virtual clusters in a physical cluster

Title: Kubernetes Cluster per app?

Body:
I would suggest you slice and dice your cluster by using Namespaces.You can easily create a namespace by using the following command.

kubectl create namespace my-project

Now you can feed your all manifest files (deployment, services, secrets, PersistentVolumeClaims) to API Server to that my-project namespace. for instance,

kubectl create -f my-deployment.yaml --namespace my-project

Do not forget to use namespace flag otherwise these manifest would be applied to the default namespace.

If you want to delete your project. you just need to delete the namespace.It will delete all of the resources related to that project.

kubectl delete namespace my-project

furthermore, You can limit the quota to each namespace for resources utilization.

you can further dig up with Namespace

Edited

Namespaces are virtual clusters in a physical cluster


问:
Python's request.get only show 200 status
I'm trying to workd with the Cisco Prime API, and it seems to work when using Postman (the output is an xml file). However, when I try to reproduce the same with Python:

```<code>request.get(url, verify=False, auth=credentials)
print(response)
</code>```

the only response I get is <Response [200]> (and a warning for disabling SSL, but that's not relevant)... I use requests.auth.HTTPBasicAuth to generate the "crdentials" variable

答:
You need to get with

```<code>print(response.json())
</code>```

Or

```<code>print(response.text)
</code>```

Body:
I'm trying to workd with the Cisco Prime API, and it seems to work when using Postman (the output is an xml file). However, when I try to reproduce the same with Python:

request.get(url, verify=False, auth=credentials)
print(response)

the only response I get is <Response [200]> (and a warning for disabling SSL, but that's not relevant)... I use requests.auth.HTTPBasicAuth to generate the "crdentials" variable

Body:
You need to get with

print(response.json())

Or

print(response.text)


问:
How to load partial razor page into razor view
I am trying to replace my view components with razor pages but it seems that it's not possible to load a partial razor page because a model is expected to be passed yet it is my understanding that the model for a razor page should be declared in the OnGetAsync method. Here is my code...

Razor Page

```<code>@page "{id:int}"
@model _BackgroundModel

<form method="POST">
    <div>Name: <input asp-for="Description" /></div>
    <input type="submit" />
</form>
</code>```

Razor Page Code-Behind

```<code>public class _BackgroundModel : PageModel
{
    private readonly IDataClient _dataClient;

    public _BackgroundModel(IDataClient dataClient)
    {
        _dataClient = dataClient;
    }

    [BindProperty]
    public BackgroundDataModel Background { get; set; }

    public async Task OnGetAsync(int id)
    {
        Background = await _dataClient.GetBackground(id);
    }

    public async Task OnPostAsync()
    {
        if (ModelState.IsValid)
        {
            await _dataClient.PostBackground(Background);
        }
    }

}
</code>```

Razor View

```<code><div class="tab-pane fade" id="client-background-tab">
    <div class="row">
        <div class="col-sm-12">
            @await Html.PartialAsync("/Pages/Client/_Background.cshtml", new { id = 1 })
        </div>
    </div>
</div>
</code>```

Page Load Error

InvalidOperationException: The model item passed into the
  ViewDataDictionary is of type '<>f__AnonymousType0`1[System.Int32]',
  but this ViewDataDictionary instance requires a model item of type
  'WebApp.Pages.Client._BackgroundModel'

In this example (as per MS recommended approach in their docs) the model is set inside the OnGetAsync method which should be run when the page is requested. I have also tried @await Html.RenderPartialAsync("/Pages/Client/_Background.cshtml", new { id = 1 }) but the same error result.

How can I load the razor page into my existing view?

答:
Microsoft confirmed this cannot be achieved and therefore razor pages cannot be used as a replacement for view components.

See the comments of their docs...

MS docs

@RickAndMSFT moderator15 hours ago
  @OjM You can redirect to the page, or you can make the core view >code into a partial and call it from both.

Pages are not a replacement for partials or View Components.

Body:
I am trying to replace my view components with razor pages but it seems that it's not possible to load a partial razor page because a model is expected to be passed yet it is my understanding that the model for a razor page should be declared in the OnGetAsync method. Here is my code...

Razor Page

@page "{id:int}"
@model _BackgroundModel

<form method="POST">

Name: <input asp-for="Description" />

    <input type="submit" />
</form>

Razor Page Code-Behind

public class _BackgroundModel : PageModel
{
    private readonly IDataClient _dataClient;

    public _BackgroundModel(IDataClient dataClient)
    {
        _dataClient = dataClient;
    }

    [BindProperty]
    public BackgroundDataModel Background { get; set; }

    public async Task OnGetAsync(int id)
    {
        Background = await _dataClient.GetBackground(id);
    }

    public async Task OnPostAsync()
    {
        if (ModelState.IsValid)
        {
            await _dataClient.PostBackground(Background);
        }
    }

}

Razor View

            @await Html.PartialAsync("/Pages/Client/_Background.cshtml", new { id = 1 })

Page Load Error

InvalidOperationException: The model item passed into the
  ViewDataDictionary is of type '<>f__AnonymousType0`1[System.Int32]',
  but this ViewDataDictionary instance requires a model item of type
  'WebApp.Pages.Client._BackgroundModel'

In this example (as per MS recommended approach in their docs) the model is set inside the OnGetAsync method which should be run when the page is requested. I have also tried @await Html.RenderPartialAsync("/Pages/Client/_Background.cshtml", new { id = 1 }) but the same error result.

How can I load the razor page into my existing view?


问:
How to unit test an expression?
I have looked at a few posts such as this one but it doesn't answer my question.

Basically I have use LINQKIT to build an expression which looks like this:

```<code>public Expression<Func<uv_Manifest, bool>> CreateManifestFilters(ManifestFilterItem filterItem)
{
    var predicate = PredicateBuilder.New<uv_Manifest>;

        if(!string.IsNullorWhiteSpace(filterItem.CID)){
        predicate = predicate.And(x => x.CID == filterItem.CID && x.CID != null);
        }

    return predicate;
}
</code>```

And I have a unit tests which looks like this:

```<code>[TestMethod()]
public void CreateManifestFilters_FunctionHitWithCIDPopulated_ExpressionWillContainWhereOnCID()
{
    var filterItem = new ManifestFilterItem("002");
    var predicate = PredicateBuilder.New<uv_Manifest>.And(x => x.CID == filterItem.CID && x.CID != null);

    var result = _iManifestManager.CreateManifestFilters(filterItem);

    var manifest = new uv_Manifest();

    Assert.AreEqual(predicate, result);

}
</code>```

What I am trying to do is check that the expression is doing a where on the property CID. However I get this error when the test fails:

Assert.AreEqual failed. Expected: ((CompareString(x.CID, value(FSVendor_Refactored.Tests.ManifestFixture+_Closure$__11-0).$VB$Local_filterItem.CID, False) == 0) AndAlso (Convert(x.CID) != null))>. Actual: ((CompareString(x.CID, value(FSVendor_RefactoredRepository.ManifestManager+_Closure$__2-0).$VB$Local_filterItem.CID, False) == 0) AndAlso (Convert(x.CID) != null))>.

I think I understand why it's failing, both the unit tests and CreateManifestFilters function are in different projects. So I believe that this is causing the test to fail.

Anyone know how to check the expression to check if it's doing a where on the CID property?

EDIT: This is NOT a duplicate as the other answer does not use PredicateBuilder therefore the linked answer doesn't suit my requirements.

答:
What I am trying to do is check that the expression is doing a where on the property CID.

  ...

  Anyone know how to check the expression to check if it's doing a where on the CID property?

Yes, I can think of a few ways. The easiest is probably to compile the expression and test it.

```<code>[TestMethod()]
public void CreateManifestFilters_FunctionHitWithCIDPopulated_ExpressionFiltersOnCID()
{
    var filterItem = new ManifestFilterItem("002");
    var predicate = _iManifestManager.CreateManifestFilters(filterItem);
    var predicateFunc = predicate.Compile();
    var manifest1 = new uv_Manifest{ CID = "001" };
    var manifest2 = new uv_Manifest{ CID = "002" };

    var result1 = predicateFunc(manifest1);
    var result2 = predicateFunc(manifest2);

    Assert.IsFalse(result1);
    Assert.IsTrue(result2);
}
</code>```

Hey, I'm not trying to unit test the results of the expression.

Why not? You specifically said you wanted to check that the expression is doing a WHERE on the CID property. Is the behavior of the expression not as important as knowing you hit the if block? In that case, it may be more appropriate to have another injected service providing the CID-checking expression so you can unit-test this method by mocking that service. But that seems like overkill to me.

Another option, if you just want to make sure that something CID-related is on that expression, is to ToString() the expression and look for a specific substring, like "filterItem.CID" in that string.

This is NOT a duplicate as the other answer does not use PredicateBuilder therefore the linked answer doesn't suit my requirements.

Actually, if you're really trying to just do an equality comparison between two expression trees, as you indicate in your code sample, then it doesn't matter how you generate the expressions. If they're equivalent, then the other answer's expression checker should work just fine.

Title: How to unit test an expression?

Body:
I have looked at a few posts such as this one but it doesn't answer my question.

Basically I have use LINQKIT to build an expression which looks like this:

public Expression<Func<uv_Manifest, bool>> CreateManifestFilters(ManifestFilterItem filterItem)
{
    var predicate = PredicateBuilder.New<uv_Manifest>;

        if(!string.IsNullorWhiteSpace(filterItem.CID)){
        predicate = predicate.And(x => x.CID == filterItem.CID && x.CID != null);
        }

    return predicate;
}

And I have a unit tests which looks like this:

[TestMethod()]
public void CreateManifestFilters_FunctionHitWithCIDPopulated_ExpressionWillContainWhereOnCID()
{
    var filterItem = new ManifestFilterItem("002");
    var predicate = PredicateBuilder.New<uv_Manifest>.And(x => x.CID == filterItem.CID && x.CID != null);

    var result = _iManifestManager.CreateManifestFilters(filterItem);

    var manifest = new uv_Manifest();

    Assert.AreEqual(predicate, result);

}

What I am trying to do is check that the expression is doing a where on the property CID. However I get this error when the test fails:

Assert.AreEqual failed. Expected: ((CompareString(x.CID, value(FSVendor_Refactored.Tests.ManifestFixture+_Closure$__11-0).$VB$Local_filterItem.CID, False) == 0) AndAlso (Convert(x.CID) != null))>. Actual: ((CompareString(x.CID, value(FSVendor_RefactoredRepository.ManifestManager+_Closure$__2-0).$VB$Local_filterItem.CID, False) == 0) AndAlso (Convert(x.CID) != null))>.

I think I understand why it's failing, both the unit tests and CreateManifestFilters function are in different projects. So I believe that this is causing the test to fail.

Anyone know how to check the expression to check if it's doing a where on the CID property?

EDIT: This is NOT a duplicate as the other answer does not use PredicateBuilder therefore the linked answer doesn't suit my requirements.

Body:
What I am trying to do is check that the expression is doing a where on the property CID.

  ...

  Anyone know how to check the expression to check if it's doing a where on the CID property?

Yes, I can think of a few ways. The easiest is probably to compile the expression and test it.

[TestMethod()]
public void CreateManifestFilters_FunctionHitWithCIDPopulated_ExpressionFiltersOnCID()
{
    var filterItem = new ManifestFilterItem("002");
    var predicate = _iManifestManager.CreateManifestFilters(filterItem);
    var predicateFunc = predicate.Compile();
    var manifest1 = new uv_Manifest{ CID = "001" };
    var manifest2 = new uv_Manifest{ CID = "002" };

    var result1 = predicateFunc(manifest1);
    var result2 = predicateFunc(manifest2);

    Assert.IsFalse(result1);
    Assert.IsTrue(result2);
}

Hey, I'm not trying to unit test the results of the expression.

Why not? You specifically said you wanted to check that the expression is doing a WHERE on the CID property. Is the behavior of the expression not as important as knowing you hit the if block? In that case, it may be more appropriate to have another injected service providing the CID-checking expression so you can unit-test this method by mocking that service. But that seems like overkill to me.

Another option, if you just want to make sure that something CID-related is on that expression, is to ToString() the expression and look for a specific substring, like "filterItem.CID" in that string.

This is NOT a duplicate as the other answer does not use PredicateBuilder therefore the linked answer doesn't suit my requirements.

Actually, if you're really trying to just do an equality comparison between two expression trees, as you indicate in your code sample, then it doesn't matter how you generate the expressions. If they're equivalent, then the other answer's expression checker should work just fine.


问:
Uber Api History Data Ordering
The get history api documentation does not specify whether the data returned is ordered from the latest trip time . The example data here looks like it is ordered from latest:

https://developer.uber.com/docs/riders/references/api/v1.2/history-get

But my application has a hard dependency on being able to fetch a sample of the latest trips.

Can anyone confirm whether or not this is guaranteed?

答: History endpoint supposes to return data in descending order - so the latest trips will be displayed first. But you can sort the data on your side how you prefer - you don't need to relay in response you are getting back from the endpoint. It is trivial to sort the list/collection of data - there are many samples how to do it on SO in any programing language you are using. </p>

Title: Uber Api History Data Ordering


问:
react native how to get return from a promise
my problem is i want to get a json from this function but all i get is a only a promise and why i choose this way because in app that i'm working on it works dynamicly but the only place that i see i can put this promise is render()

this is my code :

```<code>var userInfo = (async()=>{
    var value = await AsyncStorage.getItem("@user_info");
    value = JSON.parse(value);
    return value ;
  })();
</code>```

and this is my result :

```<code>Promise {
 "_40": 0,
 "_55": null,
 "_65": 0,
 "_72": null,
}
</code>```

but what i want to get is a json what sould i have to do ?

答:
You have to call this function from componentDidMount and after the promise completes, call setState.

Here is a canonical example of how to do this:

```<code>class User extends React.Component {
  state = { user: null };

  render() {
     return this.state.user && <div>{this.state.user.name}</div>;
  }

  async componentDidMount() {
    const value = await AsyncStorage.getItem("@user_info");
    if (!this._unmounted) {
      const user = JSON.parse(value);
      this.setState({ user: user });
    }
  }

  componentWillUnmount() {
    this._unmounted = true;
  }
}
</code>```

Body:
my problem is i want to get a json from this function but all i get is a only a promise and why i choose this way because in app that i'm working on it works dynamicly but the only place that i see i can put this promise is render()

this is my code :

var userInfo = (async()=>{
    var value = await AsyncStorage.getItem("@user_info");
    value = JSON.parse(value);
    return value ;
  })();

and this is my result :

Promise {
 "_40": 0,
 "_55": null,
 "_65": 0,
 "_72": null,
}

but what i want to get is a json what sould i have to do ?

Body:
You have to call this function from componentDidMount and after the promise completes, call setState.

Here is a canonical example of how to do this:

class User extends React.Component {
  state = { user: null };

  render() {
     return this.state.user && <div>{this.state.user.name}</div>;
  }

  async componentDidMount() {
    const value = await AsyncStorage.getItem("@user_info");
    if (!this._unmounted) {
      const user = JSON.parse(value);
      this.setState({ user: user });
    }
  }

  componentWillUnmount() {
    this._unmounted = true;
  }
}


问:
Decimal to Binary
I have a number that I would like to convert to binary (from decimal) in C.

I would like my binary to always be in 5 bits (the decimal will never exceed 31). I already have a function that does it manually by dividing but that is hard to pad it to 5 bits.

Is there any easier way? Perhaps using bitwise shift?

I would also like the binary to be represented in a char *

答:
```<code>#include "stdio.h"
#include "conio.h"

int main(void)
{
int i, d , n = 1;
int store[10];

printf("Please enter a number to be converted to binary:\n");
scanf("%d",&d);

for (i=0;i<8 ;i++ )
  store[i] = 0;

i = 0;

do{
if(d & n ){
    n <<= 1;  //10
    store[i] = 1;
    i++;
}
else {
    n <<= 1;
    store[i] = 0;
    i++;
}

}while(n <= d);

printf("\n");
for (i=7;i>=0 ;i-- ){
  printf("%d",store[i]);
if(i == 4)
    printf(" ");
}
printf("\n");
return 0;
}
</code>```

Title: Decimal to Binary


问:
Google Sheets tab color for conditional formatting
I'm trying to use the tab color to conditionally format a cell.  I've got a custom function that returns all the tabs from my spreadsheet:

```<code>function STABS() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var stabs = [];

for (i = 0; i < ss.getNumSheets(); i++) {
stabs.push(ss.getSheets()[i].getName());
}
</code>```

Some of these tabs are colored as a visual cue to our workflow.  I would like to have the cell highlighted the same color as the tab.

Any help would be greatly appreciated.

Thanks,

Lynn

答:
To get the color of the tab in the script you can use the getTabColor() function for the Sheet class.

See the Sheet API here

The you can use functions like setBackgroundColor() for a range to set the formatting.

See the Range API here

Body:
I'm trying to use the tab color to conditionally format a cell.  I've got a custom function that returns all the tabs from my spreadsheet:

function STABS() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var stabs = [];

for (i = 0; i < ss.getNumSheets(); i++) {
stabs.push(ss.getSheets()[i].getName());
}

Some of these tabs are colored as a visual cue to our workflow.  I would like to have the cell highlighted the same color as the tab.

Any help would be greatly appreciated.

Thanks,

Lynn


问:
Attempting to install SQL Server 2008 somewhere other than the C:\ drive
I'm trying to install SQL Server 2008 Management Studio on a Microsoft Windows Server 2003 machine, however I do not have enough space on the C:\ partition, so I'd like to install it on the D:\ partition.  When I go through the installation, the install path is grayed-out.  Some people have said that you have to uninstall any previous versions of SQL Server, which I did but to no avail.  Anyone have any suggestions on how to get Management Studio installed on a different partition or how to edit this seemingly read-only field during the installation?

Thanks in advance

答: Even though you uninstalled the previous versions, did you clear the registry entries? Those could keep you from changing the installation directory.</p>


问:
List organization by file name in R
I'm trying to create a list of data separated by month and year (40 years worth).  The data currently has the name structure (Year)-(Numeric Month)-(Var).nc. I'd like to get all the data into its appropriate list created below.  Not exactly sure how to proceed from here.  Any guidance is appreciated.</p>

```<code>files_nc <- list.files(pattern = ".nc")

year <- vector("list", length = 40)
month <- vector("list", length = 12)

names(year) <- c(1978:2017)
names(month) <- c("Jan","Feb","Mar","Apr","May","Jun","Jul",
   "Aug","Sep","Oct","Nov","Dec")

for (i in 1:40) {
   year[[i]] <- month
}
</code>```

答:
It's not entirely clear what you're asking for, but I believe this should work.  I'm assuming you're loading in a list of files, and each file is associated with a year and month.

```<code>file_names <- list(names(files_nc))

file_names_split <- lapply(file_names,function(x)strsplit(x,"-"))

for(i in 1:length(file_names_split)) {

  y <- which(names(year) == file_names_split[[i]][[1]][1])
  m <- as.numeric(file_names_split[[i]][[1]][2])

  year[[y]][m] <- files_nc[[i]]

}
</code>```

In general, this method should work.  If it works I'd take the time to rewrite the for loop as an apply statement.

Title: List organization by file name in R

Body:
I'm trying to create a list of data separated by month and year (40 years worth).  The data currently has the name structure (Year)-(Numeric Month)-(Var).nc. I'd like to get all the data into its appropriate list created below.  Not exactly sure how to proceed from here.  Any guidance is appreciated.

files_nc <- list.files(pattern = ".nc")

year <- vector("list", length = 40)
month <- vector("list", length = 12)

names(year) <- c(1978:2017)
names(month) <- c("Jan","Feb","Mar","Apr","May","Jun","Jul",
   "Aug","Sep","Oct","Nov","Dec")

for (i in 1:40) {
   year[[i]] <- month
}

Body:
It's not entirely clear what you're asking for, but I believe this should work.  I'm assuming you're loading in a list of files, and each file is associated with a year and month.

file_names <- list(names(files_nc))

file_names_split <- lapply(file_names,function(x)strsplit(x,"-"))

for(i in 1:length(file_names_split)) {

  y <- which(names(year) == file_names_split[[i]][[1]][1])
  m <- as.numeric(file_names_split[[i]][[1]][2])

  year[[y]][m] <- files_nc[[i]]

}

In general, this method should work.  If it works I'd take the time to rewrite the for loop as an apply statement.


问:
Parse query with no current user
I have a working app on android and IOS.

The first activity on both is a log in screen.
The second activity is a search function that allows you to find nearby users using parse.

However I am trying the make the app allow users to search without having to login.

This was easy to do with IOS.

In android I have changed my startup activity to activity 2 (the search activity) in the manifest file and it loads fine but obviously there is no current user.

When I try to run the query now, the app just stalls and in the debugger it says the user is null. I am guessing this is the problem here.

So I then tried to create an anonous user in the oncreate method using the lines..

```<code>  ParseAnonymousUtils.logIn(new LogInCallback() {
        @Override
        public void done(ParseUser user, ParseException e) {
            if (e != null) {
                Log.d("MyApp", "Anonymous login failed.");
            } else {
                Log.d("MyApp", "Anonymous user logged in.");
            }
        }
    });
</code>```

This then fails with the message

java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.File com.parse.ParsePlugins.getParseDir()' on a null object reference at com.parse.Parse.getParseDir(Parse.java:499)

Oddly enough though. This bit of code does work if i put it in activity 1, but the app then gets stuck when it tries to launch activity 2.

Does anyone know what is happening? Or how I can solve my original original problem?

Thanks

答:
This error appears when Parse is not initialized. I'm guessing you put your Parse.initialize() code in your activity. When you go to another one, the initialization is lost. You need to extend your Application class so that it holds a single initialization for the whole app.

```<code>public class Application extends android.app.Application {

    @Override
    public void onCreate() {
        super.onCreate();
        Parse.initialize(new Parse.Configuration.Builder(this)
                .applicationId("id")
                .clientKey("key")
                .server("server")
                .enableLocalDataStore()
                .build()
        );
        ParseUser.enableAutomaticUser();
   }
}
</code>```

And this in your AndroidManifest.xml

```<code><application
        android:name=".Application"
        android:allowBackup="true"
        android:icon="@drawable/logo"
        android:label="@string/app_name"
        android:theme="@style/AppTheme">
</code>```

Title: Parse query with no current user

Body:
I have a working app on android and IOS.

The first activity on both is a log in screen.
The second activity is a search function that allows you to find nearby users using parse.

However I am trying the make the app allow users to search without having to login.

This was easy to do with IOS.

In android I have changed my startup activity to activity 2 (the search activity) in the manifest file and it loads fine but obviously there is no current user.

When I try to run the query now, the app just stalls and in the debugger it says the user is null. I am guessing this is the problem here.

So I then tried to create an anonous user in the oncreate method using the lines..

  ParseAnonymousUtils.logIn(new LogInCallback() {
        @Override
        public void done(ParseUser user, ParseException e) {
            if (e != null) {
                Log.d("MyApp", "Anonymous login failed.");
            } else {
                Log.d("MyApp", "Anonymous user logged in.");
            }
        }
    });

This then fails with the message

java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.File com.parse.ParsePlugins.getParseDir()' on a null object reference at com.parse.Parse.getParseDir(Parse.java:499)

Oddly enough though. This bit of code does work if i put it in activity 1, but the app then gets stuck when it tries to launch activity 2.

Does anyone know what is happening? Or how I can solve my original original problem?

Thanks

Body:
This error appears when Parse is not initialized. I'm guessing you put your Parse.initialize() code in your activity. When you go to another one, the initialization is lost. You need to extend your Application class so that it holds a single initialization for the whole app.

public class Application extends android.app.Application {

    @Override
    public void onCreate() {
        super.onCreate();
        Parse.initialize(new Parse.Configuration.Builder(this)
                .applicationId("id")
                .clientKey("key")
                .server("server")
                .enableLocalDataStore()
                .build()
        );
        ParseUser.enableAutomaticUser();
   }
}

And this in your AndroidManifest.xml

<application
        android:name=".Application"
        android:allowBackup="true"
        android:icon="@drawable/logo"
        android:label="@string/app_name"
        android:theme="@style/AppTheme">


问:
Unable to change image size proportionally
I am building an interactive website where the main image is a camera with buttons to operate it. I want to place buttons on it for the user to click on. I am able to position it just fine at full width, and when I resize smaller for a phone the camera resizes beautifully. On the other hand, the About button never moves or resizes it just stays in place.

HTML:

```<code><div class="camera">
  <div id="about_pos">
     <div id="about">

     </div>
 </div>
</div>
</code>```

CSS:

```<code>.camera {
position: relative;
width: 100%;
height: 100%;
background-image: url('../images/camera.png');
background-repeat: no-repeat;
background-size: contain;
background-position: center;
}

#about {
  display: block;
  width: 55px;
  height: 55px;
  background-image: url('../images/about_bw.png');
  background-repeat: no-repeat;
}

#about:hover {
  background-image: url('../images/about.png');
}

#about_pos{
    float: left;
    padding-left: 128px;
    padding-top: 77px;
}
</code>```

From what I have seen on the internet it appears that my mistake is forcing the button to a specific height and width, but that is where the real problem comes in. When I try setting them to either auto or 100% I lose the image all together.

I feel like I have tried every scenario out there and none of them work. Any thoughts on this would be greatly appreciated.

I marked the below as the answer but the rest of the answer is found at bottom in the comments section.

Here is the final code:

HTML

```<code>     <div class="camera">
       <div class="buttons" id="about">

       </div>
    </div>
</code>```

CSS

```<code>.camera {
position: relative;
width: 100%;
height: 100%;
background-image: url('images/camera_with_buttons.png');
background-repeat: no-repeat;
background-size: 90%;
background-position: center top;
}

.buttons{
display: block;
width: 4vw;
height: 4vw;
margin-left: 1vw;
margin-top: 1vw;

border-radius: 50%;
position: absolute;
}

#about {
top: 5.6vw;
left: 6.2vw;
}

#about:hover {
background-size: cover;
background-image: url('images/about.png');
background-repeat: no-repeat;
}
</code>```

答:
Make use of relative positioning that you already have on .camera and add position: absolute on #about_pos. Use percentages or viewport units (vh and vw) to position it (eg. top: 30% or if the button's vertical position is relative to the width of .camera you can use top: 25vw).

Also remove float from the about_pos div and you can keep the dimensions of a button in px since you are doing positioning with absolute div parent, about_pos.

Update

In order to resize the button in response to changing screen width, use width: 7vw; height: 3vw; or similar

Update 2

You can remove #about_pos and do it simpler, like this:

body {
    padding: 0;
    margin: 0;
}

.camera {
    position: relative;
    width: 100%;
    height: 100%;
    background-image: url('http://www.kenrockwell.com/nikon/d800/d800-back-1200.jpg');
    background-repeat: no-repeat;
    background-size: 100%;
    background-position: center top;
}

#about {
    display: block;
    width: 8vw;
    height: 8vw;
    margin-left: -4vw;
    margin-top: -4vw;
    border-radius: 50%;
    background: orange;
    position: absolute;
    top: 23.5vw;
    left: 71.6vw;
    opacity: 0.7;
    cursor: pointer;
}

#about:hover {
    background: yellow;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
    <div class="camera">
        <div id="about">

        </div>
    </div>
</body></code>```

Body:
I am building an interactive website where the main image is a camera with buttons to operate it. I want to place buttons on it for the user to click on. I am able to position it just fine at full width, and when I resize smaller for a phone the camera resizes beautifully. On the other hand, the About button never moves or resizes it just stays in place.

HTML:

CSS:

.camera {
position: relative;
width: 100%;
height: 100%;
background-image: url('../images/camera.png');
background-repeat: no-repeat;
background-size: contain;
background-position: center;
}

#about {
  display: block;
  width: 55px;
  height: 55px;
  background-image: url('../images/about_bw.png');
  background-repeat: no-repeat;
}

#about:hover {
  background-image: url('../images/about.png');
}

#about_pos{
    float: left;
    padding-left: 128px;
    padding-top: 77px;
}

From what I have seen on the internet it appears that my mistake is forcing the button to a specific height and width, but that is where the real problem comes in. When I try setting them to either auto or 100% I lose the image all together.

I feel like I have tried every scenario out there and none of them work. Any thoughts on this would be greatly appreciated.

I marked the below as the answer but the rest of the answer is found at bottom in the comments section.

Here is the final code:

HTML

CSS

.camera {
position: relative;
width: 100%;
height: 100%;
background-image: url('images/camera_with_buttons.png');
background-repeat: no-repeat;
background-size: 90%;
background-position: center top;
}

.buttons{
display: block;
width: 4vw;
height: 4vw;
margin-left: 1vw;
margin-top: 1vw;

border-radius: 50%;
position: absolute;
}

#about {
top: 5.6vw;
left: 6.2vw;
}

#about:hover {
background-size: cover;
background-image: url('images/about.png');
background-repeat: no-repeat;
}

Body:
Make use of relative positioning that you already have on .camera and add position: absolute on #about_pos. Use percentages or viewport units (vh and vw) to position it (eg. top: 30% or if the button's vertical position is relative to the width of .camera you can use top: 25vw).

Also remove float from the about_pos div and you can keep the dimensions of a button in px since you are doing positioning with absolute div parent, about_pos.

Update

In order to resize the button in response to changing screen width, use width: 7vw; height: 3vw; or similar

Update 2

You can remove #about_pos and do it simpler, like this:

body {
    padding: 0;
    margin: 0;
}

.camera {
    position: relative;
    width: 100%;
    height: 100%;
    background-image: url('http://www.kenrockwell.com/nikon/d800/d800-back-1200.jpg');
    background-repeat: no-repeat;
    background-size: 100%;
    background-position: center top;
}

#about {
    display: block;
    width: 8vw;
    height: 8vw;
    margin-left: -4vw;
    margin-top: -4vw;
    border-radius: 50%;
    background: orange;
    position: absolute;
    top: 23.5vw;
    left: 71.6vw;
    opacity: 0.7;
    cursor: pointer;
}

#about:hover {
    background: yellow;
}

<body>
    <div class="camera">
        <div id="about">

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


问:
Specifying CSS stack order without using z-index
I am wondering if either of the following are possible:

Is there a way to use z-index without specifying the position attribute for an element.

Is there any way to specify the CSS stack order for elements without using either the z-index property or the position attribute

答:
(1) No. see the CSS specs:

For a positioned box, the 'z-index'
  property specifies:

     1. The stack level ...

Each positioned box in a given
  stacking context has an integer stack
  level.

(2) No. the CSS stack order is the z-index