问:
Swift iOS: Getting Cell's IndexPath From Custom Cell Class
I'm trying to get the cell indexPath from within the cell's custom class.

When I put it this way:

```<code>let indexPath :NSIndexPath = (self.superview!.superview as! UITableView).indexPath(for: self)! as NSIndexPath
</code>```

It works fine on iOS 10 device, but on iOS 11 simulator, it gives this error

```<code>Could not cast value of type 'UIView' (0x10636c5d8) to 'UITableView'
</code>```

So, then when I change it and put it this way:

```<code>let indexPath :NSIndexPath = (self.superview! as! UITableView).indexPath(for: self)! as NSIndexPath
</code>```

It works fine on iOS 11 simulator, but on the iOS 10 device, it gives this error:

```<code>Could not cast value of type 'UITableViewWrapperView'  to 'UITableView'
</code>```

What can I do to get it working on both iOS 10 and 11?

答:
Though this is a bad design to get index path inside a custom cell.You can check on which version you are running and implement the logic to get indexPath.

```<code>// INDEXPATH VARIABLE
var indexPath :NSIndexPath!

// CHECK FOR IOS 11 AND ABOVE
if #available(iOS 11, *) {
 // CALCULATE USING TABLE VIEW
 indexPath = (self.superview! as! UITableView).indexPath(for: self)! as NSIndexPath
} else {
  // CALCULATE USING TABLEVIEW WRAPPER
  indexPath = (self.superview!.superview as! UITableView).indexPath(for: self)! as NSIndexPath
}
</code>```

Hope this helps.

Body:
I'm trying to get the cell indexPath from within the cell's custom class.

When I put it this way:

let indexPath :NSIndexPath = (self.superview!.superview as! UITableView).indexPath(for: self)! as NSIndexPath

It works fine on iOS 10 device, but on iOS 11 simulator, it gives this error

Could not cast value of type 'UIView' (0x10636c5d8) to 'UITableView'

So, then when I change it and put it this way:

let indexPath :NSIndexPath = (self.superview! as! UITableView).indexPath(for: self)! as NSIndexPath

It works fine on iOS 11 simulator, but on the iOS 10 device, it gives this error:

Could not cast value of type 'UITableViewWrapperView'  to 'UITableView'

What can I do to get it working on both iOS 10 and 11?

Body:
Though this is a bad design to get index path inside a custom cell.You can check on which version you are running and implement the logic to get indexPath.

// INDEXPATH VARIABLE
var indexPath :NSIndexPath!

// CHECK FOR IOS 11 AND ABOVE
if #available(iOS 11, *) {
 // CALCULATE USING TABLE VIEW
 indexPath = (self.superview! as! UITableView).indexPath(for: self)! as NSIndexPath
} else {
  // CALCULATE USING TABLEVIEW WRAPPER
  indexPath = (self.superview!.superview as! UITableView).indexPath(for: self)! as NSIndexPath
}

Hope this helps.


来源: stackexchange

问:
How to change the data type of a table column to enum?
I have a table "ENGINE" in a Postgres DB, in which I have to change the datatype of a column named loglevel from string to enum.

However, I am not able to understand instructions in the manual:

```<code>ALTER [ COLUMN ] column TYPE type [ USING expression ]
</code>```

答:
enum is not a data type per se. It's a class of data types. (Generally, you can replace any enum with a FK column to a 1:n table.) And "string" is not a data type at all in Postgres. I assume we are talking about text or varchar? If so, these are the steps for your task:

Step 1

Create new enum type if it does not exist, yet.

Let's call it loglevel. It has to include all distinct values from your string column or the type cast will fail. This DO command takes care of it:

DO
$$
BEGIN
EXECUTE (
   SELECT 'CREATE TYPE loglevel AS ENUM ('
        || string_agg(quote_literal(loglevel), ', ')
        || ')'
   FROM  (
      SELECT loglevel
      FROM   "ENGINE"
      WHERE  loglevel IS NOT NULL  -- exclude NULL if present
      GROUP  BY 1
      ORDER  BY 1
      ) sub
   );
END
$$;
```
<p>We have to exclude NULL if present, that cannot be listed as enum value. (Any <code>enum</code> type can be NULL anyway.)</p>
<p>Related:</p>
<ul>
<li>Algebraic Data Types in Postgres</li>
</ul>
<h3>Step 2</h3>
<p>Change the data type of the column:</p>
<p>You have to specify <code>USING loglevel::loglevel</code> explicitely, since there is no implicit cast between any string type (<code>text</code>, <code>varchar</code>, ...) and the new <code>enum</code> data type:</p>
```ALTER TABLE "ENGINE" ALTER loglevel TYPE loglevel USING loglevel::loglevel;
```

Details:

Rails Migrations: tried to change the type of column from string to integer

ContentLicense: CC BY-SA 3.0

Body:
I have a table "ENGINE" in a Postgres DB, in which I have to change the datatype of a column named loglevel from string to enum.

However, I am not able to understand instructions in the manual:

ALTER [ COLUMN ] column TYPE type [ USING expression ]

Body:
enum is not a data type per se. It's a class of data types. (Generally, you can replace any enum with a FK column to a 1:n table.) And "string" is not a data type at all in Postgres. I assume we are talking about text or varchar? If so, these are the steps for your task:

Step 1

Create new enum type if it does not exist, yet.

Let's call it loglevel. It has to include all distinct values from your string column or the type cast will fail. This DO command takes care of it:

DO
$$
BEGIN
EXECUTE (
   SELECT 'CREATE TYPE loglevel AS ENUM ('
        || string_agg(quote_literal(loglevel), ', ')
        || ')'
   FROM  (
      SELECT loglevel
      FROM   "ENGINE"
      WHERE  loglevel IS NOT NULL  -- exclude NULL if present
      GROUP  BY 1
      ORDER  BY 1
      ) sub
   );
END
$$;

We have to exclude NULL if present, that cannot be listed as enum value. (Any enum type can be NULL anyway.)

Related:

Algebraic Data Types in Postgres

Step 2

Change the data type of the column:

You have to specify USING loglevel::loglevel explicitely, since there is no implicit cast between any string type (text, varchar, ...) and the new enum data type:

ALTER TABLE "ENGINE" ALTER loglevel TYPE loglevel USING loglevel::loglevel;

Details:

Rails Migrations: tried to change the type of column from string to integer

ContentLicense: CC BY-SA 4.0


问:
Gap between inline-block elements with whitespace: nowrap and overflow: scroll parent element
I wanted to display a table (but I'm using div) that will scroll the overflow since the table is long. The problem I'm getting at is there's an unknown gap between my divs.

And here's the snippet: what's causing the unwanted gaps between columns (divs)?

.mobile-cross-reference {
  border: 1px solid #2980b9;
  color: #333;
  float: left;
  margin: 2%;
  width: 96%;
}

.m-grid-scroll {
  overflow-x: scroll;
}

.m-grid-header {
  background-color: #2980b9;
  color: white;
  text-align: center;
}

.m-grid-header,
.m-grid-row {
  float: left;
  width: 100%;
}

.m-grid-header-col {
  background-color: #2980b9 !important;
}

.m-grid-row-inline {
  background-color: transparent;
  display: inline-block;
  float: none;
  white-space: nowrap;
}

.m-grid-col {
  border-right: 1px solid #ccc;
  float: left;
  padding: 1% 0 1% 1%;
}

.m-grid-col:last-child {
  border-right: 0;
}

.m-grid-col3 {
  width: 31%;
}

.m-grid-inline {
  display: inline-block;
  float: none;
  margin: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="mobile-cross-reference m-grid-scroll">
      <div class="m-grid-header m-grid-row-inline">
        <div class="m-grid-col m-grid-inline m-grid-col3 m-grid-header-col">Bourns</div>
        <div class="m-grid-col m-grid-inline m-grid-col3 m-grid-header-col">BI Tech</div>
        <div class="m-grid-col m-grid-inline m-grid-col3 m-grid-header-col">Dale/Vishay</div>
        <div class="m-grid-col m-grid-inline m-grid-col3 m-grid-header-col">Philips/Mepco</div>
        <div class="m-grid-col m-grid-inline m-grid-col3 m-grid-header-col">Murata</div>
        <div class="m-grid-col m-grid-inline m-grid-col3 m-grid-header-col">Panasonic</div>
        <div class="m-grid-col m-grid-inline m-grid-col3 m-grid-header-col">Spectrol</div>
        <div class="m-grid-col m-grid-inline m-grid-col3 m-grid-header-col">Mil Spec</div>
      </div>
      <div class="m-grid-row m-grid-row-inline">
        <div class="m-grid-col m-grid-inline m-grid-col3">Bourns</div>
        <div class="m-grid-col m-grid-inline m-grid-col3">BI Tech</div>
        <div class="m-grid-col m-grid-inline m-grid-col3">Dale/Vishay</div>
        <div class="m-grid-col m-grid-inline m-grid-col3">Philips/Mepco</div>
        <div class="m-grid-col m-grid-inline m-grid-col3">Murata</div>
        <div class="m-grid-col m-grid-inline m-grid-col3">Panasonic</div>
        <div class="m-grid-col m-grid-inline m-grid-col3">Spectrol</div>
        <div class="m-grid-col m-grid-inline m-grid-col3">Mil Spec</div>
      </div>
    </div></code>```

答:
Interestingly enough, the white space between the div tags. See the first columns.

.mobile-cross-reference {
  border: 1px solid #2980b9;
  color: #333;

}

.m-grid-scroll {
  overflow-x: scroll;
}

.m-grid-header {
  background-color: #2980b9;
  color: white;
  text-align: center;
}

.m-grid-header,
.m-grid-row {

  width: 100%;
  white-space:nowrap;
  display:block;
}

.m-grid-header-col {
  background-color: #2980b9 !important;
}

.m-grid-row-inline {
  background-color: transparent;
  white-space: nowrap;
}

.m-grid-col {
  border-right: 1px solid #ccc;
  padding:0px;
  margin:0px;

}

.m-grid-col:last-child {
  border-right: 0;
}

.m-grid-col3 {
  width: 31%;
}

.m-grid-inline {
  display: inline-block;

  margin: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="mobile-cross-reference m-grid-scroll">
      <div class="m-grid-header m-grid-row-inline"><div class="m-grid-col m-grid-inline m-grid-col3 m-grid-header-col">Bourns</div><div class="m-grid-col m-grid-inline m-grid-col3 m-grid-header-col">BI Tech</div><div class="m-grid-col m-grid-inline m-grid-col3 m-grid-header-col">Dale/Vishay</div>
        <div class="m-grid-col m-grid-inline m-grid-col3 m-grid-header-col">Philips/Mepco</div>
        <div class="m-grid-col m-grid-inline m-grid-col3 m-grid-header-col">Murata</div>
        <div class="m-grid-col m-grid-inline m-grid-col3 m-grid-header-col">Panasonic</div>
        <div class="m-grid-col m-grid-inline m-grid-col3 m-grid-header-col">Spectrol</div>
        <div class="m-grid-col m-grid-inline m-grid-col3 m-grid-header-col">Mil Spec</div>
      </div>
      <div class="m-grid-row m-grid-row-inline">
        <div class="m-grid-col m-grid-inline m-grid-col3">Bourns</div>
        <div class="m-grid-col m-grid-inline m-grid-col3">BI Tech</div>
        <div class="m-grid-col m-grid-inline m-grid-col3">Dale/Vishay</div>
        <div class="m-grid-col m-grid-inline m-grid-col3">Philips/Mepco</div>
        <div class="m-grid-col m-grid-inline m-grid-col3">Murata</div>
        <div class="m-grid-col m-grid-inline m-grid-col3">Panasonic</div>
        <div class="m-grid-col m-grid-inline m-grid-col3">Spectrol</div>
        <div class="m-grid-col m-grid-inline m-grid-col3">Mil Spec</div>
      </div>
    </div></code>```

Body:
I wanted to display a table (but I'm using div) that will scroll the overflow since the table is long. The problem I'm getting at is there's an unknown gap between my divs.

And here's the snippet: what's causing the unwanted gaps between columns (divs)?

.mobile-cross-reference {
  border: 1px solid #2980b9;
  color: #333;
  float: left;
  margin: 2%;
  width: 96%;
}

.m-grid-scroll {
  overflow-x: scroll;
}

.m-grid-header {
  background-color: #2980b9;
  color: white;
  text-align: center;
}

.m-grid-header,
.m-grid-row {
  float: left;
  width: 100%;
}

.m-grid-header-col {
  background-color: #2980b9 !important;
}

.m-grid-row-inline {
  background-color: transparent;
  display: inline-block;
  float: none;
  white-space: nowrap;
}

.m-grid-col {
  border-right: 1px solid #ccc;
  float: left;
  padding: 1% 0 1% 1%;
}

.m-grid-col:last-child {
  border-right: 0;
}

.m-grid-col3 {
  width: 31%;
}

.m-grid-inline {
  display: inline-block;
  float: none;
  margin: 0;
}

Bourns

BI Tech

Dale/Vishay

Philips/Mepco

Murata

Panasonic

Spectrol

Mil Spec

Bourns

BI Tech

Dale/Vishay

Philips/Mepco

Murata

Panasonic

Spectrol

Mil Spec

Body:
Interestingly enough, the white space between the div tags. See the first columns.

.mobile-cross-reference {
  border: 1px solid #2980b9;
  color: #333;

}

.m-grid-scroll {
  overflow-x: scroll;
}

.m-grid-header {
  background-color: #2980b9;
  color: white;
  text-align: center;
}

.m-grid-header,
.m-grid-row {

  width: 100%;
  white-space:nowrap;
  display:block;
}

.m-grid-header-col {
  background-color: #2980b9 !important;
}

.m-grid-row-inline {
  background-color: transparent;
  white-space: nowrap;
}

.m-grid-col {
  border-right: 1px solid #ccc;
  padding:0px;
  margin:0px;

}

.m-grid-col:last-child {
  border-right: 0;
}

.m-grid-col3 {
  width: 31%;
}

.m-grid-inline {
  display: inline-block;

  margin: 0;
}

<div class="mobile-cross-reference m-grid-scroll">
      <div class="m-grid-header m-grid-row-inline"><div class="m-grid-col m-grid-inline m-grid-col3 m-grid-header-col">Bourns</div><div class="m-grid-col m-grid-inline m-grid-col3 m-grid-header-col">BI Tech</div><div class="m-grid-col m-grid-inline m-grid-col3 m-grid-header-col">Dale/Vishay</div>
        <div class="m-grid-col m-grid-inline m-grid-col3 m-grid-header-col">Philips/Mepco</div>
        <div class="m-grid-col m-grid-inline m-grid-col3 m-grid-header-col">Murata</div>
        <div class="m-grid-col m-grid-inline m-grid-col3 m-grid-header-col">Panasonic</div>
        <div class="m-grid-col m-grid-inline m-grid-col3 m-grid-header-col">Spectrol</div>
        <div class="m-grid-col m-grid-inline m-grid-col3 m-grid-header-col">Mil Spec</div>
      </div>
      <div class="m-grid-row m-grid-row-inline">
        <div class="m-grid-col m-grid-inline m-grid-col3">Bourns</div>
        <div class="m-grid-col m-grid-inline m-grid-col3">BI Tech</div>
        <div class="m-grid-col m-grid-inline m-grid-col3">Dale/Vishay</div>
        <div class="m-grid-col m-grid-inline m-grid-col3">Philips/Mepco</div>
        <div class="m-grid-col m-grid-inline m-grid-col3">Murata</div>
        <div class="m-grid-col m-grid-inline m-grid-col3">Panasonic</div>
        <div class="m-grid-col m-grid-inline m-grid-col3">Spectrol</div>
        <div class="m-grid-col m-grid-inline m-grid-col3">Mil Spec</div>
      </div>
    </div>


问:
JSON jsonObject.optString() returns String "null"
I'm developing an Android App which uses JSON for the server communication and I've got a weird problem when I'm trying to parse my json file.

This is my json from the server

```<code>{
    "street2": null,
    "province": null,
    "street1": null,
    "postalCode": null,
    "country": null,
    "city": null
}
</code>```

I'm getting the value for City by calling String city = address.optString("city", "") on my address Json-object. For this situation I'm expecting cityto be empty (that's what optString is here for isn't it?) but in fact it contains the String "null". So further null- or isEmpty-checks will return false as the String contains text. If I call address.isNull("city") it returns true which is correct. Only optString fails.

I couldn't find anything on Google or Stackoverflow for this problem. I don't really understand how it can happen as I thought optString would do exactly what I expected. Anybody knows what's going wrong here?

答:
Using Matt Quigley's answer as a basis, here is the code if you desire to mimic the full functionality of optString, including the fallback portion, written in Kotlin and Java.

Kotlin:

```<code>fun optString(json: JSONObject, key: String, fallback: String?): String? {
    var stringToReturn = fallback
    if (!json.isNull(key)) {
        stringToReturn = json.optString(key, null)
    }
    return stringToReturn
}
</code>```

Java:

```<code>public static String optString(JSONObject json, String key, String fallback) {
    String stringToReturn = fallback;
    if (!json.isNull(key)) {
        stringToReturn = json.optString(key, null);
    }
    return stringToReturn;
 }
</code>```

Simply pass in null for the fallback parameter if you don't need the fallback.

Body:
I'm developing an Android App which uses JSON for the server communication and I've got a weird problem when I'm trying to parse my json file.

This is my json from the server

{
    "street2": null,
    "province": null,
    "street1": null,
    "postalCode": null,
    "country": null,
    "city": null
}

I'm getting the value for City by calling String city = address.optString("city", "") on my address Json-object. For this situation I'm expecting cityto be empty (that's what optString is here for isn't it?) but in fact it contains the String "null". So further null- or isEmpty-checks will return false as the String contains text. If I call address.isNull("city") it returns true which is correct. Only optString fails.

I couldn't find anything on Google or Stackoverflow for this problem. I don't really understand how it can happen as I thought optString would do exactly what I expected. Anybody knows what's going wrong here?

Body:
Using Matt Quigley's answer as a basis, here is the code if you desire to mimic the full functionality of optString, including the fallback portion, written in Kotlin and Java.

Kotlin:

fun optString(json: JSONObject, key: String, fallback: String?): String? {
    var stringToReturn = fallback
    if (!json.isNull(key)) {
        stringToReturn = json.optString(key, null)
    }
    return stringToReturn
}

Java:

public static String optString(JSONObject json, String key, String fallback) {
    String stringToReturn = fallback;
    if (!json.isNull(key)) {
        stringToReturn = json.optString(key, null);
    }
    return stringToReturn;
 }

Simply pass in null for the fallback parameter if you don't need the fallback.


问:
How to kill a web process
I have a web script that takes a really long time to run (and it's supposed to take a long time). By "web script" I mean a script that's run by visiting a page in a browser and opposed to executed on the command line. The script is in PHP and I'm on a LAMP stack.

How can I find and kill this process if I want to?

"Kill" might be the wrong word. I just want the script to stop. I could conceivably make this script "watch" for some state of my system to change, and then halt when it notices that change. If I do that, I'm not sure what the best way to do that would be. In any case, I'm completely open to any suggestions.

答:
When the script starts, write its pid to a file, something like

```<code> file_put_contents(getmypid ().".pid","Running");
</code>```

And when the script is done, it deletes the file.

You then create another script that will run form cron. It looks for pid files over a certain age, and does a kill $pid on them

Simple.

ContentLicense: CC BY-SA 2.5

Title: How to kill a web process

Body:
When the script starts, write its pid to a file, something like

 file_put_contents(getmypid ().".pid","Running");

And when the script is done, it deletes the file.

You then create another script that will run form cron. It looks for pid files over a certain age, and does a kill $pid on them

Simple.


问:
Shuffling the training dataset with Tensorflow object detection api
I'm working on a logo detection algorithm using the Faster-RCNN model with the Tensorflow object detection api.
My dataset is alphabetically ordered (so there are a hundred adidas logo, then hundred apple logo etc.). And i would like it to be shuffled while training.

I've put some values in the config file:

```<code>train_input_reader:{
          shuffle: true
          queue_capacity: some value
          min_after_dequeue : some other value}
</code>```

However whatever are the values, I'm putting in, algorithm is at first training on all of the a's logos (adidas, apple and so on) and only a lapse of time after starting to see the b's logos (bmw etc.) and the c's one etc.

Of course I could just shuffle my input dataset directly, but I would like to understand the logic behind it.

PS: I've seen this post about shuffling and min_after_dequeue, but I still dont quite get it. My batch size is 1 so it shouldn't be using tf.train.shuffle_batch() but only tf.RandomShuffleQueue

My training dataset size is 5000 and if I write min_after_dequeue: 4000 or 5000 it is still not shuffled right. Why though?

Update:
@AllenLavoie It's a bit hard for me; as there is a lot of dependencies and I'm new to Tensorflow.
But in the end the queue is constructed by

```<code>tf.contrib.slim.parallel_reader.parallel_read(    _, string_tensor = parallel_reader.parallel_read(
        config.input_path,
        reader_class=tf.TFRecordReader,
        num_epochs=(input_reader_config.num_epochs
                    if input_reader_config.num_epochs else None),
        num_readers=input_reader_config.num_readers,
        shuffle=input_reader_config.shuffle,
        dtypes=[tf.string, tf.string],
        capacity=input_reader_config.queue_capacity,
        min_after_dequeue=input_reader_config.min_after_dequeue)
</code>```

It seems that when I'm putting num_readers = 1 in the config file the dataset is finally shuffling as I want, (at least in the beginning), but when there are more somehow on the start the logos are getting in the alphabetical order.

答: I recommend shuffling the dataset prior to training.  The way shuffling currently happens is imperfect and my guess at what is happening is that at the beginning the queue starts off empty and only gets examples that start with 'A' --- after a while it may be more shuffled, but there is no getting around the beginning part when the queue hasn't been filled yet.  </p>

Body:
I'm working on a logo detection algorithm using the Faster-RCNN model with the Tensorflow object detection api.
My dataset is alphabetically ordered (so there are a hundred adidas logo, then hundred apple logo etc.). And i would like it to be shuffled while training.

I've put some values in the config file:

train_input_reader:{
          shuffle: true
          queue_capacity: some value
          min_after_dequeue : some other value}

However whatever are the values, I'm putting in, algorithm is at first training on all of the a's logos (adidas, apple and so on) and only a lapse of time after starting to see the b's logos (bmw etc.) and the c's one etc.

Of course I could just shuffle my input dataset directly, but I would like to understand the logic behind it.

PS: I've seen this post about shuffling and min_after_dequeue, but I still dont quite get it. My batch size is 1 so it shouldn't be using tf.train.shuffle_batch() but only tf.RandomShuffleQueue

My training dataset size is 5000 and if I write min_after_dequeue: 4000 or 5000 it is still not shuffled right. Why though?

Update:
@AllenLavoie It's a bit hard for me; as there is a lot of dependencies and I'm new to Tensorflow.
But in the end the queue is constructed by

tf.contrib.slim.parallel_reader.parallel_read(    _, string_tensor = parallel_reader.parallel_read(
        config.input_path,
        reader_class=tf.TFRecordReader,
        num_epochs=(input_reader_config.num_epochs
                    if input_reader_config.num_epochs else None),
        num_readers=input_reader_config.num_readers,
        shuffle=input_reader_config.shuffle,
        dtypes=[tf.string, tf.string],
        capacity=input_reader_config.queue_capacity,
        min_after_dequeue=input_reader_config.min_after_dequeue)

It seems that when I'm putting num_readers = 1 in the config file the dataset is finally shuffling as I want, (at least in the beginning), but when there are more somehow on the start the logos are getting in the alphabetical order.


问:
Result of validation different between Chrome and the AMPProject Validator
I'm trying to get my AMP pages working, and I have a weird issue: everything seems good to me regarding all the guidelines to have valid AMP pages, when I ask Chrome to validate one of my pages, it works like a charm, but when I go on the AMPProject Validator page, the same page I check fails the validation, and the code that the validator presents me looks like a mix between my regular theme and my AMP theme.

The website runs on Drupal, and I did not have this issue on my dev environment, and the only difference between my dev and production environments is the presence of Cloudflare in front of my production environment. Can the problem come from Cloudflare? Did anyone already have that kind of issue?

Thanks a lot in advance!
Francois

答:
The most likely answer is that your server is responding with different outputs to your browser's HTTP request vs the HTTP request that https://validator.ampproject.org/ uses to fetch the same page. The requests will have different useragents, cookies, ips, etc. Check your server configuration to see what's going on and why it is responding differently.

The text in the preview area on https://validator.ampproject.org/ displays exactly what your server returned to that tool.


问:
Convert Token Numbers to Strings in ANTLR4
I'm trying to use ANTLR4 to build a sort of autocomplete system using the getExpectedTokens() function that can be called when the parser experiences an error. getExpectedTokens() returns an IntervalSet, containing all the token numbers of the acceptable tokens at that point in the parse. Is there some mapping from the token numbers back to the actual Tokens themselves? (So, for example, if one of the expected tokens is a keyword that keyword can be displayed to the user in some way).

答:
Using getSymbolicName() worked for me.

So you could do parser.getVocabulary().getSymbolicName(tokenType) where tokenType is an int.


问:
Why does width and height of a flex item affect how a flex item is rendered?
An image in a flexbox that has a max-height style appears to render differently depending on whether it has its height and width attributes set.

The one with the attributes, set to the true width/height of the image, renders with its aspect ratio preserved, but the ones without the attributes respects the max-height and appear squashed.

.flex-parent {
  display: flex;
  max-height: 10vh;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="flex-parent">
  <img                          src="https://upload.wikimedia.org/wikipedia/commons/thumb/b/be/Red_eyed_tree_frog_edit2.jpg/320px-Red_eyed_tree_frog_edit2.jpg">
  <img width="320" height="240" src="https://upload.wikimedia.org/wikipedia/commons/thumb/b/be/Red_eyed_tree_frog_edit2.jpg/320px-Red_eyed_tree_frog_edit2.jpg">
</div></code>```

This is how is appears in Chrome 58 (and it appears similarly in Firefox 54).

Why do they render differently? What are the rules that govern this behaviour?

My (obviously incorrect) understanding is that height and width attributes overwrite the intrinsic height and width that is found when the image loads, and if the height and width attributes equal the dimensions of the image, there should be no difference in rendering once the image has loaded.

The context is making a page with responsive images, where each image

can have unique original dimensions

does not cause a reflow when it's loaded, i.e. the correct space is reserved on initial render (hence using height and width attributes)

can fit all on screen at once (hence me messing with vh in the CSS)

The frog image is from https://en.wikipedia.org/wiki/File:Red_eyed_tree_frog_edit2.jpg

答:
An initial setting of a flex container is align-items: stretch.

That means that flex items will expand across the cross axis of the container.

In a row-direction container, like in the question, the cross axis is vertical.

That means the items (images, in this case) will cover the full height of the container.

However, when a flex item has a defined cross size, that overrides the stretch default.

From the spec:

8.3. Cross-axis Alignment: the align-items and align-self
  properties

Flex items can be aligned in the cross axis of the current line of the
  flex container, similar to justify-content but in the perpendicular
  direction.

stretch

If the cross size property of the flex item computes to auto, and
  neither of the cross-axis margins are auto, the flex item is
  stretched.

This is the key language:

If the cross size property of the flex item computes to auto

And this is how the spec defines "cross size property":

The width or height of a flex item, whichever is in the cross
  dimension, is the item’s cross size. The cross size property is
  whichever of width or height that is in the cross dimension.

https://www.w3.org/TR/css-flexbox-1/#cross-size-property

So your code appears to be playing out as defined in the spec.

This is what you have:

.flex-parent {
  display: flex;
  max-height: 10vh;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="flex-parent">
  <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/b/be/Red_eyed_tree_frog_edit2.jpg/320px-Red_eyed_tree_frog_edit2.jpg">
  <img width="320" height="240" src="https://upload.wikimedia.org/wikipedia/commons/thumb/b/be/Red_eyed_tree_frog_edit2.jpg/320px-Red_eyed_tree_frog_edit2.jpg">
</div></code>```

The first image has no defined width (main size) or height (cross size), either in the CSS or the HTML. Its cross size, therefore, computes to auto.

This statement:

If the cross size property of the flex item computes to auto

... is true, and align-items: stretch goes into effect.

The image expands across the height of the container, which is 10px.

The second image, however, has explicit sizing. The cross size is defined in the HTML (height="240").

Now this statement:

If the cross size property of the flex item computes to auto

... is false, and align-items: stretch is overridden. The HTML height attribute prevails.

Two notes about the second image:

The image ignores the max-height limit on the container because an initial setting in CSS is overflow: visible.

The HTML width and height attributes map to their respective CSS properties. Hence, height="240" overrides the height: auto default. See below for the spec references.*

There are two other issues to consider when rendering images in a flex container.

The default minimum size of flex items. This setting prevents flex items from shrinking below the size of their content. Read this post for full details:

Why doesn't flex item shrink past content size?

Varying behavior among major browsers. Firefox, Chrome, Safari, Edge and IE11 don't always render images as flex items in the same way. Read this post for more details:

Flex in Firefox shrinks images automatically, but not in Chrome

Considering all factors above, here's my suggested solution:

.flex-parent {
  display: flex;
  max-height: 50vh; /* adjusted for demo */
}

.flex-parent {
  min-width: 0;
}

img {
  width: 100%;
  height: auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="flex-parent">
  <div>
    <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/b/be/Red_eyed_tree_frog_edit2.jpg/320px-Red_eyed_tree_frog_edit2.jpg">
  </div>
  <div>
    <img width="320" height="240" src="https://upload.wikimedia.org/wikipedia/commons/thumb/b/be/Red_eyed_tree_frog_edit2.jpg/320px-Red_eyed_tree_frog_edit2.jpg">
  </div>
</div></code>```

*The HTML width and height attributes map to their respective CSS properties. Hence, when specified, they override the CSS defaults. From the HTML5 spec:

10.4.3 Attributes for embedded content and
  images

The width and height attributes on applet, embed, iframe,
  object or video elements, and input elements with a type
  attribute in the Image Button state and that either represents an
  image or that the user expects will eventually represent an image,
  map to the dimension properties width and height on the element respectively.

10.2 The CSS user agent style sheet and presentational
  hints

When the text below says that an attribute on an element maps to the
  dimension property (or properties), it means that if the element has
  an attribute set, and parsing that attribute's value using the rules
  for parsing dimension
  values doesn't generate an error, then the user agent is expected to use the
  parsed dimension as the value for a presentational hint for
  properties, with the value given as a pixel length if the dimension
  was an integer, and with the value given as a percentage if the
  dimension was a percentage.

Body:
An image in a flexbox that has a max-height style appears to render differently depending on whether it has its height and width attributes set.

The one with the attributes, set to the true width/height of the image, renders with its aspect ratio preserved, but the ones without the attributes respects the max-height and appear squashed.

.flex-parent {
  display: flex;
  max-height: 10vh;
}

This is how is appears in Chrome 58 (and it appears similarly in Firefox 54).

Why do they render differently? What are the rules that govern this behaviour?

My (obviously incorrect) understanding is that height and width attributes overwrite the intrinsic height and width that is found when the image loads, and if the height and width attributes equal the dimensions of the image, there should be no difference in rendering once the image has loaded.

The context is making a page with responsive images, where each image

can have unique original dimensions

does not cause a reflow when it's loaded, i.e. the correct space is reserved on initial render (hence using height and width attributes)

can fit all on screen at once (hence me messing with vh in the CSS)

The frog image is from https://en.wikipedia.org/wiki/File:Red_eyed_tree_frog_edit2.jpg

Body:
An initial setting of a flex container is align-items: stretch.

That means that flex items will expand across the cross axis of the container.

In a row-direction container, like in the question, the cross axis is vertical.

That means the items (images, in this case) will cover the full height of the container.

However, when a flex item has a defined cross size, that overrides the stretch default.

From the spec:

8.3. Cross-axis Alignment: the align-items and align-self
  properties

Flex items can be aligned in the cross axis of the current line of the
  flex container, similar to justify-content but in the perpendicular
  direction.

stretch

If the cross size property of the flex item computes to auto, and
  neither of the cross-axis margins are auto, the flex item is
  stretched.

This is the key language:

If the cross size property of the flex item computes to auto

And this is how the spec defines "cross size property":

The width or height of a flex item, whichever is in the cross
  dimension, is the item’s cross size. The cross size property is
  whichever of width or height that is in the cross dimension.

https://www.w3.org/TR/css-flexbox-1/#cross-size-property

So your code appears to be playing out as defined in the spec.

This is what you have:

.flex-parent {
  display: flex;
  max-height: 10vh;
}

<div class="flex-parent">
  <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/b/be/Red_eyed_tree_frog_edit2.jpg/320px-Red_eyed_tree_frog_edit2.jpg">
  <img width="320" height="240" src="https://upload.wikimedia.org/wikipedia/commons/thumb/b/be/Red_eyed_tree_frog_edit2.jpg/320px-Red_eyed_tree_frog_edit2.jpg">
</div>

The first image has no defined width (main size) or height (cross size), either in the CSS or the HTML. Its cross size, therefore, computes to auto.

This statement:

If the cross size property of the flex item computes to auto

... is true, and align-items: stretch goes into effect.

The image expands across the height of the container, which is 10px.

The second image, however, has explicit sizing. The cross size is defined in the HTML (height="240").

Now this statement:

If the cross size property of the flex item computes to auto

... is false, and align-items: stretch is overridden. The HTML height attribute prevails.

Two notes about the second image:

The image ignores the max-height limit on the container because an initial setting in CSS is overflow: visible.

The HTML width and height attributes map to their respective CSS properties. Hence, height="240" overrides the height: auto default. See below for the spec references.*

There are two other issues to consider when rendering images in a flex container.

The default minimum size of flex items. This setting prevents flex items from shrinking below the size of their content. Read this post for full details:

Why doesn't flex item shrink past content size?

Varying behavior among major browsers. Firefox, Chrome, Safari, Edge and IE11 don't always render images as flex items in the same way. Read this post for more details:

Flex in Firefox shrinks images automatically, but not in Chrome

Considering all factors above, here's my suggested solution:

.flex-parent {
  display: flex;
  max-height: 50vh; /* adjusted for demo */
}

.flex-parent {
  min-width: 0;
}

img {
  width: 100%;
  height: auto;
}

<div class="flex-parent">
  <div>
    <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/b/be/Red_eyed_tree_frog_edit2.jpg/320px-Red_eyed_tree_frog_edit2.jpg">
  </div>
  <div>
    <img width="320" height="240" src="https://upload.wikimedia.org/wikipedia/commons/thumb/b/be/Red_eyed_tree_frog_edit2.jpg/320px-Red_eyed_tree_frog_edit2.jpg">
  </div>
</div>

*The HTML width and height attributes map to their respective CSS properties. Hence, when specified, they override the CSS defaults. From the HTML5 spec:

10.4.3 Attributes for embedded content and
  images

The width and height attributes on applet, embed, iframe,
  object or video elements, and input elements with a type
  attribute in the Image Button state and that either represents an
  image or that the user expects will eventually represent an image,
  map to the dimension properties width and height on the element respectively.

10.2 The CSS user agent style sheet and presentational
  hints

When the text below says that an attribute on an element maps to the
  dimension property (or properties), it means that if the element has
  an attribute set, and parsing that attribute's value using the rules
  for parsing dimension
  values doesn't generate an error, then the user agent is expected to use the
  parsed dimension as the value for a presentational hint for
  properties, with the value given as a pixel length if the dimension
  was an integer, and with the value given as a percentage if the
  dimension was a percentage.


问:
swift: Hermite round cap UIBezierpath
I have a section in my app where users can draw something.
Because of the slow refresh rate of touchesMoved, if a user draws fast, the line doesn't go smooth.
That's why I'm using Hermite. It sets a point for every refresh rate and then draws a UIBezierpath (with extension to make it smooth) between those points.
It's working perfectly ! I have a smooth design right now !

The only problem is that I'm sometimes not getting a round begin cap and if I switch on the same path back it also happens.

I think it has something to do with the code that draws a bezierpath between those points. So I'm looking for someone that also uses Hermite and knows how to fix this.

答:
The hermite spline is just a series of cubic beziers. But you can get these weird discrepancies with UIBezierPath. For example, there is a UIBezierPath rendering problem when you add multiple cubic beziers where the start, control point 1, control point 2, and end are all collinear. So, I've added a check to my hermite spline path to check to see if these four points are collinear, and, if so, just add a line in those cases.

So, instead of just:

```<code>addCurve(to: endPoint, controlPoint1: control1, controlPoint2: control2)
</code>```

I do:

```<code>let angleFull = angle(between: previousPoint, and: endPoint)
let angle1 = angle(between: previousPoint, and: control1)
let angle2 = angle(between: control2, and: endPoint)

if (angleFull == angle1 || angle1 == nil) && (angleFull == angle2 || angle2 == nil) {
    addLine(to: endPoint)
} else {
    addCurve(to: endPoint, controlPoint1: control1, controlPoint2: control2)
}
</code>```

Where

```<code>private func angle(between point1: CGPoint, and point2: CGPoint) -> CGFloat? {
    if point1 == point2 { return nil }
    return atan2(point2.y - point1.y, point2.x - point1.x)
}
</code>```

Another, more generalized solution (though a bit inelegant, IMHO),  approach, is to avoid joining these cubic curves entirely, so, before adding each cubic curve, do a move(to:) the previous point first. That should prevent all problems stemming from bugs related to joining cubic beziers.

Title: swift: Hermite round cap UIBezierpath

Body:
The hermite spline is just a series of cubic beziers. But you can get these weird discrepancies with UIBezierPath. For example, there is a UIBezierPath rendering problem when you add multiple cubic beziers where the start, control point 1, control point 2, and end are all collinear. So, I've added a check to my hermite spline path to check to see if these four points are collinear, and, if so, just add a line in those cases.

So, instead of just:

addCurve(to: endPoint, controlPoint1: control1, controlPoint2: control2)

I do:

let angleFull = angle(between: previousPoint, and: endPoint)
let angle1 = angle(between: previousPoint, and: control1)
let angle2 = angle(between: control2, and: endPoint)

if (angleFull == angle1 || angle1 == nil) && (angleFull == angle2 || angle2 == nil) {
    addLine(to: endPoint)
} else {
    addCurve(to: endPoint, controlPoint1: control1, controlPoint2: control2)
}

Where

private func angle(between point1: CGPoint, and point2: CGPoint) -> CGFloat? {
    if point1 == point2 { return nil }
    return atan2(point2.y - point1.y, point2.x - point1.x)
}

Another, more generalized solution (though a bit inelegant, IMHO),  approach, is to avoid joining these cubic curves entirely, so, before adding each cubic curve, do a move(to:) the previous point first. That should prevent all problems stemming from bugs related to joining cubic beziers.


问:
IntelliJ IDEA - caret behavior
I am trying to figure out one thing in IntelliJ IDEA 10:

current caret position

where caret moves after pressing DOWN arrow

where I want caret to be

Is such setting possible?

答: File | Settings (or Preferences on Mac) | Editor | Allow placement of caret after end of line:

Title: IntelliJ IDEA - caret behavior


问:
With PHP download full html with all files
When I download html code with php by using file_get_contents.
I get a part of what I need.

In a page some images and html tag's are created by JavaScrip.

On a chrome by pressing f12 I can find a link, but if I print out php downloaded html there is none. Is there a way to get everything as if it was view on a browser? Or save everything, like on a browser Save as...

答:
you can use wget

```<code>wget --page-requisites yourUrl
</code>```

and use exec or system to invoke through php.

Body:
you can use wget

wget --page-requisites yourUrl

and use exec or system to invoke through php.


问:
how to have both gRPC server and client at same process to achieve bi-directional communication(not server/client streaming)
I am pretty new to gRPC. I am thinking of using gRPC(Java) to do inter node(server) communication in my use case:

I have my own app logic to do some bookkeeping work on each node;

a node would need to communicate with others to reach some consensus(part of app logic) and this means a node need to both have client and server;

so how could I achieve this? server seems to be blocking after I call server.awaitTerminate(), right?  but do we also have the async version of the gRPC server in java? I bet yes, but I am not yet sure how could I leverage it.

for example, I have node A, B, C. I will need to have gRPC serverA, serverB, serverC start first, and for each server say A, I need client to connect to B and C. and in addition to communication part, app (say in node A)logic would be able to send out msg to other nodes(say B and C) via corresponding clients(to server B and C) if needed;and of course app logic would be notified when requests coming from B and C(because itself is a server).

I've been searching online for days and have gone through grpc/grpc-java related material and code example. however, i find there's not that much code example to show what is best practice and pattern to leverage gRPC...i'd really like to hear whatever suggestion you may have...

thanks in advance!

答:
Calling server.awaitTermination() in your main() is not required. The examples do so because grpc-java uses daemon threads by default. Thus, in the examples the only non-daemon thread is the main thread, and you need at least one non-daemon thread to keep the JVM running. See the documentation for java.lang.Thread.

awaitTermination() is not a serve_forever() method that processes new requests; awaitTermination() simply blocks the current thread until the grpc server has terminated. Processing happens on other threads.


问:
polymer change function of on-click button after clicking it
I have an expanding search bar that when I click, expands due to JS that I have written for the on-click function. I also want this on-click function to change so that I can actually search with the search bar when I type something in.

Is this actually possible?

Example...
click search icon > search bar expands > type in question and click search icon > searches...

HTML

```<code><paper-input id="searchMe" placeholder="Some text as a placeholder" on-input="inputText">
   <div suffix>
      <paper-icon-button class="clear" id="clearIcon" icon="clear" on-click="clearInput" style="display: none;"></paper-icon-button>
      <paper-icon-button class="search" id="searchIcon" icon="search" on-click="searchClick"></paper-icon-button>
    </div>
</paper-input>
</code>```

JS

```<code>searchClick : function() {
    /* expands the search bar */
    this.$.searchIcon.setAttribut('on-click','doSomethingElse');
}

doSomethingElse : function() {
    /* Does something else */
}
</code>```

UPDATE 03/07/17

I thought I had sorted this, but I have a bug with it...

I changed the search button when text is input to fire a new function (this will be used to actually search in the future as a PUT or something), however I can't get it to revert back to the original function afterwards... See my GIF for example.

```<code> doSomething : function() {
     this.$.searchMe.value = 'JS has been switched!';
     this.listen(this.$.iconSearch, 'click','searchClick');
 },
</code>```

答:
Why not simply toggle an expanded state property of the search bar on click and search or expand based on the current state.</p>

```<code>searchClick : function() {
    if(this.expanded){
     //do search
    }
    this.expanded = !this.expanded;
}
</code>```

Body:
I have an expanding search bar that when I click, expands due to JS that I have written for the on-click function. I also want this on-click function to change so that I can actually search with the search bar when I type something in.

Is this actually possible?

Example...
click search icon > search bar expands > type in question and click search icon > searches...

HTML

<paper-input id="searchMe" placeholder="Some text as a placeholder" on-input="inputText">

      <paper-icon-button class="clear" id="clearIcon" icon="clear" on-click="clearInput" style="display: none;"></paper-icon-button>
      <paper-icon-button class="search" id="searchIcon" icon="search" on-click="searchClick"></paper-icon-button>

</paper-input>

JS

searchClick : function() {
    /* expands the search bar */
    this.$.searchIcon.setAttribut('on-click','doSomethingElse');
}

doSomethingElse : function() {
    /* Does something else */
}

UPDATE 03/07/17

I thought I had sorted this, but I have a bug with it...

I changed the search button when text is input to fire a new function (this will be used to actually search in the future as a PUT or something), however I can't get it to revert back to the original function afterwards... See my GIF for example.

 doSomething : function() {
     this.$.searchMe.value = 'JS has been switched!';
     this.listen(this.$.iconSearch, 'click','searchClick');
 },

Body:
Why not simply toggle an expanded state property of the search bar on click and search or expand based on the current state.

searchClick : function() {
    if(this.expanded){
     //do search
    }
    this.expanded = !this.expanded;
}


问:
Firebase Phone number authentication Error
I am Using Firebase phone number login authentication All things are perfect

1) Provisioning profile

2) certificate

3) Signing methods Enable

4) Project setting with .12 file

5) everything should perfect

Issue
When I send mobile number for the OTP using thins method using this code

```<code>NSString *phoneNumber = @"+919428936703";

[[FIRPhoneAuthProvider provider]
 verifyPhoneNumber:phoneNumber
 completion:^(NSString * verificationID,
              NSError * error) {

     NSLog(@"VARIFICATION CODE %@", verificationID);
     NSLog(@"Error %@", error);

     if (!error){

     }else{

     }
 }];
</code>```

Also get call methods

```<code>- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    // Pass device token to auth.
    [[FIRAuth auth] setAPNSToken:deviceToken type:FIRAuthAPNSTokenTypeSandbox];

}

- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)notification
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {

    NSLog(@"DATA OF AUTH %@", [FIRAuth auth]);

    if ([[FIRAuth auth] canHandleNotification:notification]) {

        NSLog(@"Handle by Firebase ");

        completionHandler(UIBackgroundFetchResultNoData);
        return;
    }else{
        NSLog(@"NOT HANDLE BY FIREBASE %@", notification);
    }
}
</code>```

but then after getting a crash with this error log

```<code>-[__NSCFString setFir_authPhoneNumber:]: unrecognized selector sent to instance 0x166388b0
</code>```

答:
It looks like you're not linking your app with -ObjC linker flag, which is part of the instructions for Integrate without CocoaPods.

setFir_authPhoneNumber: is implemented as a category, thus -ObjC linker flag must be used or the compiled .o from the library won't be linked into your app binary.

Body:
I am Using Firebase phone number login authentication All things are perfect

1) Provisioning profile

2) certificate

3) Signing methods Enable

4) Project setting with .12 file

5) everything should perfect

Issue
When I send mobile number for the OTP using thins method using this code

NSString *phoneNumber = @"+919428936703";

[[FIRPhoneAuthProvider provider]
 verifyPhoneNumber:phoneNumber
 completion:^(NSString * verificationID,
              NSError * error) {

     NSLog(@"VARIFICATION CODE %@", verificationID);
     NSLog(@"Error %@", error);

     if (!error){

     }else{

     }
 }];

Also get call methods

- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    // Pass device token to auth.
    [[FIRAuth auth] setAPNSToken:deviceToken type:FIRAuthAPNSTokenTypeSandbox];

}

- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)notification
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {

    NSLog(@"DATA OF AUTH %@", [FIRAuth auth]);

    if ([[FIRAuth auth] canHandleNotification:notification]) {

        NSLog(@"Handle by Firebase ");

        completionHandler(UIBackgroundFetchResultNoData);
        return;
    }else{
        NSLog(@"NOT HANDLE BY FIREBASE %@", notification);
    }
}

but then after getting a crash with this error log

-[__NSCFString setFir_authPhoneNumber:]: unrecognized selector sent to instance 0x166388b0


问:
How to change cell value repeatedly by entering the value in other cell or sheet?
I want to create a roster in excel-sheet using 3 resources( resource 1, resource 2 and resource 3) into 2 shifts.
Now I want, when I enter resource 1 in some other cell this value should be copied to shift column. Here is sample data and you would be able to understand what is required.Sample Data</p>

答:
Edit J1:J4 as per the image below ...

and fill down the following formula from C2

```<code>=VLOOKUP(B:B,$I$1:$J$4,2,0)
</code>```

Body:
Edit J1:J4 as per the image below ...

and fill down the following formula from C2

=VLOOKUP(B:B,$I$1:$J$4,2,0)


问:
Remove all dots except the first one from a string
Given a string

```<code>'1.2.3.4.5'
</code>```

I would like to get this output

```<code>'1.2345'
</code>```

(In case there are no dots in the string, the string should be returned unchanged.)

I wrote this

```<code>function process( input ) {
    var index = input.indexOf( '.' );

    if ( index > -1 ) {
        input = input.substr( 0, index + 1 ) +
                input.slice( index ).replace( /\./g, '' );
    }

    return input;
}
</code>```

Live demo: http://jsfiddle.net/EDTNK/1/

It works but I was hoping for a slightly more elegant solution...

答:
Based on @Tadek's answer above. This function takes other locales into consideration.

For example, some locales will use a comma for the decimal separator and a period for the thousand separator (e.g. -451.161,432e-12).

First we convert anything other than 1) numbers; 2) negative sign; 3) exponent sign into a period ("-451.161.432e-12").

Next we split by period (["-451", "161", "432e-12"]) and pop out the right-most value ("432e-12"), then join with the rest ("-451161.432e-12")

(Note that I'm tossing out the thousand separators, but those could easily be added in the join step (.join(','))

```<code>var ensureDecimalSeparatorIsPeriod = function (value) {
    var numericString = value.toString();
    var splitByDecimal = numericString.replace(/[^\d.e-]/g, '.').split('.');
    if (splitByDecimal.length < 2) {
        return numericString;
    }
    var rightOfDecimalPlace = splitByDecimal.pop();
    return splitByDecimal.join('') + '.' + rightOfDecimalPlace;
};
</code>```

Body:
Given a string

'1.2.3.4.5'

I would like to get this output

'1.2345'

(In case there are no dots in the string, the string should be returned unchanged.)

I wrote this

function process( input ) {
    var index = input.indexOf( '.' );

    if ( index > -1 ) {
        input = input.substr( 0, index + 1 ) +
                input.slice( index ).replace( /\./g, '' );
    }

    return input;
}

Live demo: http://jsfiddle.net/EDTNK/1/

It works but I was hoping for a slightly more elegant solution...

Body:
Based on @Tadek's answer above. This function takes other locales into consideration.

For example, some locales will use a comma for the decimal separator and a period for the thousand separator (e.g. -451.161,432e-12).

First we convert anything other than 1) numbers; 2) negative sign; 3) exponent sign into a period ("-451.161.432e-12").

Next we split by period (["-451", "161", "432e-12"]) and pop out the right-most value ("432e-12"), then join with the rest ("-451161.432e-12")

(Note that I'm tossing out the thousand separators, but those could easily be added in the join step (.join(','))

var ensureDecimalSeparatorIsPeriod = function (value) {
    var numericString = value.toString();
    var splitByDecimal = numericString.replace(/[^\d.e-]/g, '.').split('.');
    if (splitByDecimal.length < 2) {
        return numericString;
    }
    var rightOfDecimalPlace = splitByDecimal.pop();
    return splitByDecimal.join('') + '.' + rightOfDecimalPlace;
};


问:
I want to redirect where VB2017 community saves projects
I have the location to do the changes but do not understand why there are three settings.

I teach VB at the university and VB, by default, saves student work to the C drive.  Needless to say, it is fraught with complications such as that the student has to return to that same computer if they forget to change the save location.

Do I need to redirect all three options?
Please explain why three locations are needed.

答:
The Projects location is the default path where Visual Studio projects are stored. If I understand your question completely, this is the path that would change from student to student.

The Project templates location is the location where custom project templates can be stored. The Item templates location is the location where custom item templates can be stored. For more info, see enter link description here


问:
TypeError: unbound method SendVars() must be called with Vars instance as first argument (got bool instance instead)
So I am trying to create a GUI that shares information between frames (which are set up as classes) and ran into this error, which despite the many hours of googling and trying different things, had no luck solving. Im just trying to create a library which can be written to and read from other classes. I created this test code just to debug the problem so if you want to see my main code let me know, thanks.

```<code>class Vars():

    global vari

    vari = dict(Sifo = False, Username = "", Password = "", Event = "", Time = "")

    def GetVars(self, var):

        print "1"
        return vari.pop(var)

    def SendVars(self, var, val):

        print"2"
        vari[str(var)] = val

class maintest():

    def test(self):

        yes = raw_input("Yes: ")

        if yes == "1":
            yes = True
        else:
            yes = False

        self.result(yes)

    def result(self, reslt):

        if reslt == True:
            yes = True
        else:
            yes = False

        Vars.SendVars('yes', yes)

a = maintest()
a.test()

print Vars.GetVars('yes')
</code>```

Output:

```<code>Yes: 1
Traceback (most recent call last):
  File "/Users/jacobsifodaskalakis/Documents/LiClipse
Workspace/Test/Test4.py", line 43, in <module>
    a.test()
  File "/Users/jacobsifodaskalakis/Documents/LiClipse
Workspace/Test/Test4.py", line 31, in test
    self.result(yes)
  File "/Users/jacobsifodaskalakis/Documents/LiClipse
Workspace/Test/Test4.py", line 40, in result
    Vars.SendVars('yes', yes)
TypeError: unbound method SendVars() must be called with Vars
instance as first argument (got str instance instead)
</code>```

答:
Looks like you need to instantiate your Vars class before you can use it:

```<code>def result(self, reslt):

    if reslt == True:
        yes = True
    else:
        yes = False

    vars_instance = Vars()

    vars_instance.SendVars('yes', yes)
</code>```

take a look at this question: How to instantiate a class in python

You also need to instantiate it near the end of your script:

```<code>vars_instance = Vars()

print vars_instance.GetVars('yes')
</code>```

finally, you've forgotten to actually define your global vari

```<code>global vari
vari = {}
</code>```

Body:
So I am trying to create a GUI that shares information between frames (which are set up as classes) and ran into this error, which despite the many hours of googling and trying different things, had no luck solving. Im just trying to create a library which can be written to and read from other classes. I created this test code just to debug the problem so if you want to see my main code let me know, thanks.

class Vars():

    global vari

    vari = dict(Sifo = False, Username = "", Password = "", Event = "", Time = "")

    def GetVars(self, var):

        print "1"
        return vari.pop(var)

    def SendVars(self, var, val):

        print"2"
        vari[str(var)] = val

class maintest():

    def test(self):

        yes = raw_input("Yes: ")

        if yes == "1":
            yes = True
        else:
            yes = False

        self.result(yes)

    def result(self, reslt):

        if reslt == True:
            yes = True
        else:
            yes = False

        Vars.SendVars('yes', yes)

a = maintest()
a.test()

print Vars.GetVars('yes')

Output:

Yes: 1
Traceback (most recent call last):
  File "/Users/jacobsifodaskalakis/Documents/LiClipse
Workspace/Test/Test4.py", line 43, in <module>
    a.test()
  File "/Users/jacobsifodaskalakis/Documents/LiClipse
Workspace/Test/Test4.py", line 31, in test
    self.result(yes)
  File "/Users/jacobsifodaskalakis/Documents/LiClipse
Workspace/Test/Test4.py", line 40, in result
    Vars.SendVars('yes', yes)
TypeError: unbound method SendVars() must be called with Vars
instance as first argument (got str instance instead)

Body:
Looks like you need to instantiate your Vars class before you can use it:

def result(self, reslt):

    if reslt == True:
        yes = True
    else:
        yes = False

    vars_instance = Vars()

    vars_instance.SendVars('yes', yes)

take a look at this question: How to instantiate a class in python

You also need to instantiate it near the end of your script:

vars_instance = Vars()

print vars_instance.GetVars('yes')

finally, you've forgotten to actually define your global vari

global vari
vari = {}


问:
How to run multiple times a Docker container with different parameters in Kubernetes?
I have a Docker container that reads a variable which I provide to it during the execution. Then I though that I would like to run many of those and pass a different value as variable for each one of those. Then, I just created a simple text file which contains all the values I want to pass into (they are about 20k different ones) and I am using gnu-parallel to spawn multiple Dockers in parallel.

My question is how I could do something like that in a Kubernetes environment?

答:
Sounds like you want you want to do can be achieved using kubernetes jobs.
I would advise against using gnu parallel on kubernetes unless you can fit all the jobs in one node. If this is the case I think it's ok, just set the cpu request in the job template.</p>


问:
When Django models field is empty, set value to the Default value
Whenever the user doesn't add a value, I need my Django models to replace the otherwise empty field with the value set in default.

My models looks like this:

```<code>not_before = models.TimeField(blank=True, null=True, default='00:00:00')
max_num_per_day = models.IntegerField(blank=True, null=True, default=0)
</code>```

I tried every combination of null, blank and default but no matter what I do, the fields gets replaced by null instead of '00:00:00' and 0.

Is there anyway I can force it to the default value whenever the field is empty?

答:
you can set up your form  with a default function like:

```<code>class YourForm(forms.Form):
.....
def clean_field(self):
        data = self.cleaned_data['not_before']
        if not data:
            data = '00:00:00'
</code>```

or write a function in your model like:

```<code>class Molde(models.Model):
  not_before = models.TimeField(blank=True, null=True, default='00:00:00')
  def time(self):
    if self.not_before:
        return self.not_before
    else:
        return '00:00:00'
</code>```

In this case you would call the function instead of the model field itself. You can also take a look at this.

Hope that helps.

Body:
Whenever the user doesn't add a value, I need my Django models to replace the otherwise empty field with the value set in default.

My models looks like this:

not_before = models.TimeField(blank=True, null=True, default='00:00:00')
max_num_per_day = models.IntegerField(blank=True, null=True, default=0)

I tried every combination of null, blank and default but no matter what I do, the fields gets replaced by null instead of '00:00:00' and 0.

Is there anyway I can force it to the default value whenever the field is empty?

Body:
you can set up your form  with a default function like:

class YourForm(forms.Form):
.....
def clean_field(self):
        data = self.cleaned_data['not_before']
        if not data:
            data = '00:00:00'

or write a function in your model like:

class Molde(models.Model):
  not_before = models.TimeField(blank=True, null=True, default='00:00:00')
  def time(self):
    if self.not_before:
        return self.not_before
    else:
        return '00:00:00'

In this case you would call the function instead of the model field itself. You can also take a look at this.

Hope that helps.


问:
Eclipse PDT, how do I get the files on the server?
I am trying to learn how to use Eclipse Helios PDT, but I don't understand how one gets the files from their workspace to the server. The PDT documentation is painfully sparse.

I have my workspace in /home/bob/workspace and my local dev webroot is /home/bob/public_html.

If I set up a run configuration for my php project I see where I can set up the path to the server, etc, but I do not see any obvious way to auto copy the files to my webroot to actuallly run the project. If I click on run, I just get a 404 in the browser.

With NetBeans, for instance, you can configure a PHP project to copy on save to a local webserver, FTP to a server, etc.  Does PDT not have some sort of similar functionality?

答: You can consider to instead of keeping a local project within the Eclipse Workspace, have the project directly "on the server" - e.g. "Map network drive" to the server having the files (if this is a unix server, and you program in windows, then use Samba on the unix server). Thus, when you save a change, you are actually changing it directly on the server, and hence the change will be reflected immediately when you refresh your browser.</p>


问:
Turn SELECT into DELETE mysql php
I am having a heck of a time turn this SELECT statement into a DELETE.

```<code>$query  = "
SELECT n.thread_id
     , n.status
     , n.status_tooltip_text
  FROM newmessages n
     , oldmessages o
 WHERE n.thread_id = o.thread_id
   AND n.status_tooltip_text = o.status_tooltip_text
";
</code>```

The end result I am trying to achieve is to delete from newmessages where the status tooltip text is the same as the status tooltip in oldmessages.

The select I have above works, but when I turn the select into a delete it says database query failed.  The columns in the two tables have identical column definitions.

答:
I'm struggling to see what's wrong with the following:</p>

```<code>DELETE n
  FROM newmessages n
  JOIN oldmessages o
    ON n.thread_id = o.thread_id
   AND n.status_tooltip_text = o.status_tooltip_text
</code>```

Title: Turn SELECT into DELETE mysql php

Body:
I am having a heck of a time turn this SELECT statement into a DELETE.

$query  = "
SELECT n.thread_id
     , n.status
     , n.status_tooltip_text
  FROM newmessages n
     , oldmessages o
 WHERE n.thread_id = o.thread_id
   AND n.status_tooltip_text = o.status_tooltip_text
";

The end result I am trying to achieve is to delete from newmessages where the status tooltip text is the same as the status tooltip in oldmessages.

The select I have above works, but when I turn the select into a delete it says database query failed.  The columns in the two tables have identical column definitions.

Body:
I'm struggling to see what's wrong with the following:

DELETE n
  FROM newmessages n
  JOIN oldmessages o
    ON n.thread_id = o.thread_id
   AND n.status_tooltip_text = o.status_tooltip_text


问:
Create PASCAL Voc for Tensorflow Object Detection API
This question is an extension of this one.

TLDR;
I'm trying to train the TS Object Detection API using my own dataset. For proof of concept, I decided to adhere my dataset to the Pascal VOC 2012 benchmark.

At the moment, I am trying to create a TFRecord from my Pascal VOC annotations.

Looking at this line in their create_pascal_tf_record.py script, they're just grabbing the aeroplane's descriptor; lack of a better word, text file. Why is this so? What about the other classes' descriptors?

Side Note

This file; titled aeroplane_train.txt, was included along with the Pascal VOC 2012 dataset inside VOC2012/ImageSets/Main/.

A peek into the file shows that the first column represents an image name and the -1 or 1 states whether that particular image consists of the class(aeroplane) we're interested in.

Partial contents of the aeroplane_train.txt file:

```<code>2008_000008 -1
2008_000015 -1
2008_000019 -1
2008_000023 -1
2008_000028 -1
2008_000033  1
2008_000036 -1
2008_000037  1
2008_000041 -1
2008_000045 -1
2008_000053 -1
2008_000060 -1
2008_000066 -1
2008_000070 -1
2008_000074 -1
2008_000085 -1
2008_000089 -1
2008_000093 -1
2008_000095 -1
2008_000096 -1
2008_000097 -1
2008_000099 -1
2008_000103 -1
2008_000105 -1
2008_000109 -1
2008_000112 -1
2008_000128 -1
2008_000131 -1
2008_000132 -1
2008_000141 -1
</code>```

答: I answered a similar question here.  The punchline is that we currently only look at the first column of the aeroplane_train.txt file (which is the same as the other xxx_train.txt files) and lets us figure out the path for each image in the training set.</p>

Body:
This question is an extension of this one.

TLDR;
I'm trying to train the TS Object Detection API using my own dataset. For proof of concept, I decided to adhere my dataset to the Pascal VOC 2012 benchmark.

At the moment, I am trying to create a TFRecord from my Pascal VOC annotations.

Looking at this line in their create_pascal_tf_record.py script, they're just grabbing the aeroplane's descriptor; lack of a better word, text file. Why is this so? What about the other classes' descriptors?

Side Note

This file; titled aeroplane_train.txt, was included along with the Pascal VOC 2012 dataset inside VOC2012/ImageSets/Main/.

A peek into the file shows that the first column represents an image name and the -1 or 1 states whether that particular image consists of the class(aeroplane) we're interested in.

Partial contents of the aeroplane_train.txt file:

2008_000008 -1
2008_000015 -1
2008_000019 -1
2008_000023 -1
2008_000028 -1
2008_000033  1
2008_000036 -1
2008_000037  1
2008_000041 -1
2008_000045 -1
2008_000053 -1
2008_000060 -1
2008_000066 -1
2008_000070 -1
2008_000074 -1
2008_000085 -1
2008_000089 -1
2008_000093 -1
2008_000095 -1
2008_000096 -1
2008_000097 -1
2008_000099 -1
2008_000103 -1
2008_000105 -1
2008_000109 -1
2008_000112 -1
2008_000128 -1
2008_000131 -1
2008_000132 -1
2008_000141 -1


问:
Call a Google App Maker App with a parameter
Hello i am new here so if i ask a stupid question please forgive me.

We at AppAtSchool are working with Google ApMaker and we want to call a published App with 2 parameters. How can we read those in App Maker? Thanks in advance!

答:
If you pass parameters to your App Maker app through URL parameters, your app can read the parameters using the google.script.url.getLocation method:

```<code>google.script.url.getLocation(function(location) {
  console.log(location.parameters);
  console.log(location.hash);
});
</code>```

Find more details in the documentation

Body:
If you pass parameters to your App Maker app through URL parameters, your app can read the parameters using the google.script.url.getLocation method:

google.script.url.getLocation(function(location) {
  console.log(location.parameters);
  console.log(location.hash);
});

Find more details in the documentation


问:
How do I get changed Value?
I have something like this

```<code>@action changeValue(event){
    console.log('value', event.target.value);
}

let dueDate = moment(task.dueDate).format("YYYY-MM-DD");
input type="date" className="task-due-date" value={dueDate} onChange={(event) => changeValue(event)}
</code>```

Nothing is in event.target.value. I have some proxy event object but target has nothing. I don't know why.

答:
I recommend you to use refs. Something like this:

```<code>class MapContainer extends Component {
  changeUser() {
    console.log(this.refs.user.value)
  }
  render() {
    return (<input ref="user" type="text" onChange={this.changeUser.bind(this)} />)
  }
}
</code>```

note the ref attribute in the input and the binding of this in the onChange attribute, that way you can access the refs object in the changeUser function to get your new value.

Title: How do I get changed Value?

Body:
I have something like this

@action changeValue(event){
    console.log('value', event.target.value);
}

let dueDate = moment(task.dueDate).format("YYYY-MM-DD");
input type="date" className="task-due-date" value={dueDate} onChange={(event) => changeValue(event)}

Nothing is in event.target.value. I have some proxy event object but target has nothing. I don't know why.

Body:
I recommend you to use refs. Something like this:

class MapContainer extends Component {
  changeUser() {
    console.log(this.refs.user.value)
  }
  render() {
    return (<input ref="user" type="text" onChange={this.changeUser.bind(this)} />)
  }
}

note the ref attribute in the input and the binding of this in the onChange attribute, that way you can access the refs object in the changeUser function to get your new value.


问:
use response write to make a link
I have a urlcolumn and a title column and i want the link to be automatically made in asp</p>

```<code> <td><%response.write(<a href="rs.fields.item("urlcolumn")target=_"blank">rs.fields.item("titlecolumn")</a>)%></td>
</code>```

答:
```<code><td><%response.write("<a href=""" & rs.fields.item("urlcolumn") & """ target=""_blank"">" & rs.fields.item("titlecolumn") & "</a>")%></td>
</code>```

Title: use response write to make a link

Body:
I have a urlcolumn and a title column and i want the link to be automatically made in asp

 <%response.write(rs.fields.item("titlecolumn"))%>


问:
appending to empty lists through a for loop but my lists print out empty
I've written a function whose purpose is to open, read, access data values within the each file in an indicated directory and iteratively append each files data entries into empty lists which will then be used to construct a summary csv file.

The issue is that my lists are empty at the termination of the for loop.
How do i get around this issue?

I've tried looking through existing questions and haven't found it helpful.

Here's my code:

```<code>fileid   = [] * len(os.listdir(path))
objname  = [] * len(os.listdir(path))
obsvtype = [] * len(os.listdir(path))
filtr    = [] * len(os.listdir(path))

# Open, read, and iterate over files ending with the .fits extension in inputted path.
# Assign fits header key data to a variable and then append iteratively to respective empty list.

for fitsfile in os.listdir(path):
    if fitsfile[-5:] == '.fits':
        try:
            hdulist     = fits.open(str.format(fitsfile))

            filename    = hdulist[0].data['FILENAME']
            fileid.append(filename)

            object_name = hdulist[0].data['OBJECT']
            objname.append(object_name)

            obsvtyp     = hdulist[0].data['OBSTYPE']
            obsvtype.append(obsvtyp)

            filt        = hdulist[0].data['FILTERS']
            filtr.append(filt)
        except:
            pass

print(fileid,objname,obsvtype,filtr)

# Create an empty pandas dataframe object (data table) and assign populated data lists to dataframe.
# columns.

dataframe = pd.DataFrame(data = None)
dataframe['Filename']         = fileid
dataframe['Object_Name']      = objname
dataframe['Observation_type'] = obsvtype
dataframe['Filter']           = filtr

print(dataframe)

# Export compiled dataframe object to a .csv file in specified directory path.

dataframe.to_csv(path + 'reduc_tbl_result.csv',columns = ['Filename','Object_name',
    'Observation_Type','Filter'],index = None)
</code>```

and the result:

([], [], [], [])
Empty DataFrame
Columns: [Filename, Object_Name, Observation_type, Filter]
Index: [])

Thanks in advance.

答:
I've since recognized the source of my issue for those who'll need a solution in the future. My code from above was printing empty lists because the fits.open() call was not operating on string elements of the os.listdir(path) via the code below:

```<code>    for fitsfile in os.listdir(path):
        if fitsfile[-5:] == '.fits':
           try:
               hdulist     = fits.open(str.format(fitsfile))
</code>```

I tried this and it made the difference:

```<code>    for fitsfile in os.listdir(path):
        if fitsfile[-5:] == '.fits':
            with fits.open(os.path.join(path,fitsfile)) as hdulist:
                try:
                   hdu = hdulist[0]
</code>```

Body:
I've written a function whose purpose is to open, read, access data values within the each file in an indicated directory and iteratively append each files data entries into empty lists which will then be used to construct a summary csv file.

The issue is that my lists are empty at the termination of the for loop.
How do i get around this issue?

I've tried looking through existing questions and haven't found it helpful.

Here's my code:

fileid   = [] * len(os.listdir(path))
objname  = [] * len(os.listdir(path))
obsvtype = [] * len(os.listdir(path))
filtr    = [] * len(os.listdir(path))

# Open, read, and iterate over files ending with the .fits extension in inputted path.
# Assign fits header key data to a variable and then append iteratively to respective empty list.

for fitsfile in os.listdir(path):
    if fitsfile[-5:] == '.fits':
        try:
            hdulist     = fits.open(str.format(fitsfile))

            filename    = hdulist[0].data['FILENAME']
            fileid.append(filename)

            object_name = hdulist[0].data['OBJECT']
            objname.append(object_name)

            obsvtyp     = hdulist[0].data['OBSTYPE']
            obsvtype.append(obsvtyp)

            filt        = hdulist[0].data['FILTERS']
            filtr.append(filt)
        except:
            pass

print(fileid,objname,obsvtype,filtr)

# Create an empty pandas dataframe object (data table) and assign populated data lists to dataframe.
# columns.

dataframe = pd.DataFrame(data = None)
dataframe['Filename']         = fileid
dataframe['Object_Name']      = objname
dataframe['Observation_type'] = obsvtype
dataframe['Filter']           = filtr

print(dataframe)

# Export compiled dataframe object to a .csv file in specified directory path.

dataframe.to_csv(path + 'reduc_tbl_result.csv',columns = ['Filename','Object_name',
    'Observation_Type','Filter'],index = None)

and the result:

([], [], [], [])
Empty DataFrame
Columns: [Filename, Object_Name, Observation_type, Filter]
Index: [])

Thanks in advance.

Body:
I've since recognized the source of my issue for those who'll need a solution in the future. My code from above was printing empty lists because the fits.open() call was not operating on string elements of the os.listdir(path) via the code below:

    for fitsfile in os.listdir(path):
        if fitsfile[-5:] == '.fits':
           try:
               hdulist     = fits.open(str.format(fitsfile))

I tried this and it made the difference:

    for fitsfile in os.listdir(path):
        if fitsfile[-5:] == '.fits':
            with fits.open(os.path.join(path,fitsfile)) as hdulist:
                try:
                   hdu = hdulist[0]


问:
google-container access the ui panel
I'm following a course where the teacher connects to google container ui panel by accessing https://ip-of-container/ui he is then asked for password and username.

In my case what I see is :

```<code>User "system:anonymous" cannot get  at the cluster scope.: "No policy matched.\nUnknown user \"system:anonymous\""
</code>```

This issue on github says this:

A better way to access the UI via the API is to run kubectl proxy and
  access http://localhost:8001/ui

I don't understand what he is trying to say. Is localhost a placeholder for the machine endpoint ip ? How could it connect to my localhost since I have no server running ?

I did run kubectl proxy then,

try to access http(s)://container-endpoint-ip:8001/ui

literally http://localhost:8001/ui

None of those work.

答: Try running kubectl proxy and open http://localhost:8001/ui.

Title: google-container access the ui panel

Body:
I'm following a course where the teacher connects to google container ui panel by accessing https://ip-of-container/ui he is then asked for password and username.

In my case what I see is :

User "system:anonymous" cannot get  at the cluster scope.: "No policy matched.\nUnknown user \"system:anonymous\""

This issue on github says this:

A better way to access the UI via the API is to run kubectl proxy and
  access http://localhost:8001/ui

I don't understand what he is trying to say. Is localhost a placeholder for the machine endpoint ip ? How could it connect to my localhost since I have no server running ?

I did run kubectl proxy then,

try to access http(s)://container-endpoint-ip:8001/ui

literally http://localhost:8001/ui

None of those work.


问:
Stock of products during time
We need to create a query in which we will have the available stock of our products during next weeks.

We have 4 kind of orders-invoices.

a) Orders from suppliers which have an estimated delivery date

b) Invoices from suppliers which are being transformed from their orders and they also have a date

c) Orders for Clients with estimated execution date

d) Invoices for clients with a date

The a,b are going to add quantities to our table

The c,d are going to remove quantities from our table

For example:

We are currently on week 27 and we know that at 12 of July (week 28) we will receive 100 pcs of product A.

Then a client already pre-ordered 50 pcs with execution date 25 of July (week 30) , so we have an order which should reduce the quantity of product A at week 30.

If we are going to receive at 2 of August 100 pcs more, then on week 31 the table should show the estimated quantity by calculating:

```<code> Week27 - 0   pcs
 Week28 - 100 pcs (we will receive 100 pcs)
 Week29 - 100 pcs (nothing was sold)
 Week30 - 50  pcs (we will sell 50 pcs so the remaining quantity is 50)
 Week31 - 150 pcs (we will receive 100 pcs so the remaining quantity will be 150)
</code>```

答:
It's a pretty common requirement in any Warehouse Management or ERP system, they mostly do this in a similar way: Store every transaction as either a positive or negative number. then for each date, sum every transaction prior to that date.

Pseudo-code as follows, obviously implement to suit your database schema:

```<code>Select
    Week,
   (Select
           Sum(Quantity) from
           Transactions
            where date < Weeks.EndDate) as ClosingBalance

from Weeks
</code>```

Title: Stock of products during time

Body:
We need to create a query in which we will have the available stock of our products during next weeks.

We have 4 kind of orders-invoices.

a) Orders from suppliers which have an estimated delivery date

b) Invoices from suppliers which are being transformed from their orders and they also have a date

c) Orders for Clients with estimated execution date

d) Invoices for clients with a date

The a,b are going to add quantities to our table

The c,d are going to remove quantities from our table

For example:

We are currently on week 27 and we know that at 12 of July (week 28) we will receive 100 pcs of product A.

Then a client already pre-ordered 50 pcs with execution date 25 of July (week 30) , so we have an order which should reduce the quantity of product A at week 30.

If we are going to receive at 2 of August 100 pcs more, then on week 31 the table should show the estimated quantity by calculating:

 Week27 - 0   pcs
 Week28 - 100 pcs (we will receive 100 pcs)
 Week29 - 100 pcs (nothing was sold)
 Week30 - 50  pcs (we will sell 50 pcs so the remaining quantity is 50)
 Week31 - 150 pcs (we will receive 100 pcs so the remaining quantity will be 150)

Body:
It's a pretty common requirement in any Warehouse Management or ERP system, they mostly do this in a similar way: Store every transaction as either a positive or negative number. then for each date, sum every transaction prior to that date.

Pseudo-code as follows, obviously implement to suit your database schema:

Select
    Week,
   (Select
           Sum(Quantity) from
           Transactions
            where date < Weeks.EndDate) as ClosingBalance

from Weeks


问:
javax.jms.JMSException: Cannot send to a non-connected transport
I am using the qpid-jms-client.jar library to form a connection with a broker.

My code is ::

```<code>Properties properties = new Properties();
properties.load(this.getClass().getResourceAsStream("jndi.properties"));
Context context = new InitialContext(properties);

System.setProperty("javax.net.ssl.trustStore", "C:/Users/xxxxx/qpid.jks");
System.setProperty("javax.net.ssl.trustStorePassword", "test123");

ConnectionFactory factory = (ConnectionFactory) context.lookup("myFactoryLookup");
Destination queue = (Destination) context.lookup("myQueueLookup");
Connection connection = factory.createConnection("<my-username>", "<my-password>");
connection.setExceptionListener(new MyExceptionListener());
connection.start();
</code>```

My jndi.properties file is ::

```<code>java.naming.factory.initial=org.apache.qpid.jms.jndi.JmsInitialContextFactory
connectionfactory.myFactoryLookup=amqps://esesslx0100.se:9443
queue.myQueueLookup=emft_input
topic.myTopicLookup=topic
destination.topicExchange=amq.topic
jms.user=test
</code>```

Now the above code gives me the ERROR ::

```<code>Connection ExceptionListener fired, exiting.
javax.jms.JMSException: Cannot send to a non-connected transport.
    at org.apache.qpid.jms.exceptions.JmsExceptionSupport.create(JmsExceptionSupport.java:66)
    at org.apache.qpid.jms.exceptions.JmsExceptionSupport.create(JmsExceptionSupport.java:88)
    at org.apache.qpid.jms.JmsConnection.onAsyncException(JmsConnection.java:1188)
    at org.apache.qpid.jms.JmsConnection.onConnectionFailure(JmsConnection.java:1104)
    at org.apache.qpid.jms.provider.amqp.AmqpProvider.fireProviderException(AmqpProvider.java:847)
    at org.apache.qpid.jms.provider.amqp.AmqpProvider.pumpToProtonTransport(AmqpProvider.java:820)
    at org.apache.qpid.jms.provider.amqp.AmqpProvider.access$300(AmqpProvider.java:90)
    at org.apache.qpid.jms.provider.amqp.AmqpProvider$16.run(AmqpProvider.java:683)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.io.IOException: Cannot send to a non-connected transport.
    at org.apache.qpid.jms.transports.netty.NettyTcpTransport.checkConnected(NettyTcpTransport.java:279)
    at org.apache.qpid.jms.transports.netty.NettyTcpTransport.allocateSendBuffer(NettyTcpTransport.java:176)
    at org.apache.qpid.jms.provider.amqp.AmqpProvider.pumpToProtonTransport(AmqpProvider.java:806)
    ... 9 more
</code>```

Since the broker is configures with SaSL, I am also providing my username and password. I am currently unaware of why this ERROR occurs. Ive looked around on the internet but there is no clear explanation as to why it would occur with qpid. Any ideas why this ERROR occurs ?

My trustStore file is correct since I have verifies SSL connectivity using it.

答:
In my case when receiving this error it was simply because when I was in the office our company proxy was filtering this traffic out when I executed programatically. Using Service Bus Explorer still worked though as it must have picked up machine settings that add the proxy.

We were using a publicly hosted Service Bus so I attempted from my home network without the proxy and everything worked as expected. Using Wireshark or similar program probably would have helped identify this quicker. Hope this helps someone.

Body:
I am using the qpid-jms-client.jar library to form a connection with a broker.

My code is ::

Properties properties = new Properties();
properties.load(this.getClass().getResourceAsStream("jndi.properties"));
Context context = new InitialContext(properties);

System.setProperty("javax.net.ssl.trustStore", "C:/Users/xxxxx/qpid.jks");
System.setProperty("javax.net.ssl.trustStorePassword", "test123");

ConnectionFactory factory = (ConnectionFactory) context.lookup("myFactoryLookup");
Destination queue = (Destination) context.lookup("myQueueLookup");
Connection connection = factory.createConnection("<my-username>", "<my-password>");
connection.setExceptionListener(new MyExceptionListener());
connection.start();

My jndi.properties file is ::

java.naming.factory.initial=org.apache.qpid.jms.jndi.JmsInitialContextFactory
connectionfactory.myFactoryLookup=amqps://esesslx0100.se:9443
queue.myQueueLookup=emft_input
topic.myTopicLookup=topic
destination.topicExchange=amq.topic
jms.user=test

Now the above code gives me the ERROR ::

Connection ExceptionListener fired, exiting.
javax.jms.JMSException: Cannot send to a non-connected transport.
    at org.apache.qpid.jms.exceptions.JmsExceptionSupport.create(JmsExceptionSupport.java:66)
    at org.apache.qpid.jms.exceptions.JmsExceptionSupport.create(JmsExceptionSupport.java:88)
    at org.apache.qpid.jms.JmsConnection.onAsyncException(JmsConnection.java:1188)
    at org.apache.qpid.jms.JmsConnection.onConnectionFailure(JmsConnection.java:1104)
    at org.apache.qpid.jms.provider.amqp.AmqpProvider.fireProviderException(AmqpProvider.java:847)
    at org.apache.qpid.jms.provider.amqp.AmqpProvider.pumpToProtonTransport(AmqpProvider.java:820)
    at org.apache.qpid.jms.provider.amqp.AmqpProvider.access$300(AmqpProvider.java:90)
    at org.apache.qpid.jms.provider.amqp.AmqpProvider$16.run(AmqpProvider.java:683)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.io.IOException: Cannot send to a non-connected transport.
    at org.apache.qpid.jms.transports.netty.NettyTcpTransport.checkConnected(NettyTcpTransport.java:279)
    at org.apache.qpid.jms.transports.netty.NettyTcpTransport.allocateSendBuffer(NettyTcpTransport.java:176)
    at org.apache.qpid.jms.provider.amqp.AmqpProvider.pumpToProtonTransport(AmqpProvider.java:806)
    ... 9 more

Since the broker is configures with SaSL, I am also providing my username and password. I am currently unaware of why this ERROR occurs. Ive looked around on the internet but there is no clear explanation as to why it would occur with qpid. Any ideas why this ERROR occurs ?

My trustStore file is correct since I have verifies SSL connectivity using it.