问:
How are gradients calculated for DeepDream
I have a very simple implementation of Deep Dream algorithm inspired by kadenze example https://github.com/pkmital/CADL/blob/master/session-4/lecture-4.ipynb:

```<code>layer = graph.get_tensor_by_name('inception/output2:0')
layer_size = layer.eval({x: img_4d}).shape

neuron_i = 110

layer_activation = np.zeros(layer_size)
layer_activation[..., neuron_i] = 1

grad = tf.gradients(layer[..., neuron_i], x)[0]

img_noise_4d = img_noise.copy()[np.newaxis]
img_noise_4d /=  255.0

grad_step = 4.0
n_steps = 100
for step in range(n_steps):
    print(step, end=', ')
    res = grad.eval({layer: layer_activation, x: img_noise_4d})
    res /= (np.max(np.abs(res)) + 1e-8)
    img_noise_4d += res * grad_step

plt.imshow(normalize(img_noise_4d[0]))
</code>```

What I can't understand is how it works - I mean how can we replace actual layer activation with one which we generated (layer_activation) and get a correct gradient?

I made a simple experiment:

```<code>x = tf.Variable(3.0)
y = x**2

session = tf.InteractiveSession()
session.run(tf.global_variables_initializer())

session.run(tf.gradients(y, x)[0], {y: 100})
</code>```

Whatever I substitute as y - I always get correct gradient for x in point 3.0 which is 6.0. I understand that I'm missing something, but what exactly?

答:
I think I can answer my question now - it turns out I had a bad example.

This answer better shows how this works:

```<code>x = tf.Variable(3.0)
w = tf.Variable([6.0, 2.0])
y = x * w

session = tf.InteractiveSession()
session.run(tf.global_variables_initializer())

session.run(
    tf.gradients(tf.reduce_max(y), x)[0],
    {y: [3, 9],
})
</code>```

So basically by passing custom y to session.run we can suggest to back propagation algorithm which 'neuron' we expect to be the max one - and thus it will calculate gradient w.r.t. not actual one (y[0]), but to custom one (y[1]).

We can do even simpler if we know what particular neuron we are interested in:

```<code>session.run(
    tf.gradients(y[1], x)[0],
)
</code>```

Body:
I have a very simple implementation of Deep Dream algorithm inspired by kadenze example https://github.com/pkmital/CADL/blob/master/session-4/lecture-4.ipynb:

layer = graph.get_tensor_by_name('inception/output2:0')
layer_size = layer.eval({x: img_4d}).shape

neuron_i = 110

layer_activation = np.zeros(layer_size)
layer_activation[..., neuron_i] = 1

grad = tf.gradients(layer[..., neuron_i], x)[0]

img_noise_4d = img_noise.copy()[np.newaxis]
img_noise_4d /=  255.0

grad_step = 4.0
n_steps = 100
for step in range(n_steps):
    print(step, end=', ')
    res = grad.eval({layer: layer_activation, x: img_noise_4d})
    res /= (np.max(np.abs(res)) + 1e-8)
    img_noise_4d += res * grad_step

plt.imshow(normalize(img_noise_4d[0]))

What I can't understand is how it works - I mean how can we replace actual layer activation with one which we generated (layer_activation) and get a correct gradient?

I made a simple experiment:

x = tf.Variable(3.0)
y = x**2

session = tf.InteractiveSession()
session.run(tf.global_variables_initializer())

session.run(tf.gradients(y, x)[0], {y: 100})

Whatever I substitute as y - I always get correct gradient for x in point 3.0 which is 6.0. I understand that I'm missing something, but what exactly?

Body:
I think I can answer my question now - it turns out I had a bad example.

This answer better shows how this works:

x = tf.Variable(3.0)
w = tf.Variable([6.0, 2.0])
y = x * w

session = tf.InteractiveSession()
session.run(tf.global_variables_initializer())

session.run(
    tf.gradients(tf.reduce_max(y), x)[0],
    {y: [3, 9],
})

So basically by passing custom y to session.run we can suggest to back propagation algorithm which 'neuron' we expect to be the max one - and thus it will calculate gradient w.r.t. not actual one (y[0]), but to custom one (y[1]).

We can do even simpler if we know what particular neuron we are interested in:

session.run(
    tf.gradients(y[1], x)[0],
)


来源: stackexchange

问:
SQL Querying Help/IF Conditional Statement
So I am creating a booking table. I have two drop down lists called Date and Time and the data for these is being retrieved from a table called "DateTime" with a field called Date with a load of dates in it and same with time.

This booking system is booking time and a date with a Doctor. I'm lost at this point in terms of how do I get times to only appear for a doctor that the user wants to choose an appointment with to avoid double bookings. If a user has booked 9:15am on a certain date, I don't want that time to appear for another user for that date and doctor.

UPDATE Once a user has selected their date time and doctor, this is stored in a table called Booking. So i was originally going to delete that time and date out of that DateTime but this will then  not appear for another doctor if selected.

HELP PLEASE. :'(

答:
You can do that with a query without deleting data from your DateTime table.

```<code>    SELECT dt.[Date], dt.[Time], dt.Doctor
    FROM dbo.[DateTime] dt
    WHERE NOT EXISTS (  SELECT 1
                        FROM dbo.Booking b
                        WHERE
                            b.[Date] = dt.[Date]
                            AND b.[Time] = dt.[Time]
                            AND b.Doctor = dt.Doctor)
</code>```

The query selects all the dates and times that does not currently exist in your booking table.

Hope this helps.

Marius

ContentLicense: CC BY-SA 3.0

Body:
You can do that with a query without deleting data from your DateTime table.

    SELECT dt.[Date], dt.[Time], dt.Doctor
    FROM dbo.[DateTime] dt
    WHERE NOT EXISTS (  SELECT 1
                        FROM dbo.Booking b
                        WHERE
                            b.[Date] = dt.[Date]
                            AND b.[Time] = dt.[Time]
                            AND b.Doctor = dt.Doctor)

The query selects all the dates and times that does not currently exist in your booking table.

Hope this helps.

Marius


问:
Salt Length To Total Hash Length Ratio
I'm using KeyDerivation.Pbkdf2 to generate password hashes, and I was wondering what the general advice is regarding the salt length compared to the overall hash length that Pbkdf2 outputs.

In the implementation below, I'm using HMACSHA512, and assume that the salt is 512 bits, and that the hashBitLength is also 512 bits.

```<code>KeyDerivation.Pbkdf2(password, salt, KeyDerivationPrf.HMACSHA512, iterationCount, hashBitLength / 8);
</code>```

I've seen an example which uses HMACSHA256, but it has the salt set to 128 bits and the overall hash bit length to 256.
Why would this approach be taken?

I've read that 512 bits is probably overkill, but in terms of storage, it doesn't concern me (I'm not sure how performance is impacted though, I haven't measured that).

Should the salt be the same length as the overall resulting hash.
Should it be half?
Or should it be anything above a certain threshold and below the overall length?

My gut says the way I'm doing it is correct (Aside from perhaps the 512 bit) as I suspect I'm getting maximum entropy, but I'm no cryptographer.

Could someone please clarify this for me?

答:
It really does not need to be that big, but let's understand why.  The purpose of the salt is:

If two people have the same passwords, then the 'hashed' result should not be the same.

Prevent rainbow table attacks.

The first point can be accomplished by simply using a counter -- at least that prevents duplicates from your own database, but it might not prevent a hash of the password in your database from being the same as the hash of the same password in somebody else's database.  That brings us to the second point.

If one simply used a counter starting from zero, then one could construct a rainbow table based upon it.  The larger the salt, the more enormous that rainbow table would have to be to have a chance at being effective.  These tables grow exponentially with the salt size, so your salt really does not have to be that big to rule out this attack.

It's hard to point out exactly a minimum size, but I can assure you that 128-bits is more than enough.  I personally, as a security code auditor, would certainly not raise an issue with a salt as little as 64-bits.

One of the big problems with security advice on this topic is that nobody has ever analysed it -- instead you just get blind recommendations from people who claim to be experts.  I wrote a paper on password processing making exactly this point.  Specifically see section 3 for my rant about salt.

Remark: to rule out rainbow tables altogether, don't use a counter.  Instead, choose your salts 'large enough' (as above) and in an unpredictable way.

Title: Salt Length To Total Hash Length Ratio

Body:
I'm using KeyDerivation.Pbkdf2 to generate password hashes, and I was wondering what the general advice is regarding the salt length compared to the overall hash length that Pbkdf2 outputs.

In the implementation below, I'm using HMACSHA512, and assume that the salt is 512 bits, and that the hashBitLength is also 512 bits.

KeyDerivation.Pbkdf2(password, salt, KeyDerivationPrf.HMACSHA512, iterationCount, hashBitLength / 8);

I've seen an example which uses HMACSHA256, but it has the salt set to 128 bits and the overall hash bit length to 256.
Why would this approach be taken?

I've read that 512 bits is probably overkill, but in terms of storage, it doesn't concern me (I'm not sure how performance is impacted though, I haven't measured that).

Should the salt be the same length as the overall resulting hash.
Should it be half?
Or should it be anything above a certain threshold and below the overall length?

My gut says the way I'm doing it is correct (Aside from perhaps the 512 bit) as I suspect I'm getting maximum entropy, but I'm no cryptographer.

Could someone please clarify this for me?


问:
Spring Websocket in a tomcat cluster
In our current application, we use Spring Websockets over STOMP. We are looking to scale horizontally. Are there any best practices on how we should handle websocket traffic over multiple tomcat instances and how can we maintain session info across multiple nodes.Is there a working sample that one can refer to?</p>

答:
Horizontally scaling WebSockets is actually very different than horizontally scaling stateless/stateful HTTP only based applications.

Horizontally Scaling Stateless HTTP app: just spin up some application instances in different machines and put a load balancer in front of them. There are quite a lot different load balancer solutions such as HAProxy, Nginx, etc. If you are on a cloud environment such as AWS you could also have managed solutions such as Elastic Load Balancer.

Horizontally Scaling Stateful HTTP app: it would be great if we could have all applications being stateless everytime, but unfortunately that's not always possible. So, when dealing with stateful HTTP apps, you must care about the HTTP session, which is a basically a local storage for each different client where the web server can store data that is kept across different HTTP requests (such as when dealing with a Shopping Cart). Well, in this case, when scaling horizontally you should be aware that, as I said, it's a LOCAL storage, so ServerA will not be able to handle an HTTP session that is on ServerB. In other words, if for any reason Client1 that is being served by ServerA starts suddenly to be served by ServerB, his HTTP session will be lost (and his shopping cart will be gone!). The reasons could be a node failure or even a deployment.
In order to address this issue, you can't keep HTTP sessions only locally, that is, you must store them on another external component. That are several components that would be able to handle this, such as any relational database, but that would be actually an overhead. Some NoSQL databases can handle this key-value behavior very well, such as Redis.
Now, with the HTTP session being stored on Redis, if a client starts to be served by another server, it will fetch the client's HTTP session from Redis and load it into its memory, so everything will continue working and the user will not lost his HTTP session anymore.
You can use Spring Session to easily store the HTTP session on Redis.

Horizontally Scaling WebSocket app: When a WebSocket connection is established, the server must keep the connection opened with the client so that they can exchange data in both directions. When a client is listening to a destination such as "/topic/public.messages" we say the client is subscribed to this destination. In Spring, when you use the simpleBroker approach, the subscriptions are kept in memory, so what happens for instance if Client1 is being served by ServerA and wants to send a message using WebSocket to Client2 being served by ServerB? You already know the answer! The message will not be delivered to Client2 because Server1 not even know about the Client2's subscription.
So, in order to address this issue, again you have to externalize the WebSockets subscriptions. As you are using STOMP as a subprotocol, you need an external component that can act as a external STOMP broker. There are quite a lot tools able to do this, but I would suggest RabbitMQ.
Now, you must change your Spring configuration so that it will not keep the subscriptions in-memory. Instead, it will delegate the subscriptions to a external STOMP broker. You can easily achieve this with some basic configurations such as enableStompBrokerRelay.
The important thing to note is that HTTP session is different than WebSocket session. Using Spring Session to store the HTTP session in Redis has absolutely nothing to do with horizontally scaling WebSockets.

I've coded a complete Web Chat Application with Spring Boot (and much more) that uses RabbitMQ as a Full External STOMP Broker and it's public on GitHub so please clone it, run the app in your machine and see the code details.

When it comes to a WebSocket connection loss, there's not much that Spring can do. Actually, the reconnection must be requested by the client side implementing a reconnection callback function, for instance (that's the WebSocket handshake flow, the client must start the handshake, not the server). There are some client side libraries that can handle this transparently for you. That's not SockJS case. In the Chat Application I also implemented this reconnection feature.

Title: Spring Websocket in a tomcat cluster


问:
Converting Dataset[Array[String]] to Dataset[MyCaseClass]
I am working with a csv file like below

```<code>"age;""job"";""marital"""
"58;""management"";""married"""
"44;""technician"";""single"""
</code>```

Because of the extra quotes, spark.read.csv does not give clean columns.
So I thought of using spark.read.textFile which gives Dataset[String]. I use below code to remove the quotes and split them.

```<code>case class MyCaseClass(age: String, job: String, marital: String)
val inputDS = spark.read.textFile(inpPath)
val cleanDS = inputDS.map(_.replaceAll(""""""", "").split(";"))
val seperatedDS = cleanDS.as[MyCaseClass] //fails
</code>```

Is there a way to achieve this sort of Dataset convertion or a better way to split out into multiple columns?
For now I am using RDD to get the job done, but would like to know Dataset/Dataframe way of doing it.

答:
You can construct a record of MyCaseClass from each split line so that you have RDD[MyCaseClass], then you can directly convert it to data frame:

```<code>val cleanDS = inputDS.map(line => {
  val fields = line.replaceAll("\"", "").split(";")
  MyCaseClass(fields(0), fields(1), fields(2))
})

cleanDS
// res37: org.apache.spark.sql.Dataset[MyCaseClass] = [age: string, job: string ... 1 more field]

cleanDS.toDF.show
+---+----------+-------+
|age|       job|marital|

+---+----------+-------+
|age|       job|marital|
| 58|management|married|
| 44|technician| single|
+---+----------+-------+
</code>```

Body:
I am working with a csv file like below

"age;""job"";""marital"""
"58;""management"";""married"""
"44;""technician"";""single"""

Because of the extra quotes, spark.read.csv does not give clean columns.
So I thought of using spark.read.textFile which gives Dataset[String]. I use below code to remove the quotes and split them.

case class MyCaseClass(age: String, job: String, marital: String)
val inputDS = spark.read.textFile(inpPath)
val cleanDS = inputDS.map(_.replaceAll(""""""", "").split(";"))
val seperatedDS = cleanDS.as[MyCaseClass] //fails

Is there a way to achieve this sort of Dataset convertion or a better way to split out into multiple columns?
For now I am using RDD to get the job done, but would like to know Dataset/Dataframe way of doing it.

Body:
You can construct a record of MyCaseClass from each split line so that you have RDD[MyCaseClass], then you can directly convert it to data frame:

val cleanDS = inputDS.map(line => {
  val fields = line.replaceAll("\"", "").split(";")
  MyCaseClass(fields(0), fields(1), fields(2))
})

cleanDS
// res37: org.apache.spark.sql.Dataset[MyCaseClass] = [age: string, job: string ... 1 more field]

cleanDS.toDF.show
+---+----------+-------+
|age|       job|marital|

+---+----------+-------+
|age|       job|marital|
| 58|management|married|
| 44|technician| single|
+---+----------+-------+


问:
Adding "force field" to object in Unity to avoid collider clipping?
I'm making a bow and arrow game in Unity and C# with virtual reality. I want the arrow to rest on the bow's handle before you shoot. Right now I have a box collider on the handle and another collider on the arrow. It works OK, until you push the arrow through the handle. It glitches out for a sec then it just passes through (like a no clip).

In my VR class we learned that you can add a normal force or a "push back force" to an object to keep other objects from passing through it. I don't want this to literally push back the arrow though (that would remove the realism). Is there a way to add a force field to an object? Where other objects are repelled very lightly at all times instead of a one-shot burst of force?

Here's code I've already tried that helps a little but not much. This is a script attached to the bow:

```<code>private void OnCollisionEnter(Collision collision) {

    if (collision.gameObject.tag == "Arrow") {
        Rigidbody arrowBody = collision.gameObject.GetComponent<Rigidbody>();
        arrowBody.AddForce(this.transform.TransformDirection(Vector3.left) * 100f);
    }

}
</code>```

I should probably add that the arrow is held in a "hand" using  a fixed joint, so adding a second fixed joint to the bow handle is not an option (the hand's joint ends up failing and the arrow falls to the ground without being held by either joint).

答:
I wouldn't use physics for that unless there's a specific reason.

You can just change the orientation of the arrow by script to let it point in the right direction.

For example, you can add a child empty Transform to the bow representing the point where the arrow "touches" the bow.

Then you could add a script to the arrow that moves its back where the hand is and changes its direction to look at said Transform.

Body:
I'm making a bow and arrow game in Unity and C# with virtual reality. I want the arrow to rest on the bow's handle before you shoot. Right now I have a box collider on the handle and another collider on the arrow. It works OK, until you push the arrow through the handle. It glitches out for a sec then it just passes through (like a no clip).

In my VR class we learned that you can add a normal force or a "push back force" to an object to keep other objects from passing through it. I don't want this to literally push back the arrow though (that would remove the realism). Is there a way to add a force field to an object? Where other objects are repelled very lightly at all times instead of a one-shot burst of force?

Here's code I've already tried that helps a little but not much. This is a script attached to the bow:

private void OnCollisionEnter(Collision collision) {

    if (collision.gameObject.tag == "Arrow") {
        Rigidbody arrowBody = collision.gameObject.GetComponent<Rigidbody>();
        arrowBody.AddForce(this.transform.TransformDirection(Vector3.left) * 100f);
    }

}

I should probably add that the arrow is held in a "hand" using  a fixed joint, so adding a second fixed joint to the bow handle is not an option (the hand's joint ends up failing and the arrow falls to the ground without being held by either joint).


问:
Inheritance or composition for Category-Subcategory-Tags categorization
I need to develop categorization, which needs to have these characteristics:

An item may belong to one or more categories;

The same item may (and usually will) also belong to one or more subcategories

A subcategory is to have one or more parent categories

A subcategory is to feature several around a dozen tags

In an ideal world, categories themselves could have tags assigned to them

At this moment, I'm considering:

Having a base class Taxonomy from which Category, Subcategory and Tag would inherit. However, these would not have very specific attributes of their own to justify such a decision

Use composition instead, but I'm unsure if I understood it correctly (it may not be suitable for this case).

Maybe there are better ways to accomplish it.

答: Taxonomy seems like a good candidate for a "has a" rule set. The first thing I would consider would be have a Taxonomy interface that each Category class would implement. A Subcategory class could also implement an interface, one that extends upon Taxonomy. Finally, Tags also could be an extension of a Taxonomy interface, as an area of study should have tags. The composition could take place with a CategoryComp class that implements the highest taxonomy interface and holds references to the common objects. Another alternative might be to explore beans/wiring in Java.


问:
Scrollable div inside section of Fullpage.js doesn't work
I want to have a scrollable div inside a section of fullpage.js but when I include scrollOverflow: true then I get this error: Cannot read property 'scrollHeight' of undefined.

The scrollOverflow library is included:

http://jsfiddle.net/97tbk/1827/

I wonder what am I missing:

```<code>$('#fullpage').fullpage({
    sectionsColor: ['yellow', 'orange', '#C0C0C0', '#ADD8E6'],
    scrollOverflow: true
});
$('.fp-scrollable').slimScroll({
    alwaysVisible: true,
    color: 'black',
    size: '10px',
    allowPageScroll: true,
});
</code>```

答:
You just need to use scrollOverflow:true and include the scrolloverflow.min.js file as detailed in the fullPage.js docs.

scrollOverflow: (default false) (not compatible with IE 8) defines whether or not to create a scroll for the section/slide in case its content is bigger than the height of it. When set to true, your content will be wrapped by the plugin. Consider using delegation or load your other scripts in the afterRender callback. In case of setting it to true, it requires the vendor library scrolloverflow.min.js and it should be loaded before the fullPage.js plugin. For example:

```<code><script type="text/javascript" src="vendors/scrolloverflow.min.js"></script>
<script type="text/javascript" src="jquery.fullPage.js"></script>
</code>```

You have an example available in the examples folder in fullPage.js

For fullPage.js version 3 it would almost be identical:

```<code><script type="text/javascript" src="vendors/scrolloverflow.min.js"></script>
<script type="text/javascript" src="fullpage.js"></script>
</code>```

Body:
I want to have a scrollable div inside a section of fullpage.js but when I include scrollOverflow: true then I get this error: Cannot read property 'scrollHeight' of undefined.

The scrollOverflow library is included:

http://jsfiddle.net/97tbk/1827/

I wonder what am I missing:

$('#fullpage').fullpage({
    sectionsColor: ['yellow', 'orange', '#C0C0C0', '#ADD8E6'],
    scrollOverflow: true
});
$('.fp-scrollable').slimScroll({
    alwaysVisible: true,
    color: 'black',
    size: '10px',
    allowPageScroll: true,
});

Body:
You just need to use scrollOverflow:true and include the scrolloverflow.min.js file as detailed in the fullPage.js docs.

scrollOverflow: (default false) (not compatible with IE 8) defines whether or not to create a scroll for the section/slide in case its content is bigger than the height of it. When set to true, your content will be wrapped by the plugin. Consider using delegation or load your other scripts in the afterRender callback. In case of setting it to true, it requires the vendor library scrolloverflow.min.js and it should be loaded before the fullPage.js plugin. For example:

<script type="text/javascript" src="vendors/scrolloverflow.min.js"></script>
<script type="text/javascript" src="jquery.fullPage.js"></script>

You have an example available in the examples folder in fullPage.js

For fullPage.js version 3 it would almost be identical:

<script type="text/javascript" src="vendors/scrolloverflow.min.js"></script>
<script type="text/javascript" src="fullpage.js"></script>

ContentLicense: CC BY-SA 4.0


问:
Django "TemplateDoesNotExist " Error but "Using loader django.template.loaders.app_directories.Loader" File Exists
Template Loader finds the template but template is not loaded

```<code>TemplateDoesNotExist at /cardpayment/

cardpayment.html

Request Method:     GET
Request URL:    http://localhost:7000/cardpayment/
Django Version:     1.8
Exception Type:     TemplateDoesNotExist
Exception Value:

cardpayment.html

Exception Location:     /home/sdr/sl/lib/python3.4/site-packages/django/template/loader.py in render_to_string, line 138
Python Executable:  /home/sdr/sl/bin/python
Python Version:     3.4.3
Python Path:

['/home/sdr/sl/agryp',
 '/home/sdr/pycharm-4.0.6/helpers/pydev',
 '/home/sdr/sl/src/tastypie',
 '/home/sdr/sl/agryp',
 '/usr/local/lib/python34.zip',
 '/usr/local/lib/python3.4',
 '/usr/local/lib/python3.4/plat-linux',
 '/usr/local/lib/python3.4/lib-dynload',
 '/home/sdr/sl/lib/python3.4/site-packages']

Server time:    Tue, 5 May 2015 10:17:40 +0000
Template-loader postmortem

Django tried loading these templates, in this order:

    Using loader django.template.loaders.filesystem.Loader:
        /home/sdr/sl/agryp/templates/cardpayment.html (File does not exist)
    Using loader django.template.loaders.app_directories.Loader:
        /home/sdr/sl/agryp/agryp/templates/cardpayment.html (File exists) <=========== FILE EXISTS BUT NOT LOADED
        /home/sdr/sl/src/tastypie/tastypie/templates/cardpayment.html (File does not exist)
        /home/sdr/sl/lib/python3.4/site-packages/grappelli/templates/cardpayment.html (File does not exist)
        /home/sdr/sl/lib/python3.4/site-packages/django/contrib/admin/templates/cardpayment.html (File does not exist)
        /home/sdr/sl/lib/python3.4/site-packages/django/contrib/auth/templates/cardpayment.html (File does not exist)
        /home/sdr/sl/lib/python3.4/site-packages/oauth2_provider/templates/cardpayment.html (File does not exist)
        /home/sdr/sl/lib/python3.4/site-packages/selectable/templates/cardpayment.html (File does not exist)
</code>```

As it can be clearly seen, the loader is able to find the template.

The TEMPLATE_DIRS value in settings.py is as follows:

```<code>TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [ os.path.join(BASE_DIR, "templates"),],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'allauth.account.context_processors.account',
                'allauth.socialaccount.context_processors.socialaccount',
            ],
        },
    },
]
</code>```

I have tried to move the template to project/templates directory as well but the error persists.

Code checks out with 0 errors/warnings.

contents of cardpayment.html

```<code>{% extends "base.html" %}
{% block title %}Card Payments over Phone{% endblock %}
{% block extrahead %}
    {% load selectable_tags %}
    {% include_ui_theme %}
{% endblock %}

{% block content %}
    <h1>Receive Card Payment</h1>
    <form name="paymentType"  id="paymentType" class="form-horizontal">
    <fieldset>
        <label>Check type of Customer
        <input type="radio" value="existing">Existing Customer<br />
        <input type="radio"  value="new">Nee Customer<br />
        </label>
    </fieldset>
    </form>

    <div class="row">
    <form class="form-horizontal">
        <table class="table-responsive table-bordered">
            {{ form.as_table }}
        </table>
    </form>
    </div>
{% endblock %}
</code>```

答:
TemplateDoesNotExist... cardpayment.html might mean Django can't find cardpayment.html, or it might mean it can find cardpayment.html no problem, but can't find some  {% include 'cardpayment_subsection.html' %} within it.

Explanation:

I got this error just now, in a project that's been working for years, and the other solutions here didn't help me.

My cardpayment.html was being found by the template loaders, but contained some nonsense which meant it could not be rendered.
The error messages mislead me into thinking Django didn't know the file exists, when in fact it knew it existed, just couldn't successfully render it.

For a while everything was working fine: cardpayment.html was being rendered without a problem.

views.py

```<code>def cardpaymentview(request):
    return render_to_response("cardpayment.html", {
            "message": "Hi SO"
            }, context_instance=RequestContext(request))
</code>```

Suddenly, even though I hadn't been editing cardpayment.html, I got that error:

TemplateDoesNotExist at /cardpaymentpage:
cardpayment.html

```<code>Using loader django.template.loaders.app_directories.Loader:
folder/lib/python2.7/site-packages/django/contrib/admin/templates/cardpayment.html (File does not exist)
folder/project/app1/templates/cardpayment.html (File does not exist)
folder/project/app2/templates/cardpayment.html (File does not exist)
folder/project/paymentapp/templates/cardpayment.html (File exists)
</code>```

The problem was that my cardpayment.html in turn has an include calling another template:

```<code>{% include 'cardpayment_subsection.html' %}
</code>```

I created the error by renaming the file cardpayment_subsection.html to something_else.html, without editing cardpayment.html, so that include command naturally failed.

But as you can see, the debug message didn't indicate the problem was callling the cardpayment_subsection.html (file no longer exists).

Summary: if other solutions don't work for you, try creating a test file cardpayment2.html that simply says "Hello world" and see if you can at least render that instead. Maybe the cardpayment.html file is being read, but has an error within it. (In my case, I needed to change the {% include '____.html' %} to refer to a file that actually does exist!)

Body:
Template Loader finds the template but template is not loaded

TemplateDoesNotExist at /cardpayment/

cardpayment.html

Request Method:     GET
Request URL:    http://localhost:7000/cardpayment/
Django Version:     1.8
Exception Type:     TemplateDoesNotExist
Exception Value:

cardpayment.html

Exception Location:     /home/sdr/sl/lib/python3.4/site-packages/django/template/loader.py in render_to_string, line 138
Python Executable:  /home/sdr/sl/bin/python
Python Version:     3.4.3
Python Path:

['/home/sdr/sl/agryp',
 '/home/sdr/pycharm-4.0.6/helpers/pydev',
 '/home/sdr/sl/src/tastypie',
 '/home/sdr/sl/agryp',
 '/usr/local/lib/python34.zip',
 '/usr/local/lib/python3.4',
 '/usr/local/lib/python3.4/plat-linux',
 '/usr/local/lib/python3.4/lib-dynload',
 '/home/sdr/sl/lib/python3.4/site-packages']

Server time:    Tue, 5 May 2015 10:17:40 +0000
Template-loader postmortem

Django tried loading these templates, in this order:

    Using loader django.template.loaders.filesystem.Loader:
        /home/sdr/sl/agryp/templates/cardpayment.html (File does not exist)
    Using loader django.template.loaders.app_directories.Loader:
        /home/sdr/sl/agryp/agryp/templates/cardpayment.html (File exists) <=========== FILE EXISTS BUT NOT LOADED
        /home/sdr/sl/src/tastypie/tastypie/templates/cardpayment.html (File does not exist)
        /home/sdr/sl/lib/python3.4/site-packages/grappelli/templates/cardpayment.html (File does not exist)
        /home/sdr/sl/lib/python3.4/site-packages/django/contrib/admin/templates/cardpayment.html (File does not exist)
        /home/sdr/sl/lib/python3.4/site-packages/django/contrib/auth/templates/cardpayment.html (File does not exist)
        /home/sdr/sl/lib/python3.4/site-packages/oauth2_provider/templates/cardpayment.html (File does not exist)
        /home/sdr/sl/lib/python3.4/site-packages/selectable/templates/cardpayment.html (File does not exist)

As it can be clearly seen, the loader is able to find the template.

The TEMPLATE_DIRS value in settings.py is as follows:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [ os.path.join(BASE_DIR, "templates"),],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'allauth.account.context_processors.account',
                'allauth.socialaccount.context_processors.socialaccount',
            ],
        },
    },
]

I have tried to move the template to project/templates directory as well but the error persists.

Code checks out with 0 errors/warnings.

contents of cardpayment.html

{% extends "base.html" %}
{% block title %}Card Payments over Phone{% endblock %}
{% block extrahead %}
    {% load selectable_tags %}
    {% include_ui_theme %}
{% endblock %}

{% block content %}

Receive Card Payment

    <form name="paymentType"  id="paymentType" class="form-horizontal">
    <fieldset>
        Check type of Customer
        <input type="radio" value="existing">Existing Customer

        <input type="radio"  value="new">Nee Customer

    </fieldset>
    </form>

    <form class="form-horizontal">

            {{ form.as_table }}

    </form>

{% endblock %}

Body:
TemplateDoesNotExist... cardpayment.html might mean Django can't find cardpayment.html, or it might mean it can find cardpayment.html no problem, but can't find some  {% include 'cardpayment_subsection.html' %} within it.

Explanation:

I got this error just now, in a project that's been working for years, and the other solutions here didn't help me.

My cardpayment.html was being found by the template loaders, but contained some nonsense which meant it could not be rendered.
The error messages mislead me into thinking Django didn't know the file exists, when in fact it knew it existed, just couldn't successfully render it.

For a while everything was working fine: cardpayment.html was being rendered without a problem.

views.py

def cardpaymentview(request):
    return render_to_response("cardpayment.html", {
            "message": "Hi SO"
            }, context_instance=RequestContext(request))

Suddenly, even though I hadn't been editing cardpayment.html, I got that error:

TemplateDoesNotExist at /cardpaymentpage:
cardpayment.html

Using loader django.template.loaders.app_directories.Loader:
folder/lib/python2.7/site-packages/django/contrib/admin/templates/cardpayment.html (File does not exist)
folder/project/app1/templates/cardpayment.html (File does not exist)
folder/project/app2/templates/cardpayment.html (File does not exist)
folder/project/paymentapp/templates/cardpayment.html (File exists)

The problem was that my cardpayment.html in turn has an include calling another template:

{% include 'cardpayment_subsection.html' %}

I created the error by renaming the file cardpayment_subsection.html to something_else.html, without editing cardpayment.html, so that include command naturally failed.

But as you can see, the debug message didn't indicate the problem was callling the cardpayment_subsection.html (file no longer exists).

Summary: if other solutions don't work for you, try creating a test file cardpayment2.html that simply says "Hello world" and see if you can at least render that instead. Maybe the cardpayment.html file is being read, but has an error within it. (In my case, I needed to change the {% include '____.html' %} to refer to a file that actually does exist!)


问:
Const in JavaScript: when to use it and is it necessary?
I've recently come across the const keyword in JavaScript. From what I can tell, it is used to create immutable variables, and I've tested to ensure that it cannot be redefined (in Node.js):

```<code>const x = 'const';
const x = 'not-const';

// Will give an error: 'constant 'x' has already been defined'
</code>```

I realise that it is not yet standardized across all browsers - but I'm only interested in the context of Node.js V8, and I've noticed that certain developers / projects seem to favor it heavily when the var keyword could be used to the same effect.

When is it appropriate to use const in place of var?

Should it be used every time a variable which is not going to be
re-assigned is declared?

Does it actually make any difference if var is used in place of
const or vice-versa?

答:
For why to use const, Tibos's answer's great.

But you said:

From what I can tell, it is used to create immutable variables

That is wrong. Mutating a variable is different from reassigning:

```<code>var hello = 'world' // Assigning
hello = 'bonjour!' // Reassigning
</code>```

With const, you can not do that:

```<code>const hello = 'world'
hello = 'bonjour!' // Error
</code>```

But you can mutate your variable:

```<code>const marks = [92, 83]
marks.push(95)
console.log(marks) // [92, 83, 95] -> the variable has been mutated.
</code>```

So, any process that changes the variable's value without using the = sign is mutating the variable.

Note: += for example is ... reassigning!

```<code>var a = 5
a += 2 // Is the same as a = a + 2
</code>```

So, the bottom line is: const doesn't prevent you from mutating variables; it prevents you from reassigning them.

Body:
I've recently come across the const keyword in JavaScript. From what I can tell, it is used to create immutable variables, and I've tested to ensure that it cannot be redefined (in Node.js):

const x = 'const';
const x = 'not-const';

// Will give an error: 'constant 'x' has already been defined'

I realise that it is not yet standardized across all browsers - but I'm only interested in the context of Node.js V8, and I've noticed that certain developers / projects seem to favor it heavily when the var keyword could be used to the same effect.

When is it appropriate to use const in place of var?

Should it be used every time a variable which is not going to be
re-assigned is declared?

Does it actually make any difference if var is used in place of
const or vice-versa?

Body:
For why to use const, Tibos's answer's great.

But you said:

From what I can tell, it is used to create immutable variables

That is wrong. Mutating a variable is different from reassigning:

var hello = 'world' // Assigning
hello = 'bonjour!' // Reassigning

With const, you can not do that:

const hello = 'world'
hello = 'bonjour!' // Error

But you can mutate your variable:

const marks = [92, 83]
marks.push(95)
console.log(marks) // [92, 83, 95] -> the variable has been mutated.

So, any process that changes the variable's value without using the = sign is mutating the variable.

Note: += for example is ... reassigning!

var a = 5
a += 2 // Is the same as a = a + 2

So, the bottom line is: const doesn't prevent you from mutating variables; it prevents you from reassigning them.


问:
How to publish alpha npm module without confusing the community?
Given an useless pet node module.

./node_modules/salutations.js :

```<code>var cl = function (msg) { console.log(msg) }
var hi = function () { cl("Hi !") }
var seeYa = function () { cl("SeeYa !") }
exports.hi = hi;
exports.seeYa = seeYa;
</code>```

./script.js :

```<code>var salutations = require('salutations')
salutations.hi();     // returns: "Hi !"
salutations.seeYa();  // returns: "SeeYa !"
</code>```

./package.json

```<code>{
  "name": "NodeSalutations",
  "version": "0.0.1",
  dependencies: {}
}
</code>```

Given its creation sole purpose was to learn about the creation , then publication on npm.org of a minimalist node module.

Given there is nothing valuable on this module, so I don't want to set up a private account.

Is there a way to publish, test, then remove discretely the module on npm, without polluting npm.org ?

Edit : I did read npmjs.com's publish, unpublish, registry and scope.

答:
You could just upload it to NPM.org and then deal with clean up later, Considering the scope of the module I'm sure no one would get invested enough to mind a removal/change.

Your other option is to host your own NPM repository for testing (this is what I would do) using something like sinopia

Body:
Given an useless pet node module.

./node_modules/salutations.js :

var cl = function (msg) { console.log(msg) }
var hi = function () { cl("Hi !") }
var seeYa = function () { cl("SeeYa !") }
exports.hi = hi;
exports.seeYa = seeYa;

./script.js :

var salutations = require('salutations')
salutations.hi();     // returns: "Hi !"
salutations.seeYa();  // returns: "SeeYa !"

./package.json

{
  "name": "NodeSalutations",
  "version": "0.0.1",
  dependencies: {}
}

Given its creation sole purpose was to learn about the creation , then publication on npm.org of a minimalist node module.

Given there is nothing valuable on this module, so I don't want to set up a private account.

Is there a way to publish, test, then remove discretely the module on npm, without polluting npm.org ?

Edit : I did read npmjs.com's publish, unpublish, registry and scope.


问:
What is a good api for mapping gps coordinates in c#?
I have a project that has a list of gps coordinates. I would like to find a way to make a simple map of those coordinates (possibly just one at a time). The map should have basic street info.

This part of our project is pretty simple so I don't think it needs to be an exceptionally feature rich product. This also means it shouldn't be really expensive.

What is a good product to achieve this?

edit: This is a desktop app where internet connectivity will probably not be available.

答:
Sharpmap is open source project written in C# and released under LGPL. To quote first line from page:

SharpMap is an easy-to-use mapping library for use in web and desktop applications.

OwnerDisplayName: BFreeman

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Brian Knoblauch


问:
bash vs csh vs others - which is better for application maintenance?

Possible Duplicate:

  What Linux shell should I use?

I am starting to get proficient in a Linux environment and i'm trying to pick a weapon of choice in terms of command shell scripting (as i'm still a big n00b at this) that will help me (and others) manage, test and administer a set of server side applications running on a *NIX environment.

My question is: What is(are) the preferred command shell(s)  out there when the following criteria are considered:

How easy is it to learn/understand for a junior dev who has never had an exposure to shell scripting?

Is there a big pool of developers out there that know this shell script?

Is it safe and easy to use - will script errors be silent or give intelligent error output, will it let the uninitiated shoot them selves in the foot?

How portable is it? - Can i expect the same script to run in OpenSolaris as well as Redhat, FreeBSD? (granted command syntax and options for specific OS will change accordingly)

How standard is it? Is it expected to be included on most distro's of *NIX or does it have to be installed additionally?

I understand that there are camps out there who hold strong feelings for/against specific command shells, i am just looking for an informed opinion.

答:
Shell scripts for any *nix shell are generally deceptively simple. Easy things are usually easy, sometimes hard things are easy, sometimes easy-seeming things are hard. No shell is particularly better than the others in this area but some are worse (I can't seriously recommend csh). Some will say that bash is the worst 'modern' shell, which may be true but you can't completely escape it anyway.

There's an argument to be made that using the most 'popular' shell is best for maintainability for the same reason Windows is best (and I'm not saying that it is): It's easy to find people you can hire who know how to use it. There are simply more people who have at least a passing familiarity with bash-specific features, say, than ksh or zsh. Finding people who actually understand what they're doing is another matter.

All shells have various gotchas, corner-cases and weird behaviors. Mostly it comes down to what you're used to. Shooting yourself in the foot is what I'd call a grand Unix tradition and no *nix shell can truly keep you safe.

Nearly every shell you'll see is highly portable to almost every platform. Even though this is true you won't necessarily be able to run the same (say) bash script on three different boxes unless you were careful about what utilities you used and which options you passed them. Writing portable shell scripts is hard for reasons having nothing to do with which shell they're written for.

Nearly every Linux uses bash by default and has most shells available. FreeBSD includes sh, csh and tcsh by default with bash and others in ports. Once upon a long time ago, Mac OS X used tcsh by default, but it now uses bash by default, and includes zsh along with most common shells. Beyond that I cannot comment.

Personally I use bash out of (mostly) inertia. If I weren't so familiar with it already I would use zsh instead.


问:
How to keep numpy from broadcasting when creating an object array of different shaped arrays
I try to store a list of different shaped arrays as a dtype=object array using np.save (I'm aware I could just pickle the list but I'm really curious how to do this).
If I do this:

```<code>import numpy as np
np.save('test.npy', [np.zeros((2, 2)), np.zeros((3,3))])
</code>```

it works.
But this:

```<code>np.save('test.npy', [np.zeros((2, 2)), np.zeros((2,3))])
</code>```

Gives me an error:

```<code>ValueError: could not broadcast input array from shape (2,2) into shape (2)
</code>```

I guess np.save converts the list into an array first, so I tried:

```<code>x=np.array([np.zeros((2, 2)), np.zeros((3,3))])
y=np.array([np.zeros((2, 2)), np.zeros((2,3))])
</code>```

Which has the same effect (first one works, second one doesn't.
The resulting x behaves as expected:

```<code>>>> x.shape
(2,)
>>> x.dtype
dtype('O')
>>> x[0].shape
(2, 2)
>>> x[0].dtype
dtype('float64')
</code>```

I also tried to force the 'object' dtype:

```<code>np.array([np.zeros((2, 2)), np.zeros((2,3))], dtype=object)
</code>```

Without success. It seems numpy tries to broadcast the array with equal first dimension into the new array and realizes too late that their shape is different. Oddly it seems to have worked at one point - so I'm really curious what the difference is, and how to do this properly.

EDIT:
I figured out the case it worked before: The only difference seems to be that the numpy arrays in the list have another data type.
It works with dtype('<f8'), but it doesn't with dtype('float64'), I'm not even sure what the difference is.

EDIT 2:
I found a very non-pythonic way to solve my issue, I add it here, maybe it helps to understand what I wanted to do:

```<code>array_list=np.array([np.zeros((2, 2)), np.zeros((2,3))])
save_array = np.empty((len(array_list),), dtype=object)
for idx, arr in enumerate(array_list):
    save_array[idx] = arr
np.save('test.npy', save_array)
</code>```

答:
One of the first things that np.save does is

```<code>arr = np.asanyarray(arr)
</code>```

So yes it is trying to turn your list into an array.

Constructing an object array from arbitrary sized arrays or lists is tricky.  np.array(...) tries to create as high a dimensional array as it can, even attempting to concatenate the inputs if possible. The surest way is to do what you did - make the empty array and fill it.

A slightly more compact way of constructing the object array:

```<code>In [21]: alist = [np.zeros((2, 2)), np.zeros((2,3))]
In [22]: arr = np.empty(len(alist), dtype=object)
In [23]: arr[:] = alist
In [24]: arr
Out[24]:
array([array([[ 0.,  0.],
       [ 0.,  0.]]),
       array([[ 0.,  0.,  0.],
       [ 0.,  0.,  0.]])], dtype=object)
</code>```

Here are 3 scenarios:

Arrays that match in shape, combine into a 3d array:

```<code>In [27]: np.array([np.zeros((2, 2)), np.zeros((2,2))])
Out[27]:
array([[[ 0.,  0.],
        [ 0.,  0.]],

       [[ 0.,  0.],
        [ 0.,  0.]]])
In [28]: _.shape
Out[28]: (2, 2, 2)
</code>```

Arrays that don't match on the first dimension - create object array

```<code>In [29]: np.array([np.zeros((2, 2)), np.zeros((3,2))])
Out[29]:
array([array([[ 0.,  0.],
       [ 0.,  0.]]),
       array([[ 0.,  0.],
       [ 0.,  0.],
       [ 0.,  0.]])], dtype=object)
In [30]: _.shape
Out[30]: (2,)
</code>```

And awkward intermediate case (which may even be described as a bug).  The first dimensions match, but the second ones don't):

```<code>In [31]: np.array([np.zeros((2, 2)), np.zeros((2,3))])
...
ValueError: could not broadcast input array from shape (2,2) into shape (2)
       [ 0.,  0.]])], dtype=object)
</code>```

It's as though it initialized a (2,2,2) array, and then found that the (2,3) wouldn't fit.  And the current logic doesn't allow it to backup and create the object array as it did in the previous scenario.

If you wanted to put the two (2,2) arrays in object array you'd have to use the create and fill logic.

Body:
I try to store a list of different shaped arrays as a dtype=object array using np.save (I'm aware I could just pickle the list but I'm really curious how to do this).
If I do this:

import numpy as np
np.save('test.npy', [np.zeros((2, 2)), np.zeros((3,3))])

it works.
But this:

np.save('test.npy', [np.zeros((2, 2)), np.zeros((2,3))])

Gives me an error:

ValueError: could not broadcast input array from shape (2,2) into shape (2)

I guess np.save converts the list into an array first, so I tried:

x=np.array([np.zeros((2, 2)), np.zeros((3,3))])
y=np.array([np.zeros((2, 2)), np.zeros((2,3))])

Which has the same effect (first one works, second one doesn't.
The resulting x behaves as expected:

>>> x.shape
(2,)
>>> x.dtype
dtype('O')
>>> x[0].shape
(2, 2)
>>> x[0].dtype
dtype('float64')

I also tried to force the 'object' dtype:

np.array([np.zeros((2, 2)), np.zeros((2,3))], dtype=object)

Without success. It seems numpy tries to broadcast the array with equal first dimension into the new array and realizes too late that their shape is different. Oddly it seems to have worked at one point - so I'm really curious what the difference is, and how to do this properly.

EDIT:
I figured out the case it worked before: The only difference seems to be that the numpy arrays in the list have another data type.
It works with dtype('<f8'), but it doesn't with dtype('float64'), I'm not even sure what the difference is.

EDIT 2:
I found a very non-pythonic way to solve my issue, I add it here, maybe it helps to understand what I wanted to do:

array_list=np.array([np.zeros((2, 2)), np.zeros((2,3))])
save_array = np.empty((len(array_list),), dtype=object)
for idx, arr in enumerate(array_list):
    save_array[idx] = arr
np.save('test.npy', save_array)

Body:
One of the first things that np.save does is

arr = np.asanyarray(arr)

So yes it is trying to turn your list into an array.

Constructing an object array from arbitrary sized arrays or lists is tricky.  np.array(...) tries to create as high a dimensional array as it can, even attempting to concatenate the inputs if possible. The surest way is to do what you did - make the empty array and fill it.

A slightly more compact way of constructing the object array:

In [21]: alist = [np.zeros((2, 2)), np.zeros((2,3))]
In [22]: arr = np.empty(len(alist), dtype=object)
In [23]: arr[:] = alist
In [24]: arr
Out[24]:
array([array([[ 0.,  0.],
       [ 0.,  0.]]),
       array([[ 0.,  0.,  0.],
       [ 0.,  0.,  0.]])], dtype=object)

Here are 3 scenarios:

Arrays that match in shape, combine into a 3d array:

In [27]: np.array([np.zeros((2, 2)), np.zeros((2,2))])
Out[27]:
array([[[ 0.,  0.],
        [ 0.,  0.]],

       [[ 0.,  0.],
        [ 0.,  0.]]])
In [28]: _.shape
Out[28]: (2, 2, 2)

Arrays that don't match on the first dimension - create object array

In [29]: np.array([np.zeros((2, 2)), np.zeros((3,2))])
Out[29]:
array([array([[ 0.,  0.],
       [ 0.,  0.]]),
       array([[ 0.,  0.],
       [ 0.,  0.],
       [ 0.,  0.]])], dtype=object)
In [30]: _.shape
Out[30]: (2,)

And awkward intermediate case (which may even be described as a bug).  The first dimensions match, but the second ones don't):

In [31]: np.array([np.zeros((2, 2)), np.zeros((2,3))])
...
ValueError: could not broadcast input array from shape (2,2) into shape (2)
       [ 0.,  0.]])], dtype=object)

It's as though it initialized a (2,2,2) array, and then found that the (2,3) wouldn't fit.  And the current logic doesn't allow it to backup and create the object array as it did in the previous scenario.

If you wanted to put the two (2,2) arrays in object array you'd have to use the create and fill logic.


问:
Download an excel file and read content with azure functions
I am trying to write a C# Azure Function to download and open an excel file using the OpenXml-SDK.

Office Interop doesn't work here because office is not available to the Azure Function.

I am trying to use OpenXml-SDK to open and read the file which seems to require a path to the saved file and not the url or a Stream downloaded from the remote url.

Given I don't know of a way to temporary store the excel file in Azure Functions, I used Azure File Storage.

I uploaded the excel file from the url to Azure File Storage, however I cannot open the excel file with OpenXML-SDK.

I tested the excel file in Azure File Storage is working, however, when I try to open the OpenXML.SpreadsheetDocument form a MemoryStream I get error indicating the file is corrupt.

If I try to open the SpreadsheetDocument passing the file Uri (https://learn.microsoft.com/en-us/azure/storage/storage-dotnet-how-to-use-files#develop-with-file-storage) then the address passes the 260 character limit.

I'm open to using a library other than OpenXML and ideally I would prefer not to have to store the excel file.

答:
If you do need to save a temporary file, Azure Functions has a %TEMP% environment variable with a path to a temporary folder. This is a folder that is local to the vm that runs your function and will not be persisted.

However, saving the file locally / in Azure Files is unnecessary. You should be able to get the stream from the response to your get request and pass it straight to OpenXML.

```<code>HttpWebRequest request = (HttpWebRequest)WebRequest.Create(originalExcelUrl);
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using (Stream stream = response.GetResponseStream())
{
    var doc = SpreadsheetDocument.Open(stream, true);
    // etc
}
</code>```

Body:
If you do need to save a temporary file, Azure Functions has a %TEMP% environment variable with a path to a temporary folder. This is a folder that is local to the vm that runs your function and will not be persisted.

However, saving the file locally / in Azure Files is unnecessary. You should be able to get the stream from the response to your get request and pass it straight to OpenXML.

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(originalExcelUrl);
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using (Stream stream = response.GetResponseStream())
{
    var doc = SpreadsheetDocument.Open(stream, true);
    // etc
}


问:
Android: Specify String in different Package in Manifest
Is it possible to specify that a @string value belongs to a different package via the Manifest?

i.e. android:text="@string/my_logo_text"

Implicitly specifies the value as belonging to the current package. Is there a way to fully qualify that this string belongs to another package?

答: To specify an resource's package you should use as following: android:text="@package:string/another_text"


问:
Trying to bundle first React app - bundle is too big
I have first react app - which is 5.5Mb when using developer mode and devtool: "source-map". Now I tried to write webpack for distribution mode like this:

```<code>var webpack = require('webpack');
var path = require('path');
var fs = require('fs')

var BUILD_DIR = path.resolve(__dirname, 'public/javascripts');
var APP_DIR = path.resolve(__dirname, 'frontend');

const babelSettings = JSON.parse(fs.readFileSync(".babelrc"))
var config = {
    entry: APP_DIR + '/app.jsx',
    output: {
        path: BUILD_DIR,
        filename: 'bundle.js',
    },
    module : {
        loaders : [
            {
                test : /\.jsx?/,
                include : APP_DIR,
                use : ['babel-loader']
            }
            ,
            {
                test: /\.css$/,
                use: ["style-loader",{
                    loader: "css-loader",
                    options: {
                        minimize: true
                    }
                }],

            },
            {
                test: /\.less$/,
                use: ["style-loader,less-loader"]
            },
            {
                test: /\.svg$/,
                loaders: [
                    {
                        loader: 'babel-loader',
                        query: {
                            presets: ['es2015']
                        }
                    },
                    {
                        loader: 'react-svg-loader',
                        query: {
                            jsx: true
                        }
                    }
                ],
                exclude: /node_modules/
            }
        ]
    },
    plugins: [
        new webpack.DefinePlugin({
            'process.env': {
                'NODE_ENV': JSON.stringify('production')
            }
        }),
        new webpack.optimize.UglifyJsPlugin({
            compress: {
                screw_ie8: true
            }
        })
    ]

};

babelSettings.plugins.push("transform-react-inline-elements");
babelSettings.plugins.push("transform-react-constant-elements");

module.exports = config;
</code>```

I run it with :

```<code>webpack --config webpack-dist.config.js -p --progress  --production --optimize-minimize
</code>```

The output is still 2.2Mb which is unacceptable size.What config did I miss?

Edit packages.json looks like this:

```<code>{
  "name": "project",
  "version": "0.1.0",
  "private": true,
  "devDependencies": {
    "babel-cli": "^6.18.0",
    "babel-plugin-transform-decorators-legacy": "^1.3.4",
    "babel-plugin-transform-runtime": "^6.22.0",
    "babel-preset-es2015": "^6.22.0",
    "babel-preset-react": "^6.22.0",
    "babel-preset-stage-3": "^6.22.0",
    "babelify": "^7.3.0",
    "browserify": "^13.3.0",
    "css-loader": "^0.28.0",
    "exorcist": "^0.4.0",
    "gulp-livereload": "^3.8.1",
    "gulp-sourcemaps": "^2.4.0",
    "less": "^2.7.2",
    "less-loader": "^2.2.3",
    "react-edit-inline": "^1.0.8",
    "react-image-fallback": "^4.0.1",
    "react-scripts": "0.8.5",
    "redux-devtools-extension": "^2.13.0",
    "remote-redux-devtools": "^0.5.0",
    "riek": "^1.0.7",
    "style-loader": "^0.13.1",
    "svg-react-loader": "^0.4.0-beta.2",
    "vinyl-buffer": "^1.0.0",
    "watchify": "^3.8.0",
    "webpack": "^2.3.2"
  },
  "dependencies": {
    "axios": "^0.16.0",
    "barcoder": "^2.0.1",
    "escape-string-regexp": "^1.0.5",
    "frisbee": "^1.1.7",
    "i18next": "^5.0.0",
    "i18next-browser-languagedetector": "^1.0.1",
    "i18next-xhr-backend": "^1.3.0",
    "immutability-helper": "^2.1.1",
    "lodash": "^4.17.4",
    "qrcode.react": "^0.6.1",
    "rc-time-picker": "^2.3.3",
    "react": "^15.4.2",
    "react-autosuggest": "^8.0.0",
    "react-bootstrap": "^0.30.7",
    "react-cards": "^0.2.2",
    "react-collapse": "^2.3.3",
    "react-cookie": "^1.0.4",
    "react-dom": "^15.4.2",
    "react-dropzone": "^3.10.0",
    "react-height": "^2.2.0",
    "react-highlight-words": "^0.6.0",
    "react-i18next": "^2.0.0",
    "react-infinite-scroller": "^1.0.4",
    "react-input-autosize": "^1.1.0",
    "react-isolated-scroll": "^0.1.0",
    "react-loaders": "^2.3.0",
    "react-motion": "^0.4.7",
    "react-number-input": "^15.0.0-rc2",
    "react-numeric-input": "^2.0.7",
    "react-popover": "^0.4.4",
    "react-preload": "^0.5.0",
    "react-redux": "^5.0.2",
    "react-redux-form": "^1.5.4",
    "react-router-dom": "^4.0.0",
    "react-select": "^1.0.0-rc.3",
    "react-svg-loader": "^1.1.1",
    "react-switch-button": "^2.1.1",
    "react-tabs": "^0.8.2",
    "react-tagsinput": "^3.14.0",
    "redux": "^3.6.0",
    "redux-thunk": "^2.2.0",
    "simple-react-pdf": "^1.0.6",
    "style-it": "^1.5.5",
    "throttle-debounce": "^1.0.1",
    "validator": "^6.2.1"
  },
</code>```

答:
Use the excellent Webpack Bundle Analyzer to look at what is taking up space in your build.

Also, try setting NODE_ENV=production before you run webpack, it makes a difference.

Body:
I have first react app - which is 5.5Mb when using developer mode and devtool: "source-map". Now I tried to write webpack for distribution mode like this:

var webpack = require('webpack');
var path = require('path');
var fs = require('fs')

var BUILD_DIR = path.resolve(__dirname, 'public/javascripts');
var APP_DIR = path.resolve(__dirname, 'frontend');

const babelSettings = JSON.parse(fs.readFileSync(".babelrc"))
var config = {
    entry: APP_DIR + '/app.jsx',
    output: {
        path: BUILD_DIR,
        filename: 'bundle.js',
    },
    module : {
        loaders : [
            {
                test : /\.jsx?/,
                include : APP_DIR,
                use : ['babel-loader']
            }
            ,
            {
                test: /\.css$/,
                use: ["style-loader",{
                    loader: "css-loader",
                    options: {
                        minimize: true
                    }
                }],

            },
            {
                test: /\.less$/,
                use: ["style-loader,less-loader"]
            },
            {
                test: /\.svg$/,
                loaders: [
                    {
                        loader: 'babel-loader',
                        query: {
                            presets: ['es2015']
                        }
                    },
                    {
                        loader: 'react-svg-loader',
                        query: {
                            jsx: true
                        }
                    }
                ],
                exclude: /node_modules/
            }
        ]
    },
    plugins: [
        new webpack.DefinePlugin({
            'process.env': {
                'NODE_ENV': JSON.stringify('production')
            }
        }),
        new webpack.optimize.UglifyJsPlugin({
            compress: {
                screw_ie8: true
            }
        })
    ]

};

babelSettings.plugins.push("transform-react-inline-elements");
babelSettings.plugins.push("transform-react-constant-elements");

module.exports = config;

I run it with :

webpack --config webpack-dist.config.js -p --progress  --production --optimize-minimize

The output is still 2.2Mb which is unacceptable size.What config did I miss?

Edit packages.json looks like this:

{
  "name": "project",
  "version": "0.1.0",
  "private": true,
  "devDependencies": {
    "babel-cli": "^6.18.0",
    "babel-plugin-transform-decorators-legacy": "^1.3.4",
    "babel-plugin-transform-runtime": "^6.22.0",
    "babel-preset-es2015": "^6.22.0",
    "babel-preset-react": "^6.22.0",
    "babel-preset-stage-3": "^6.22.0",
    "babelify": "^7.3.0",
    "browserify": "^13.3.0",
    "css-loader": "^0.28.0",
    "exorcist": "^0.4.0",
    "gulp-livereload": "^3.8.1",
    "gulp-sourcemaps": "^2.4.0",
    "less": "^2.7.2",
    "less-loader": "^2.2.3",
    "react-edit-inline": "^1.0.8",
    "react-image-fallback": "^4.0.1",
    "react-scripts": "0.8.5",
    "redux-devtools-extension": "^2.13.0",
    "remote-redux-devtools": "^0.5.0",
    "riek": "^1.0.7",
    "style-loader": "^0.13.1",
    "svg-react-loader": "^0.4.0-beta.2",
    "vinyl-buffer": "^1.0.0",
    "watchify": "^3.8.0",
    "webpack": "^2.3.2"
  },
  "dependencies": {
    "axios": "^0.16.0",
    "barcoder": "^2.0.1",
    "escape-string-regexp": "^1.0.5",
    "frisbee": "^1.1.7",
    "i18next": "^5.0.0",
    "i18next-browser-languagedetector": "^1.0.1",
    "i18next-xhr-backend": "^1.3.0",
    "immutability-helper": "^2.1.1",
    "lodash": "^4.17.4",
    "qrcode.react": "^0.6.1",
    "rc-time-picker": "^2.3.3",
    "react": "^15.4.2",
    "react-autosuggest": "^8.0.0",
    "react-bootstrap": "^0.30.7",
    "react-cards": "^0.2.2",
    "react-collapse": "^2.3.3",
    "react-cookie": "^1.0.4",
    "react-dom": "^15.4.2",
    "react-dropzone": "^3.10.0",
    "react-height": "^2.2.0",
    "react-highlight-words": "^0.6.0",
    "react-i18next": "^2.0.0",
    "react-infinite-scroller": "^1.0.4",
    "react-input-autosize": "^1.1.0",
    "react-isolated-scroll": "^0.1.0",
    "react-loaders": "^2.3.0",
    "react-motion": "^0.4.7",
    "react-number-input": "^15.0.0-rc2",
    "react-numeric-input": "^2.0.7",
    "react-popover": "^0.4.4",
    "react-preload": "^0.5.0",
    "react-redux": "^5.0.2",
    "react-redux-form": "^1.5.4",
    "react-router-dom": "^4.0.0",
    "react-select": "^1.0.0-rc.3",
    "react-svg-loader": "^1.1.1",
    "react-switch-button": "^2.1.1",
    "react-tabs": "^0.8.2",
    "react-tagsinput": "^3.14.0",
    "redux": "^3.6.0",
    "redux-thunk": "^2.2.0",
    "simple-react-pdf": "^1.0.6",
    "style-it": "^1.5.5",
    "throttle-debounce": "^1.0.1",
    "validator": "^6.2.1"
  },


问:
can i implement Openjdk and create a new JDK which is redistributable?, without passing tests of tck or any special license?
Can i implement OpenJdk and create my own JDK and redistribute it? without passing tests of Technology Compatibility Kit(TCK) or does it require any special license to be called it as JDK?

I just found that many of the third party vendors of JDK are written on top of OpenJdk by doing tweak changes, do they require any TCK (or) License for their Redistributable JDK ?

答:
IANAL. I have been working with OpenJDK for a while, but I don't understand all the legalities myself. Here's my understanding.

To be able to call something "Java" requires getting a license from the term "Java" which is owned by Oracle.

The TCK is not part of OpenJDK itself. It's a separate product available under a non-Free license. The process to get a TCK for OpenJDK is avialable here: http://openjdk.java.net/groups/conformance/JckAccess/ but I have heard stories where actually getting access is non-trivial. Your experience may vary.

You can definitely take OpenJDK modify it and release the results, claiming it is a fork of OpenJDK. This is pretty much what every Linux distribution does - they take OpenJDK and patch it (even if it's minor changes) and then build/release it. You can't call it "Java" unless you have Oracle's approval and you can't claim it has passed the TCK unless it actually has.

As far as I know, every single vendor that redistributes something and calls it Java has passed the TCK and has permission to call it "Java".

As for taking OpenJDK source, there's a long explanation here. I am 99.9% sure every single implementation uses the OpenJDK class libraries, at least. And every single OpenJDK contributor agrees to the Oracle Contributor Agreement which lets Oracle re-license OpenJDK under another license. So Oracle and other third party non-OpenJDK vendors can take OpenJDK, get a license from Oracle and publish their JDK under a license that's not the OpenJDK license.


问:
OAuth and user change of password
With this workflow:

We are an integrator with no users of our own. Our clients will each
have their own DocuSign account with their own users.

We'll send envelopes for them and they'll authenticate using OAuth in our
application. We'll store the tokens, etc. for future
authentication/authorization.

User goes to the DocuSign website and changes their password.

Will that invalidate the OAuth token? If so, what is the best way to determine that the token is now invalid and that we need to get a new one for the user?

答:
The oAuth token will still be valid even when the user changes their DocuSign password.

However the user can explicitly revoke the access to your app through Docusign if they want to.

Title: OAuth and user change of password


问:
Naming convention for posix flags
I'm writing a console application which allows several Posix flags to be set.

This is what I'm using currently. Words in the flags are concatenated with a dash:

```<code>  -p, --broker-port int     Broker Port (default 1883)
  -u, --broker-url string   Broker URL (default "localhost")
  -c, --client-id string    MQTT Client Id
  -r, --room string         Room where sensor is located (default "myroom")
  -f, --floor string        Floor, where room is located (default "basement")
</code>```

However I have also seen applications using CamelCase to concatenate pflags.

The official GNU coding standard does not specify how to concatenate words in posix flags.

What is the right way?

Thanks

答:
The answer seems to be buried in the GNU docs here.

GNU adds long options to these conventions. Long options consist of
  ‘--’ followed by a name made of alphanumeric characters and dashes.
  Option names are typically one to three words long, with hyphens to
  separate words. Users can abbreviate the option names as long as the
  abbreviations are unique.

What you've got follows the convention; camel case does not.

Title: Naming convention for posix flags

Body:
I'm writing a console application which allows several Posix flags to be set.

This is what I'm using currently. Words in the flags are concatenated with a dash:

  -p, --broker-port int     Broker Port (default 1883)
  -u, --broker-url string   Broker URL (default "localhost")
  -c, --client-id string    MQTT Client Id
  -r, --room string         Room where sensor is located (default "myroom")
  -f, --floor string        Floor, where room is located (default "basement")

However I have also seen applications using CamelCase to concatenate pflags.

The official GNU coding standard does not specify how to concatenate words in posix flags.

What is the right way?

Thanks


问:
Determining if a UIViewController is being presented modally
My application's main window contains a xib-based UITabBarController (fully configured in Interface Builder) that can also be presented modally (much like the Music.app "Add songs to playlist" modal view). The UITabBarController contains a number of UINavigationControllers which in turn contain subclassed UITableViewControllers. This is how I'm currently detecting if the subclassed UITableViewController is being presented inside a modal UITabBarController:

```<code>- (void)viewDidLoad {
    [super viewDidLoad];

    self.isModal = NO;

    UIViewController *child     = self;
    UIViewController *parent    = self.parentViewController;
    while (parent) {
        if (parent.modalViewController && parent.modalViewController == child) {
            self.isModal = YES;
            break;
        }
        child   = parent;
        parent  = parent.parentViewController;
    }

    if (self.isModal) {
        // modal additions, eg. Done button, navigationItem.prompt
    }
    else {
        // normal additions, eg. Now Playing button
    }
}
</code>```

Is there a way to do this that doesn't involve walking up the parentViewController tree or subclassing all the intermediate view controllers to pass down the isModal state when they are initialized?

答:
There is a much easier way in these Swift days.</p>

```<code>extension UIViewController {

    var isPresentedModally: Bool {
        return presentingViewController?.presentedViewController == self || parent?.isPresentedModally == true
    }

}
</code>```

Body:
My application's main window contains a xib-based UITabBarController (fully configured in Interface Builder) that can also be presented modally (much like the Music.app "Add songs to playlist" modal view). The UITabBarController contains a number of UINavigationControllers which in turn contain subclassed UITableViewControllers. This is how I'm currently detecting if the subclassed UITableViewController is being presented inside a modal UITabBarController:

- (void)viewDidLoad {
    [super viewDidLoad];

    self.isModal = NO;

    UIViewController *child     = self;
    UIViewController *parent    = self.parentViewController;
    while (parent) {
        if (parent.modalViewController && parent.modalViewController == child) {
            self.isModal = YES;
            break;
        }
        child   = parent;
        parent  = parent.parentViewController;
    }

    if (self.isModal) {
        // modal additions, eg. Done button, navigationItem.prompt
    }
    else {
        // normal additions, eg. Now Playing button
    }
}

Is there a way to do this that doesn't involve walking up the parentViewController tree or subclassing all the intermediate view controllers to pass down the isModal state when they are initialized?

Body:
There is a much easier way in these Swift days.

extension UIViewController {

    var isPresentedModally: Bool {
        return presentingViewController?.presentedViewController == self || parent?.isPresentedModally == true
    }

}