问:
How to use Prometheus to monitor nodejs cpu and memory usage on Mac?
I have a nodejs application on Mac OS and want to monitor its cpu and memory usage. I have setup Prometheus server with below configuration:

```<code># my global config
global:
  scrape_interval:     15s # Set the scrape interval to every 15 seconds. Default is every 1 minute.
  evaluation_interval: 15s # Evaluate rules every 15 seconds. The default is every 1 minute.
  # scrape_timeout is set to the global default (10s).

  # Attach these labels to any time series or alerts when communicating with
  # external systems (federation, remote storage, Alertmanager).
  external_labels:
      monitor: 'codelab-monitor'

# Load rules once and periodically evaluate them according to the global 'evaluation_interval'.
rule_files:
  # - "first.rules"
  # - "second.rules"

# A scrape configuration containing exactly one endpoint to scrape:
# Here it's Prometheus itself.
scrape_configs:
  # The job name is added as a label `job=<job_name>` to any timeseries scraped from this config.
  - job_name: 'controller'
    scrape_interval: 1s
    static_configs:
      - targets: ['172.16.123.1:3030']
        labels:
          group: 'demo'

  - job_name: "node"
    scrape_interval: "15s"
    static_configs:
       - targets: ['localhost:9100']
</code>```

In my nodejs application, I have imported prom-client dependency. And created a /metrics path which returns the metrics data:

```<code>const express = require('express');
const app = express();

app.get('/metrics', (req, res) => {
  const m = prom.register.metrics();
  console.log(m);
  res.end(m);
});
</code>```

In my service class, I use prom.Counter to record the number of request

```<code>const counter = new prom.Counter('create_connection', 'The number of requests')
counter.inc()
</code>```

when I go to localhost:3030/metrics link I can read below information:

```<code># HELP nodejs_gc_runs_total Count of total garbage collections.
# TYPE nodejs_gc_runs_total counter

# HELP nodejs_gc_pause_seconds_total Time spent in GC Pause in seconds.
# TYPE nodejs_gc_pause_seconds_total counter

# HELP nodejs_gc_reclaimed_bytes_total Total number of bytes reclaimed by GC.
# TYPE nodejs_gc_reclaimed_bytes_total counter

# HELP create_connection The number of requests
# TYPE create_connection counter
create_connection 18
</code>```

I can see that create_connection was called 18 times. Now I go to Prometheus graph page, I am able to see the graph for create_connection. But my question is how I can see how much CPU and Memory my nodejs application consumed during a time period. Is there anywhere I need to configure in my app?

答: You would have to instrument something your self.  So, you can take these measurements on your own at a set interval and use something like https://nodejs.org/api/process.html#process_process_memoryusage to get memory usage, update the metrics and they will get collected.</p>

Body:
I have a nodejs application on Mac OS and want to monitor its cpu and memory usage. I have setup Prometheus server with below configuration:

# my global config
global:
  scrape_interval:     15s # Set the scrape interval to every 15 seconds. Default is every 1 minute.
  evaluation_interval: 15s # Evaluate rules every 15 seconds. The default is every 1 minute.
  # scrape_timeout is set to the global default (10s).

  # Attach these labels to any time series or alerts when communicating with
  # external systems (federation, remote storage, Alertmanager).
  external_labels:
      monitor: 'codelab-monitor'

# Load rules once and periodically evaluate them according to the global 'evaluation_interval'.
rule_files:
  # - "first.rules"
  # - "second.rules"

# A scrape configuration containing exactly one endpoint to scrape:
# Here it's Prometheus itself.
scrape_configs:
  # The job name is added as a label `job=<job_name>` to any timeseries scraped from this config.
  - job_name: 'controller'
    scrape_interval: 1s
    static_configs:
      - targets: ['172.16.123.1:3030']
        labels:
          group: 'demo'

  - job_name: "node"
    scrape_interval: "15s"
    static_configs:
       - targets: ['localhost:9100']

In my nodejs application, I have imported prom-client dependency. And created a /metrics path which returns the metrics data:

const express = require('express');
const app = express();

app.get('/metrics', (req, res) => {
  const m = prom.register.metrics();
  console.log(m);
  res.end(m);
});

In my service class, I use prom.Counter to record the number of request

const counter = new prom.Counter('create_connection', 'The number of requests')
counter.inc()

when I go to localhost:3030/metrics link I can read below information:

# HELP nodejs_gc_runs_total Count of total garbage collections.
# TYPE nodejs_gc_runs_total counter

# HELP nodejs_gc_pause_seconds_total Time spent in GC Pause in seconds.
# TYPE nodejs_gc_pause_seconds_total counter

# HELP nodejs_gc_reclaimed_bytes_total Total number of bytes reclaimed by GC.
# TYPE nodejs_gc_reclaimed_bytes_total counter

# HELP create_connection The number of requests
# TYPE create_connection counter
create_connection 18

I can see that create_connection was called 18 times. Now I go to Prometheus graph page, I am able to see the graph for create_connection. But my question is how I can see how much CPU and Memory my nodejs application consumed during a time period. Is there anywhere I need to configure in my app?


来源: stackexchange

问:
How can I execute syncronized this gulpfile
The problem is that it does not finish generating the resources with the command 'ionic resources', and copying the images, which is already trying to compile. I don't want to use a timeout

el problema es que no termina de generar los recursos con el comando 'ionic resources', y copiar las imagenes, que ya esta tratando de compilar. No quiero usar timeouts

```<code>gulp.task('ionicResources', function () {
   gulputil.log(cp.execSync("ionic resources").toString('ascii'))
});

gulp.task('copiarAplatformRes', function () {
   gulp.src('./resources/android/icon/drawable-ldpi-icon.png')
      .pipe(rename({basename: 'icon'}))
      .pipe(gulp.dest("./platforms/android/res/mipmap-ldpi"));
});

gulp.task('compile', function () {
    gulputil.log(cp.execSync("cordova build --release adroid").toString('ascii'))
});

gulp.task("build-android", ['ionicResources', 'copiarAplatformRes','compile'],function () {
});
</code>```

答:
You need run-sequence or better yet gulp 4.0 to run your tasks in series.  Alternatively, you could make your 'copiarAplatformRes' task dependent on your 'ionicResources' task by

```<code>gulp.task('copiarAplatformRes', ['ionicResources'], function () {
  return gulp.src('./resources/android/icon/drawable-ldpi-icon.png')
  etc....
</code>```

and add similar return statements to all your tasks.

ContentLicense: CC BY-SA 3.0

Body:
The problem is that it does not finish generating the resources with the command 'ionic resources', and copying the images, which is already trying to compile. I don't want to use a timeout

el problema es que no termina de generar los recursos con el comando 'ionic resources', y copiar las imagenes, que ya esta tratando de compilar. No quiero usar timeouts

gulp.task('ionicResources', function () {
   gulputil.log(cp.execSync("ionic resources").toString('ascii'))
});

gulp.task('copiarAplatformRes', function () {
   gulp.src('./resources/android/icon/drawable-ldpi-icon.png')
      .pipe(rename({basename: 'icon'}))
      .pipe(gulp.dest("./platforms/android/res/mipmap-ldpi"));
});

gulp.task('compile', function () {
    gulputil.log(cp.execSync("cordova build --release adroid").toString('ascii'))
});

gulp.task("build-android", ['ionicResources', 'copiarAplatformRes','compile'],function () {
});

Body:
You need run-sequence or better yet gulp 4.0 to run your tasks in series.  Alternatively, you could make your 'copiarAplatformRes' task dependent on your 'ionicResources' task by

gulp.task('copiarAplatformRes', ['ionicResources'], function () {
  return gulp.src('./resources/android/icon/drawable-ldpi-icon.png')
  etc....

and add similar return statements to all your tasks.


问:
Max and Min pandas - Python
I have a table that looks at the daily open, high, low and percentage change of a specific stock from year 2010 to today's date.

```<code>        Open     High      Low    Close  Percentage Chg
Date
2017-07-03   972.79   974.49   951.00   953.66          -1.481
2017-06-30   980.12   983.47   967.61   968.00          -0.813
2017-06-29   979.00   987.56   965.25   975.93          -1.454
</code>```

I have created an empty table.

I would like to add the following to the empty column:

A column that has the top 5 largest Percentage Chg values

A column that hasthe bottom 5 lowest Percentage chg values

A column that calculates the variance of Column "CLOSE"

Thanks,

答:
I've put together a script that seems to meets your 3 objectives.

I used pandas_datareader (version 0.4.0) to read in the AMAZON stock prices.

Here's the code with explanations in it:

```<code> import pandas_datareader.data as web
import datetime

start = datetime.datetime(2010, 1, 1)
end = datetime.datetime(2017, 7, 5)

df = web.DataReader("AMZN", 'google', start, end)

#variance calculation
close_var = df['Close'].var()

#make variance a column
df['close_var_col'] = close_var

#selecting the first observation of opeing price from 2010
#base_open = int(df['Open'].head(1))

#creating the percentage difference from previous day
df['perc_chg'] = 100*(df['Close'] - df['Close'].shift(-1))/df['Close'].shift(-1)

#creating a df of top 5 and one of bottom 5 by perc_chg and removing Nan values
df = df.dropna(subset=['perc_chg'])
five_highest_df = df.sort_values(by='perc_chg').tail(5)
five_lowest_df = df.sort_values(by='perc_chg').head(5)

#creating a list of the top 5 (the only way I can think to this is with a string)
list_of_top_5 = str(list(set(list(five_highest_df['perc_chg']))))
list_of_bot_5 = str(list(set(list(five_lowest_df['perc_chg']))))

#Adding the list of the top 5 and bottom 5 to our dataframe
df['list_of_top_5'] = list_of_top_5
df['list_of_bot_5'] = list_of_bot_5

print(df.tail(20))
</code>```

It's not very efficient and I'm not sure it's particularly useful as a dataframe.  Here's the output you should get.

```<code>                   Open     High      Low    Close    Volume  close_var_col
    Date
    2017-06-07  1005.95  1010.25  1002.00  1010.07   2823041   53171.161256
    2017-06-08  1012.06  1013.61  1006.11  1010.27   2767857   53171.161256
    2017-06-09  1012.50  1012.99   927.00   978.31   7647692   53171.161256
    2017-06-12   967.00   975.95   945.00   964.91   9447233   53171.161256
    2017-06-13   977.99   984.50   966.10   980.79   4580011   53171.161256
    2017-06-14   988.59   990.34   966.71   976.47   3974900   53171.161256
    2017-06-15   958.70   965.73   950.86   964.17   5373865   53171.161256
    2017-06-16   996.00   999.75   982.00   987.71  11472662   53171.161256
    2017-06-19  1017.00  1017.00   989.90   995.17   5043408   53171.161256
    2017-06-20   998.00  1004.88   992.02   992.59   4076828   53171.161256
    2017-06-21   998.70  1002.72   992.65  1002.23   2922473   53171.161256
    2017-06-22  1002.23  1006.96   997.20  1001.30   2253433   53171.161256
    2017-06-23  1002.54  1004.62   998.02  1003.74   2879145   53171.161256
    2017-06-26  1008.50  1009.80   992.00   993.98   3386157   53171.161256
    2017-06-27   990.69   998.80   976.00   976.78   3782389   53171.161256
    2017-06-28   978.55   990.68   969.21   990.33   3737567   53171.161256
    2017-06-29   979.00   987.56   965.25   975.93   4302968   53171.161256
    2017-06-30   980.12   983.47   967.61   968.00   3390345   53171.161256
    2017-07-03   972.79   974.49   951.00   953.66   2909108   53171.161256
    2017-07-05   961.53   975.00   955.25   971.40   3652955   53171.161256

 perc_chg                                      list_of_top_5

-0.699951  [12.356073489642865, 9.0991430362990329, 10.96...
-0.019797  [12.356073489642865, 9.0991430362990329, 10.96...
 3.266858  [12.356073489642865, 9.0991430362990329, 10.96...
 1.388731  [12.356073489642865, 9.0991430362990329, 10.96...
-1.619103  [12.356073489642865, 9.0991430362990329, 10.96...
 0.442410  [12.356073489642865, 9.0991430362990329, 10.96...
 1.275709  [12.356073489642865, 9.0991430362990329, 10.96...
-2.383291  [12.356073489642865, 9.0991430362990329, 10.96...
-0.749621  [12.356073489642865, 9.0991430362990329, 10.96...
 0.259926  [12.356073489642865, 9.0991430362990329, 10.96...
-0.961855  [12.356073489642865, 9.0991430362990329, 10.96...
 0.092879  [12.356073489642865, 9.0991430362990329, 10.96...
-0.243091  [12.356073489642865, 9.0991430362990329, 10.96...
 0.981911  [12.356073489642865, 9.0991430362990329, 10.96...
 1.760888  [12.356073489642865, 9.0991430362990329, 10.96...
-1.368231  [12.356073489642865, 9.0991430362990329, 10.96...
 1.475516  [12.356073489642865, 9.0991430362990329, 10.96...
 0.819215  [12.356073489642865, 9.0991430362990329, 10.96...
 1.503681  [12.356073489642865, 9.0991430362990329, 10.96...
-1.826230  [12.356073489642865, 9.0991430362990329, 10.96...
</code>```

Title: Max and Min pandas - Python

Body:
I have a table that looks at the daily open, high, low and percentage change of a specific stock from year 2010 to today's date.

        Open     High      Low    Close  Percentage Chg
Date
2017-07-03   972.79   974.49   951.00   953.66          -1.481
2017-06-30   980.12   983.47   967.61   968.00          -0.813
2017-06-29   979.00   987.56   965.25   975.93          -1.454

I have created an empty table.

I would like to add the following to the empty column:

A column that has the top 5 largest Percentage Chg values

A column that hasthe bottom 5 lowest Percentage chg values

A column that calculates the variance of Column "CLOSE"

Thanks,

Body:
I've put together a script that seems to meets your 3 objectives.

I used pandas_datareader (version 0.4.0) to read in the AMAZON stock prices.

Here's the code with explanations in it:

 import pandas_datareader.data as web
import datetime

start = datetime.datetime(2010, 1, 1)
end = datetime.datetime(2017, 7, 5)

df = web.DataReader("AMZN", 'google', start, end)

#variance calculation
close_var = df['Close'].var()

#make variance a column
df['close_var_col'] = close_var

#selecting the first observation of opeing price from 2010
#base_open = int(df['Open'].head(1))

#creating the percentage difference from previous day
df['perc_chg'] = 100*(df['Close'] - df['Close'].shift(-1))/df['Close'].shift(-1)

#creating a df of top 5 and one of bottom 5 by perc_chg and removing Nan values
df = df.dropna(subset=['perc_chg'])
five_highest_df = df.sort_values(by='perc_chg').tail(5)
five_lowest_df = df.sort_values(by='perc_chg').head(5)

#creating a list of the top 5 (the only way I can think to this is with a string)
list_of_top_5 = str(list(set(list(five_highest_df['perc_chg']))))
list_of_bot_5 = str(list(set(list(five_lowest_df['perc_chg']))))

#Adding the list of the top 5 and bottom 5 to our dataframe
df['list_of_top_5'] = list_of_top_5
df['list_of_bot_5'] = list_of_bot_5

print(df.tail(20))

It's not very efficient and I'm not sure it's particularly useful as a dataframe.  Here's the output you should get.

                   Open     High      Low    Close    Volume  close_var_col
    Date
    2017-06-07  1005.95  1010.25  1002.00  1010.07   2823041   53171.161256
    2017-06-08  1012.06  1013.61  1006.11  1010.27   2767857   53171.161256
    2017-06-09  1012.50  1012.99   927.00   978.31   7647692   53171.161256
    2017-06-12   967.00   975.95   945.00   964.91   9447233   53171.161256
    2017-06-13   977.99   984.50   966.10   980.79   4580011   53171.161256
    2017-06-14   988.59   990.34   966.71   976.47   3974900   53171.161256
    2017-06-15   958.70   965.73   950.86   964.17   5373865   53171.161256
    2017-06-16   996.00   999.75   982.00   987.71  11472662   53171.161256
    2017-06-19  1017.00  1017.00   989.90   995.17   5043408   53171.161256
    2017-06-20   998.00  1004.88   992.02   992.59   4076828   53171.161256
    2017-06-21   998.70  1002.72   992.65  1002.23   2922473   53171.161256
    2017-06-22  1002.23  1006.96   997.20  1001.30   2253433   53171.161256
    2017-06-23  1002.54  1004.62   998.02  1003.74   2879145   53171.161256
    2017-06-26  1008.50  1009.80   992.00   993.98   3386157   53171.161256
    2017-06-27   990.69   998.80   976.00   976.78   3782389   53171.161256
    2017-06-28   978.55   990.68   969.21   990.33   3737567   53171.161256
    2017-06-29   979.00   987.56   965.25   975.93   4302968   53171.161256
    2017-06-30   980.12   983.47   967.61   968.00   3390345   53171.161256
    2017-07-03   972.79   974.49   951.00   953.66   2909108   53171.161256
    2017-07-05   961.53   975.00   955.25   971.40   3652955   53171.161256

 perc_chg                                      list_of_top_5

-0.699951  [12.356073489642865, 9.0991430362990329, 10.96...
-0.019797  [12.356073489642865, 9.0991430362990329, 10.96...
 3.266858  [12.356073489642865, 9.0991430362990329, 10.96...
 1.388731  [12.356073489642865, 9.0991430362990329, 10.96...
-1.619103  [12.356073489642865, 9.0991430362990329, 10.96...
 0.442410  [12.356073489642865, 9.0991430362990329, 10.96...
 1.275709  [12.356073489642865, 9.0991430362990329, 10.96...
-2.383291  [12.356073489642865, 9.0991430362990329, 10.96...
-0.749621  [12.356073489642865, 9.0991430362990329, 10.96...
 0.259926  [12.356073489642865, 9.0991430362990329, 10.96...
-0.961855  [12.356073489642865, 9.0991430362990329, 10.96...
 0.092879  [12.356073489642865, 9.0991430362990329, 10.96...
-0.243091  [12.356073489642865, 9.0991430362990329, 10.96...
 0.981911  [12.356073489642865, 9.0991430362990329, 10.96...
 1.760888  [12.356073489642865, 9.0991430362990329, 10.96...
-1.368231  [12.356073489642865, 9.0991430362990329, 10.96...
 1.475516  [12.356073489642865, 9.0991430362990329, 10.96...
 0.819215  [12.356073489642865, 9.0991430362990329, 10.96...
 1.503681  [12.356073489642865, 9.0991430362990329, 10.96...
-1.826230  [12.356073489642865, 9.0991430362990329, 10.96...


问:
Word VBA - Bold Paragraph If first character Is Numeric
Trying to make this macro go through all paragraphs and check if they start with a number, if yes, I'd like it to make all that paragraph Bold.
However, nothing happens, not even an error message.</p>

```<code>Sub titles()

    For Each Paragraph In ActiveDocument.Paragraphs
        If IsNumeric(Paragraph.Range.Words(1).Characters(1)) = True Then
            wcount = Paragraph.Range.Words.Count
            Paragraph.Range.Words(wcount).Font.Bold = True
            'MsgBox (wcount)
        End If
    Next Paragraph

End Sub
</code>```

答:
This:

```<code>Paragraph.Range.Words(wcount).Font.Bold = True
</code>```

will just bold the last "word".  Try:

```<code>Paragraph.Range.Font.Bold = True
</code>```

Body:
Trying to make this macro go through all paragraphs and check if they start with a number, if yes, I'd like it to make all that paragraph Bold.
However, nothing happens, not even an error message.

Sub titles()

    For Each Paragraph In ActiveDocument.Paragraphs
        If IsNumeric(Paragraph.Range.Words(1).Characters(1)) = True Then
            wcount = Paragraph.Range.Words.Count
            Paragraph.Range.Words(wcount).Font.Bold = True
            'MsgBox (wcount)
        End If
    Next Paragraph

End Sub

Body:
This:

Paragraph.Range.Words(wcount).Font.Bold = True

will just bold the last "word".  Try:

Paragraph.Range.Font.Bold = True


问:
Eclipse Oxygen Oracle java 8
Can't install Eclipse Oxygen, I installed Java Oracle 8 following these instructions

```<code>sudo apt-add-repository ppa:webupd8team/java
sudo apt-get update
sudo apt-get install oracle-java8-installer
</code>```

then I downloaded Eclipse Oxygen , I run the eclipse-inst and I get this :

```<code>JVM terminated. Exit code=11
/usr/bin/java
-Xms256M
-Xmx1024M
-jar /home/ly/Ly-Data/Linux Programs/eclipse-installer//plugins/org.eclipse.equinox.launcher_1.4.0.v20161219-1356.jar
-os linux
-ws gtk
-arch x86_64
-showsplash
-launcher /home/ly/Ly-Data/Linux Programs/eclipse-installer/eclipse-inst
-name Eclipse Installer
--launcher.library /home/ly/Ly-Data/Linux Programs/eclipse-installer//plugins/org.eclipse.equinox.launcher.gtk.linux.x86_64_1.1.500.v20170531-1133/eclipse_1624.so
-startup /home/ly/Ly-Data/Linux Programs/eclipse-installer//plugins/org.eclipse.equinox.launcher_1.4.0.v20161219-1356.jar
--launcher.appendVmargs
-exitdata 358010
-data @noDefault
-vm /usr/bin/java
-vmargs
-Xms256M
-Xmx1024M
-jar /home/ly/Ly-Data/Linux Programs/eclipse-installer//plugins/org.eclipse.equinox.launcher_1.4.0.v20161219-1356.jar
</code>```

I searched about it and thought it was a location problem, output from

```<code>which java
/usr/bin/java

whereis java
java: /usr/bin/java /usr/share/java /usr/lib/jvm/java-8-oracle/bin/java /usr/lib/jvm/java-8-oracle/jre/bin/java /usr/share/man/man1/java.1.gz
</code>```

Here is the content of the eclipse-isnt.ini file :

```<code>-startup
plugins/org.eclipse.equinox.launcher_1.4.0.v20161219-1356.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.gtk.linux.x86_64_1.1.500.v20170531-1133
--launcher.appendVmargs
--launcher.XXMaxPermSize
256M
-name
Eclipse Installer
-data
@noDefault
--launcher.GTK_version
2
-vmargs
-Xms256M
-Xmx1024M
</code>```

I already tried to add this line :

```<code>-vm
/usr/lib/jvm/java-8-oracle/bin/java
</code>```

right before -vmargs line, and it still doesn't work.
I get this error code :

```<code>JVM terminated. Exit code=11
/usr/lib/jvm/java-8-oracle/bin/java
-Xms256M
-Xmx1024M
-jar /home/ly/Ly-Data/Linux Programs/eclipse-installer//plugins/org.eclipse.equinox.launcher_1.4.0.v20161219-1356.jar
-os linux
-ws gtk
-arch x86_64
-showsplash
-launcher /home/ly/Ly-Data/Linux Programs/eclipse-installer/eclipse-inst
-name Eclipse Installer
--launcher.library /home/ly/Ly-Data/Linux Programs/eclipse-installer//plugins/org.eclipse.equinox.launcher.gtk.linux.x86_64_1.1.500.v20170531-1133/eclipse_1624.so
-startup /home/ly/Ly-Data/Linux Programs/eclipse-installer//plugins/org.eclipse.equinox.launcher_1.4.0.v20161219-1356.jar
--launcher.appendVmargs
-exitdata 3c8013
-data @noDefault
-vm /usr/lib/jvm/java-8-oracle/bin/java
-vmargs
-Xms256M
-Xmx1024M
-jar /home/ly/Ly-Data/Linux Programs/eclipse-installer//plugins/org.eclipse.equinox.launcher_1.4.0.v20161219-1356.jar
</code>```

Thanks for the help.

答:
after toying around with the eclipse-inst.ini file i find the porblem and  solved it. all i had to do was to delete the number 2 on one of the ini file lines (which was, for whatever reason always fixing the jvm location to usr/bin/java), so just replace the content of eclipse-inst.ini file with this one :

```<code>-startup
plugins/org.eclipse.equinox.launcher_1.4.0.v20161219-1356.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.gtk.linux.x86_64_1.1.500.v20170531-1133
--launcher.appendVmargs
--launcher.XXMaxPermSize
256M
-name
Eclipse Installer
-data
@noDefault
--launcher.GTK_version

-vm /usr/lib/jvm/java-8-oracle/bin/java
-vmargs
-Xms256M
-Xmx1024M
</code>```

replace the path in the line beginning with "-vm ..." with your path to java (which you can know by typing the "whereis java" command line).

Title: Eclipse Oxygen Oracle java 8

Body:
Can't install Eclipse Oxygen, I installed Java Oracle 8 following these instructions

sudo apt-add-repository ppa:webupd8team/java
sudo apt-get update
sudo apt-get install oracle-java8-installer

then I downloaded Eclipse Oxygen , I run the eclipse-inst and I get this :

JVM terminated. Exit code=11
/usr/bin/java
-Xms256M
-Xmx1024M
-jar /home/ly/Ly-Data/Linux Programs/eclipse-installer//plugins/org.eclipse.equinox.launcher_1.4.0.v20161219-1356.jar
-os linux
-ws gtk
-arch x86_64
-showsplash
-launcher /home/ly/Ly-Data/Linux Programs/eclipse-installer/eclipse-inst
-name Eclipse Installer
--launcher.library /home/ly/Ly-Data/Linux Programs/eclipse-installer//plugins/org.eclipse.equinox.launcher.gtk.linux.x86_64_1.1.500.v20170531-1133/eclipse_1624.so
-startup /home/ly/Ly-Data/Linux Programs/eclipse-installer//plugins/org.eclipse.equinox.launcher_1.4.0.v20161219-1356.jar
--launcher.appendVmargs
-exitdata 358010
-data @noDefault
-vm /usr/bin/java
-vmargs
-Xms256M
-Xmx1024M
-jar /home/ly/Ly-Data/Linux Programs/eclipse-installer//plugins/org.eclipse.equinox.launcher_1.4.0.v20161219-1356.jar

I searched about it and thought it was a location problem, output from

which java
/usr/bin/java

whereis java
java: /usr/bin/java /usr/share/java /usr/lib/jvm/java-8-oracle/bin/java /usr/lib/jvm/java-8-oracle/jre/bin/java /usr/share/man/man1/java.1.gz

Here is the content of the eclipse-isnt.ini file :

-startup
plugins/org.eclipse.equinox.launcher_1.4.0.v20161219-1356.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.gtk.linux.x86_64_1.1.500.v20170531-1133
--launcher.appendVmargs
--launcher.XXMaxPermSize
256M
-name
Eclipse Installer
-data
@noDefault
--launcher.GTK_version
2
-vmargs
-Xms256M
-Xmx1024M

I already tried to add this line :

-vm
/usr/lib/jvm/java-8-oracle/bin/java

right before -vmargs line, and it still doesn't work.
I get this error code :

JVM terminated. Exit code=11
/usr/lib/jvm/java-8-oracle/bin/java
-Xms256M
-Xmx1024M
-jar /home/ly/Ly-Data/Linux Programs/eclipse-installer//plugins/org.eclipse.equinox.launcher_1.4.0.v20161219-1356.jar
-os linux
-ws gtk
-arch x86_64
-showsplash
-launcher /home/ly/Ly-Data/Linux Programs/eclipse-installer/eclipse-inst
-name Eclipse Installer
--launcher.library /home/ly/Ly-Data/Linux Programs/eclipse-installer//plugins/org.eclipse.equinox.launcher.gtk.linux.x86_64_1.1.500.v20170531-1133/eclipse_1624.so
-startup /home/ly/Ly-Data/Linux Programs/eclipse-installer//plugins/org.eclipse.equinox.launcher_1.4.0.v20161219-1356.jar
--launcher.appendVmargs
-exitdata 3c8013
-data @noDefault
-vm /usr/lib/jvm/java-8-oracle/bin/java
-vmargs
-Xms256M
-Xmx1024M
-jar /home/ly/Ly-Data/Linux Programs/eclipse-installer//plugins/org.eclipse.equinox.launcher_1.4.0.v20161219-1356.jar

Thanks for the help.

Body:
after toying around with the eclipse-inst.ini file i find the porblem and  solved it. all i had to do was to delete the number 2 on one of the ini file lines (which was, for whatever reason always fixing the jvm location to usr/bin/java), so just replace the content of eclipse-inst.ini file with this one :

-startup
plugins/org.eclipse.equinox.launcher_1.4.0.v20161219-1356.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.gtk.linux.x86_64_1.1.500.v20170531-1133
--launcher.appendVmargs
--launcher.XXMaxPermSize
256M
-name
Eclipse Installer
-data
@noDefault
--launcher.GTK_version

-vm /usr/lib/jvm/java-8-oracle/bin/java
-vmargs
-Xms256M
-Xmx1024M

replace the path in the line beginning with "-vm ..." with your path to java (which you can know by typing the "whereis java" command line).


问:
Using uber API to schedule rides for others (customers)
1.
I've been researching into the Uber API and I can't seem to find concrete information regarding whether or not you can request rides for other people. I want to be able to offer clients that come to my business a ride home or a ride to my business. I see Uber Central is meant to fill that, but is there a way to use the API to do what Uber Central is made to do?

2.
 Also, is it possible to use the Uber Central API (if it exists) to charge the customer for the ride?

Thanks.

答:
There is not a directly publicly available API to pay for other's rides currently. As you mention, Uber Central (https://help.uber.com/h/502388e3-df83-4c4b-964d-625a1d161e12) is a good option but does not have a public API available.

Another suggestion that might be useful for you is https://vouchers.uber.com which allows you to buy promo codes for a specific location. Again, this is not available currently in an API.

This is an area that the Uber API team is exploring, however, so keep an eye out for any announcements.

Cheers.


问:
SQLException: incorrect syntax near '2'
whenever I call the "ExecuteNonQuery" command on the following CommandText, I get the above SQLException

```<code>myCommand.CommandText = "INSERT INTO fixtures (round_id, matchcode, date_utc, time_utc, date_london, time_london, team_A_id, team_A, team_A_country, team_B_id, team_B, team_B_country, status, gameweek, winner, fs_A, fs_B, hts_A, hts_B, ets_A, ets_B, ps_A, ps_B, last_updated) VALUES (" _
            & round_id & "," & match_id & "," & date_utc & ",'" & time_utc & "'," & date_london & ",'" & time_london & "'," & team_A_id & ",'" & team_A_name & "','" & team_A_country & "'," & team_B_id & ",'" & team_B_name & "','" & _
            team_B_country & "','" & status & "'," & gameweek & ",'" & winner & "'," & fs_A & "," & fs_B & "," & hts_A & "," & hts_B & "," & ets_A & "," & ets_B & "," & ps_A & "," & ps_B & "," & last_updated & ")"
</code>```

But whenever, i remove the last table item - "last_updated", the error disappears. Please help me resolve this issue. Is there any special treatment to be given to datetime fields???

Thanks for your help

答:
Almost certainly the value contained in last_updated has to be delimited in the resulting INSERT statement (the "2" in the exception is probably from 2010-etc).

Please don't post the expression you use to calculate the INSERT statement but rather the resulting statement itself (the contents of CommandText).  That's where the error is.

ContentLicense: CC BY-SA 2.5

Title: SQLException: incorrect syntax near '2'

Body:
whenever I call the "ExecuteNonQuery" command on the following CommandText, I get the above SQLException

myCommand.CommandText = "INSERT INTO fixtures (round_id, matchcode, date_utc, time_utc, date_london, time_london, team_A_id, team_A, team_A_country, team_B_id, team_B, team_B_country, status, gameweek, winner, fs_A, fs_B, hts_A, hts_B, ets_A, ets_B, ps_A, ps_B, last_updated) VALUES (" _
            & round_id & "," & match_id & "," & date_utc & ",'" & time_utc & "'," & date_london & ",'" & time_london & "'," & team_A_id & ",'" & team_A_name & "','" & team_A_country & "'," & team_B_id & ",'" & team_B_name & "','" & _
            team_B_country & "','" & status & "'," & gameweek & ",'" & winner & "'," & fs_A & "," & fs_B & "," & hts_A & "," & hts_B & "," & ets_A & "," & ets_B & "," & ps_A & "," & ps_B & "," & last_updated & ")"

But whenever, i remove the last table item - "last_updated", the error disappears. Please help me resolve this issue. Is there any special treatment to be given to datetime fields???

Thanks for your help


问:
Ruby reverse iterate array but not index
How to convert this code to Ruby involving reversed array iteration and but not indexing?

```<code>    out = 0
    for index,x in enumerate(reversed(d)):
        out += x*pow(2,index)
</code>```

From what I can understand from the Python code, the array d is reversed but the index of the elements are not?

Twisting!

How to do this in Ruby?

答:
The equivalent of your Python code snippet in Ruby is:</p>

```<code>d.reverse_each.with_index.inject(0) do |out, (x,i)|
  out += x * 2**i
end
</code>```

Body:
How to convert this code to Ruby involving reversed array iteration and but not indexing?

    out = 0
    for index,x in enumerate(reversed(d)):
        out += x*pow(2,index)

From what I can understand from the Python code, the array d is reversed but the index of the elements are not?

Twisting!

How to do this in Ruby?

Body:
The equivalent of your Python code snippet in Ruby is:

d.reverse_each.with_index.inject(0) do |out, (x,i)|
  out += x * 2**i
end


问:
Intermittent JSON parser failure for unescaped control character
Functionality in an iPhone app that searches twitter for some text.  The code is very straightforward, I pass the url string to the twitter api, and then parse the result. Although half the time JSON parser fails with errors for Unescaped control character '0x0'.  Code and full error message below.

```<code>    - (void)grabData:(NSString *)searchTerm {
     NSString *urlString = [NSString stringWithFormat:@"http://search.twitter.com/search.json?q=%@&rpp=25",searchTerm];

     NSURL *url = [NSURL URLWithString:urlString];

     NSLog(@"Created url:%@",url);

     //Setup and start async download
     NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
     NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
     [connection release];
     [request release];
    }

    - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {

     // Store incoming data into a string
     NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

     //NSLog(@"Did receive some data %@",jsonString);

     //Create a dictionary from the JSON string
     NSDictionary *results = [jsonString JSONValue];

     // Build an Array from the dictionary for easy access to each entry
     NSDictionary *tweets = [results objectForKey:@"results"];

            // Loop through each entry in the dictionary
    for(NSDictionary *tweet in tweets) {
     // Get the user string for the tweet
     NSString *tUser = [tweet objectForKey:@"from_user"];
           NSLog(@"Tweet from %@",tUser);
          }

    }
</code>```

Error Message from console, 50% of the time, other 50% it works as expected.

```<code>2010-12-20 21:22:02.022 TwitterSearch[47362:207] Created url:http://search.twitter.com/search.json?q=red&rpp=25
2010-12-20 21:22:02.361 TwitterSearch[47362:207] -JSONValue failed. Error trace is: (
    "Error Domain=org.brautaset.JSON.ErrorDomain Code=5 \"Unescaped control character '0x0'\" UserInfo=0x4d6a130 {NSLocalizedDescription=Unescaped control character '0x0'}",
    "Error Domain=org.brautaset.JSON.ErrorDomain Code=3 \"Object value expected for key: profile_image_url\" UserInfo=0x4d6a200 {NSUnderlyingError=0x4d6a170 \"Unescaped control character '0x0'\", NSLocalizedDescription=Object value expected for key: profile_image_url}",
    "Error Domain=org.brautaset.JSON.ErrorDomain Code=3 \"Expected value while parsing array\" UserInfo=0x4d6a240 {NSUnderlyingError=0x4d6a1e0 \"Object value expected for key: profile_image_url\", NSLocalizedDescription=Expected value while parsing array}",
    "Error Domain=org.brautaset.JSON.ErrorDomain Code=3 \"Object value expected for key: results\" UserInfo=0x4d6a310 {NSUnderlyingError=0x4d6a2d0 \"Expected value while parsing array\", NSLocalizedDescription=Object value expected for key: results}"
)
</code>```

答:
The didReceiveData method can be called multiple times as the data is delivered.  So in that method, you should simply append each incoming chunk to an NSMutableData class variable (not process it).

The processing of the complete data should be done in the connectionDidFinishLoading method.

The error is probably happening because it is trying to parse a partial block of data.

Body:
Functionality in an iPhone app that searches twitter for some text.  The code is very straightforward, I pass the url string to the twitter api, and then parse the result. Although half the time JSON parser fails with errors for Unescaped control character '0x0'.  Code and full error message below.

    - (void)grabData:(NSString *)searchTerm {
     NSString *urlString = [NSString stringWithFormat:@"http://search.twitter.com/search.json?q=%@&rpp=25",searchTerm];

     NSURL *url = [NSURL URLWithString:urlString];

     NSLog(@"Created url:%@",url);

     //Setup and start async download
     NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
     NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
     [connection release];
     [request release];
    }

    - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {

     // Store incoming data into a string
     NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

     //NSLog(@"Did receive some data %@",jsonString);

     //Create a dictionary from the JSON string
     NSDictionary *results = [jsonString JSONValue];

     // Build an Array from the dictionary for easy access to each entry
     NSDictionary *tweets = [results objectForKey:@"results"];

            // Loop through each entry in the dictionary
    for(NSDictionary *tweet in tweets) {
     // Get the user string for the tweet
     NSString *tUser = [tweet objectForKey:@"from_user"];
           NSLog(@"Tweet from %@",tUser);
          }

    }

Error Message from console, 50% of the time, other 50% it works as expected.

2010-12-20 21:22:02.022 TwitterSearch[47362:207] Created url:http://search.twitter.com/search.json?q=red&rpp=25
2010-12-20 21:22:02.361 TwitterSearch[47362:207] -JSONValue failed. Error trace is: (
    "Error Domain=org.brautaset.JSON.ErrorDomain Code=5 \"Unescaped control character '0x0'\" UserInfo=0x4d6a130 {NSLocalizedDescription=Unescaped control character '0x0'}",
    "Error Domain=org.brautaset.JSON.ErrorDomain Code=3 \"Object value expected for key: profile_image_url\" UserInfo=0x4d6a200 {NSUnderlyingError=0x4d6a170 \"Unescaped control character '0x0'\", NSLocalizedDescription=Object value expected for key: profile_image_url}",
    "Error Domain=org.brautaset.JSON.ErrorDomain Code=3 \"Expected value while parsing array\" UserInfo=0x4d6a240 {NSUnderlyingError=0x4d6a1e0 \"Object value expected for key: profile_image_url\", NSLocalizedDescription=Expected value while parsing array}",
    "Error Domain=org.brautaset.JSON.ErrorDomain Code=3 \"Object value expected for key: results\" UserInfo=0x4d6a310 {NSUnderlyingError=0x4d6a2d0 \"Expected value while parsing array\", NSLocalizedDescription=Object value expected for key: results}"
)


问:
Transform property in Firefox and Dropdown bug
I am having an issue with a form in a popup container that is using the css property transform:translate to center the popup.

I have a a form inside with select fields and the dropdowns are not moving with the rest of the content. They are positioned where the popup would be if it didn't have the transform property on it.

This is only happening in Firefox. I've tried adding transform:none to the select fields and child elements, as well as using a transform that is the opposite of the popup but nothing is working. Does anyone know a fix for this? Thank you.

答:
Turned out to be an animation styling property on the popup. I removed it and boom, back to normal. Thanks, Gaby aka G. Petrioli, for the reply.

```<code>.smile-3DRotateBottom {
-webkit-animation-name: smile-3DRotateBottom;
animation-name: smile-3DRotateBottom;
-webkit-perspective: 1300px;
perspective: 1300px;
-webkit-transform-style: preserve-3d;
transform-style: preserve-3d;
-webkit-transform-origin: 0 100%;
transform-origin: 0 100%;
</code>```

}

Body:
Turned out to be an animation styling property on the popup. I removed it and boom, back to normal. Thanks, Gaby aka G. Petrioli, for the reply.

.smile-3DRotateBottom {
-webkit-animation-name: smile-3DRotateBottom;
animation-name: smile-3DRotateBottom;
-webkit-perspective: 1300px;
perspective: 1300px;
-webkit-transform-style: preserve-3d;
transform-style: preserve-3d;
-webkit-transform-origin: 0 100%;
transform-origin: 0 100%;

}


问:
step plot using holoviews bokeh
I'm trying to add two step plots to the same Bokeh plot. Each step plot has different x values though, so the Step function in the bkcharts package doesnt work. I wanted to overlay two single Step charts produced by the bkcharts package, but it seems that you can't create a step chart with holoviews. Is there an easy workaround?

```<code>import bokeh.plotting as bk
from bokeh.charts import Step
import pandas as pd

data1 = pd.DataFrame({'time': [1,3,5,7], 'value': [3,4,1,3]})
data2 = pd.DataFrame({'time': [2,4,6,9], 'value': [2,1,4,2]})

step1 = Step(data1, x='time', y='value')
step2 = Step(data2, x='time', y='value')

bk.show(Step(data1, x='time', y='value'))
bk.show(Step(data2, x='time', y='value'))
</code>```

I would like to do something like step1 * step2

答:
HoloViews does let you do a step chart, using options to the Curve element.  See the example in the Gallery:

```<code>%%opts Curve [width=600] NdOverlay [legend_position='right']
hv.NdOverlay({interp: hv.Curve(points[::8])(plot=dict(interpolation=interp))
              for interp in ['linear', 'steps-mid', 'steps-pre', 'steps-post']})
</code>```

You can do the same with a regular Overlay (the * operator) too; the key is to set the interpolation option to one of the available types of steps.

Title: step plot using holoviews bokeh

Body:
I'm trying to add two step plots to the same Bokeh plot. Each step plot has different x values though, so the Step function in the bkcharts package doesnt work. I wanted to overlay two single Step charts produced by the bkcharts package, but it seems that you can't create a step chart with holoviews. Is there an easy workaround?

import bokeh.plotting as bk
from bokeh.charts import Step
import pandas as pd

data1 = pd.DataFrame({'time': [1,3,5,7], 'value': [3,4,1,3]})
data2 = pd.DataFrame({'time': [2,4,6,9], 'value': [2,1,4,2]})

step1 = Step(data1, x='time', y='value')
step2 = Step(data2, x='time', y='value')

bk.show(Step(data1, x='time', y='value'))
bk.show(Step(data2, x='time', y='value'))

I would like to do something like step1 * step2

Body:
HoloViews does let you do a step chart, using options to the Curve element.  See the example in the Gallery:

%%opts Curve [width=600] NdOverlay [legend_position='right']
hv.NdOverlay({interp: hv.Curve(points[::8])(plot=dict(interpolation=interp))
              for interp in ['linear', 'steps-mid', 'steps-pre', 'steps-post']})

You can do the same with a regular Overlay (the * operator) too; the key is to set the interpolation option to one of the available types of steps.


问:
accessing a method from a property and not an instance? Xcode
I'm confused how the following code uses the view property to access the subView method in the viewDidLoad() function. The viewDidLoad function provides access to the view property, but why is the addSubView method accessed from a property and not an instance?

```<code>override func viewDidLoad() {
    super.viewDidLoad()
    let label = UILabel(frame: CGRect(x: 16, y: 16, width: 200,
height: 44))
    view.addSubview(label) // Adds label as a child view to `view`
}
</code>```

答:
The view is a property of the viewcontroller, but it is an instance of UIView, which has a set of subviews, and you can add to this set by calling addSubview() on any UIView instance.
https://developer.apple.com/documentation/uikit/uiview</p>

Body:
I'm confused how the following code uses the view property to access the subView method in the viewDidLoad() function. The viewDidLoad function provides access to the view property, but why is the addSubView method accessed from a property and not an instance?

override func viewDidLoad() {
    super.viewDidLoad()
    let label = UILabel(frame: CGRect(x: 16, y: 16, width: 200,
height: 44))
    view.addSubview(label) // Adds label as a child view to `view`
}


问:
Start PHPmyAdmin from putty - Server is remote
Bit stuck here, I have looked on here, for similar, but cant find what I need.
Have looked at how to start PHPmyAdmin via putty on here.

I have a server, which is on a network. I log into the network via Putty.
The database usual access is for example 10.32.187.100/m . This is how I used to access it before the server reboot.

I have had to restart the server. But I cannot log into the database as I believe I have to turn it on.

As it is not on a local machine I do not know how. It is a linux server, and the location of ‘m’ is /var/www/html

In ‘m’ are the files for phpmyAdmin.

Nothing has been over written. The server had to restart. Hence why I need to start up PHPmyAdmin.

Can I ask how do I turn on PHPmyAdmin via putty I the method I need to use?

答:
try this</p>

```<code>sudo service mysql start
sudo service apache2 start
</code>```

Body:
try this

sudo service mysql start
sudo service apache2 start


问:
Child vs Parent Z-index issue
I looked at several related questions but I cannt find a solution. I even tried to use the solution in this article but it didn't work for me. > https://philipwalton.com/articles/what-no-one-told-you-about-z-index/

I need the "HOVER" to be ON the "bottom" div. Please note that I cann't change the declared position of the elements.

Is there a solution?

My code:

.top {
  position: fixed;
  z-index: 1;
}

.hover {
  position: absolute;
  z-index: 999;
}

.bottom {
  position: absolute;
  z-index: 1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="top">top
  <div class="hover">HOVER</div>
</div>
<div class="bottom">bottom<div></code>```

答:
You can't. The child element is only capable of changing within the parents region. If you try to change the childs css and it apposes the parent, the parents css will override it.

You could try to use JS to move the child outside the parent div. I would recommend using the .append() in jquery.

Title: Child vs Parent Z-index issue

Body:
I looked at several related questions but I cannt find a solution. I even tried to use the solution in this article but it didn't work for me. > https://philipwalton.com/articles/what-no-one-told-you-about-z-index/

I need the "HOVER" to be ON the "bottom" div. Please note that I cann't change the declared position of the elements.

Is there a solution?

My code:

.top {
  position: fixed;
  z-index: 1;
}

.hover {
  position: absolute;
  z-index: 999;
}

.bottom {
  position: absolute;
  z-index: 1;
}

top

HOVER

bottom


问:
Activate Anaconda Python environment from makefile
I want to use a makefile to build my project's environment using a makefile and anaconda/miniconda, so I should be able to clone the repo and simply run make myproject

```<code>myproject: build

build:
  @printf "\nBuilding Python Environment\n"
  @conda env create --quiet --force --file environment.yml
  @source /home/vagrant/miniconda/bin/activate myproject
</code>```

If I try this, however, I get the following error

make: source: Command not found

make: *** [source] Error 127

I have searched for a solution, but [this question/answer(How to source a script in a Makefile?) suggests that I cannot use source from within a makefile.

This answer, however, proposes a solution (and received several upvotes) but this doesn't work for me either

( \

      source /home/vagrant/miniconda/bin/activate myproject; \

)

/bin/sh: 2: source: not found

make: *** [source] Error 127

I also tried moving the source activate step to a separate bash script, and executing that script from the makefile. That doesn't work, and I assume for the a similar reason, i.e. I am running source from within a shell.

I should add that if I run source activate myproject from the terminal, it works correctly.

答:
You should use this, it's functional for me at moment.</p>

```<code>report.ipynb : merged.ipynb
    ( bash -c "source ${HOME}/anaconda3/bin/activate py27; which -a python; \
        jupyter nbconvert \
        --to notebook \
        --ExecutePreprocessor.kernel_name=python2 \
        --ExecutePreprocessor.timeout=3000 \
        --execute merged.ipynb \
        --output=$< $<" )
</code>```

Body:
I want to use a makefile to build my project's environment using a makefile and anaconda/miniconda, so I should be able to clone the repo and simply run make myproject

myproject: build

build:
  @printf "\nBuilding Python Environment\n"
  @conda env create --quiet --force --file environment.yml
  @source /home/vagrant/miniconda/bin/activate myproject

If I try this, however, I get the following error

make: source: Command not found

make: *** [source] Error 127

I have searched for a solution, but [this question/answer(How to source a script in a Makefile?) suggests that I cannot use source from within a makefile.

This answer, however, proposes a solution (and received several upvotes) but this doesn't work for me either

( \

      source /home/vagrant/miniconda/bin/activate myproject; \

)

/bin/sh: 2: source: not found

make: *** [source] Error 127

I also tried moving the source activate step to a separate bash script, and executing that script from the makefile. That doesn't work, and I assume for the a similar reason, i.e. I am running source from within a shell.

I should add that if I run source activate myproject from the terminal, it works correctly.

Body:
You should use this, it's functional for me at moment.

report.ipynb : merged.ipynb
    ( bash -c "source ${HOME}/anaconda3/bin/activate py27; which -a python; \
        jupyter nbconvert \
        --to notebook \
        --ExecutePreprocessor.kernel_name=python2 \
        --ExecutePreprocessor.timeout=3000 \
        --execute merged.ipynb \
        --output=$< $<" )


问:
Android: getting Resources$NotFoundException for abc_ic_ab_back_material
I'm getting a Resources$notfoundexception on older (pre-L) devices. I'm including the full stacktrace below.

My version of the support library is the latest (24.1.0), and I've included in my gradle file the line:

```<code>vectorDrawables.useSupportLibrary = true
</code>```

My base theme is a noactionbar theme - "Theme.AppCompat.Light.NoActionBar"

The crash is happening on this line in my code where I reference the back arrow in a support-toolbar in order to later change it's color:

```<code>@SuppressLint("PrivateResource") final Drawable upArrow = ContextCompat.getDrawable(this, R.drawable.abc_ic_ab_back_material);
</code>```

What could be the cause of this? This code works fine for all users with L or above.

```<code>07-19 22:36:57.029 9330-9330/mypkg E/AndroidRuntime: FATAL EXCEPTION: main
 java.lang.RuntimeException: Unable to resume activity {mypkg/mypkg.activites.myActivity}: android.content.res.Resources$NotFoundException: File res/drawable/abc_ic_ab_back_material.xml from drawable resource ID #0x7f020013
     at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2619)
     at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2647)
     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2104)
     at android.app.ActivityThread.access$600(ActivityThread.java:138)
     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1205)
     at android.os.Handler.dispatchMessage(Handler.java:99)
     at android.os.Looper.loop(Looper.java:137)
     at android.app.ActivityThread.main(ActivityThread.java:4929)
     at java.lang.reflect.Method.invokeNative(Native Method)
     at java.lang.reflect.Method.invoke(Method.java:511)
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:798)
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:565)
     at dalvik.system.NativeStart.main(Native Method)
  Caused by: android.content.res.Resources$NotFoundException: File res/drawable/abc_ic_ab_back_material.xml from drawable resource ID #0x7f020013
     at android.content.res.Resources.loadDrawable(Resources.java:1957)
     at android.content.res.Resources.getDrawable(Resources.java:673)
     at android.support.v4.content.ContextCompat.getDrawable(ContextCompat.java:354)
     at mypkg.base.mymethod(myactivity.java:100)
     at mypkg.mymethod(myactivity.java:100)
     at android.support.v4.app.FragmentActivity.onPostResume(FragmentActivity.java:511)
     at android.support.v7.app.AppCompatActivity.onPostResume(AppCompatActivity.java:178)
     at android.app.Activity.performResume(Activity.java:5341)
     at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2599)
     at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2647)
     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2104)
     at android.app.ActivityThread.access$600(ActivityThread.java:138)
     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1205)
     at android.os.Handler.dispatchMessage(Handler.java:99)
     at android.os.Looper.loop(Looper.java:137)
     at android.app.ActivityThread.main(ActivityThread.java:4929)
     at java.lang.reflect.Method.invokeNative(Native Method)
     at java.lang.reflect.Method.invoke(Method.java:511)
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:798)
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:565)
     at dalvik.system.NativeStart.main(Native Method)
  Caused by: org.xmlpull.v1.XmlPullParserException: Binary XML file line #17: invalid drawable tag vector
     at android.graphics.drawable.Drawable.createFromXmlInner(Drawable.java:877)
     at android.graphics.drawable.Drawable.createFromXml(Drawable.java:818)
     at android.content.res.Resources.loadDrawable(Resources.java:1954)
     at android.content.res.Resources.getDrawable(Resources.java:673)
     at android.support.v4.content.ContextCompat.getDrawable(ContextCompat.java:354)
     at mypkg/mymethod(myactivity.java:100)
     at mypkg/mymethod(myactivity.java:100)
     at android.support.v4.app.FragmentActivity.onPostResume(FragmentActivity.java:511)
     at android.support.v7.app.AppCompatActivity.onPostResume(AppCompatActivity.java:178)
     at android.app.Activity.performResume(Activity.java:5341)
     at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2599)
     at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2647)
     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2104)
     at android.app.ActivityThread.access$600(ActivityThread.java:138)
     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1205)
     at android.os.Handler.dispatchMessage(Handler.java:99)
     at android.os.Looper.loop(Looper.java:137)
     at android.app.ActivityThread.main(ActivityThread.java:4929)
     at java.lang.reflect.Method.invokeNative(Native Method)
     at java.lang.reflect.Method.invoke(Method.java:511)
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:798)
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:565)
     at dalvik.system.NativeStart.main(Native Method)
</code>```

答:
I was using the application context when calling ContextCompat.getDrawable() which also crashes the app with Resources$NotFoundException and now the following message even though everything else was set up just fine:

If the resource you are trying to use is a vector resource, you may be
  referencing it in an unsupported way. See
  AppCompatDelegate.setCompatVectorFromResourcesEnabled() for more info.

All I had to do was to change to the view's Context. :)

Body:
I'm getting a Resources$notfoundexception on older (pre-L) devices. I'm including the full stacktrace below.

My version of the support library is the latest (24.1.0), and I've included in my gradle file the line:

vectorDrawables.useSupportLibrary = true

My base theme is a noactionbar theme - "Theme.AppCompat.Light.NoActionBar"

The crash is happening on this line in my code where I reference the back arrow in a support-toolbar in order to later change it's color:

@SuppressLint("PrivateResource") final Drawable upArrow = ContextCompat.getDrawable(this, R.drawable.abc_ic_ab_back_material);

What could be the cause of this? This code works fine for all users with L or above.

07-19 22:36:57.029 9330-9330/mypkg E/AndroidRuntime: FATAL EXCEPTION: main
 java.lang.RuntimeException: Unable to resume activity {mypkg/mypkg.activites.myActivity}: android.content.res.Resources$NotFoundException: File res/drawable/abc_ic_ab_back_material.xml from drawable resource ID #0x7f020013
     at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2619)
     at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2647)
     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2104)
     at android.app.ActivityThread.access$600(ActivityThread.java:138)
     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1205)
     at android.os.Handler.dispatchMessage(Handler.java:99)
     at android.os.Looper.loop(Looper.java:137)
     at android.app.ActivityThread.main(ActivityThread.java:4929)
     at java.lang.reflect.Method.invokeNative(Native Method)
     at java.lang.reflect.Method.invoke(Method.java:511)
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:798)
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:565)
     at dalvik.system.NativeStart.main(Native Method)
  Caused by: android.content.res.Resources$NotFoundException: File res/drawable/abc_ic_ab_back_material.xml from drawable resource ID #0x7f020013
     at android.content.res.Resources.loadDrawable(Resources.java:1957)
     at android.content.res.Resources.getDrawable(Resources.java:673)
     at android.support.v4.content.ContextCompat.getDrawable(ContextCompat.java:354)
     at mypkg.base.mymethod(myactivity.java:100)
     at mypkg.mymethod(myactivity.java:100)
     at android.support.v4.app.FragmentActivity.onPostResume(FragmentActivity.java:511)
     at android.support.v7.app.AppCompatActivity.onPostResume(AppCompatActivity.java:178)
     at android.app.Activity.performResume(Activity.java:5341)
     at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2599)
     at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2647)
     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2104)
     at android.app.ActivityThread.access$600(ActivityThread.java:138)
     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1205)
     at android.os.Handler.dispatchMessage(Handler.java:99)
     at android.os.Looper.loop(Looper.java:137)
     at android.app.ActivityThread.main(ActivityThread.java:4929)
     at java.lang.reflect.Method.invokeNative(Native Method)
     at java.lang.reflect.Method.invoke(Method.java:511)
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:798)
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:565)
     at dalvik.system.NativeStart.main(Native Method)
  Caused by: org.xmlpull.v1.XmlPullParserException: Binary XML file line #17: invalid drawable tag vector
     at android.graphics.drawable.Drawable.createFromXmlInner(Drawable.java:877)
     at android.graphics.drawable.Drawable.createFromXml(Drawable.java:818)
     at android.content.res.Resources.loadDrawable(Resources.java:1954)
     at android.content.res.Resources.getDrawable(Resources.java:673)
     at android.support.v4.content.ContextCompat.getDrawable(ContextCompat.java:354)
     at mypkg/mymethod(myactivity.java:100)
     at mypkg/mymethod(myactivity.java:100)
     at android.support.v4.app.FragmentActivity.onPostResume(FragmentActivity.java:511)
     at android.support.v7.app.AppCompatActivity.onPostResume(AppCompatActivity.java:178)
     at android.app.Activity.performResume(Activity.java:5341)
     at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2599)
     at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2647)
     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2104)
     at android.app.ActivityThread.access$600(ActivityThread.java:138)
     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1205)
     at android.os.Handler.dispatchMessage(Handler.java:99)
     at android.os.Looper.loop(Looper.java:137)
     at android.app.ActivityThread.main(ActivityThread.java:4929)
     at java.lang.reflect.Method.invokeNative(Native Method)
     at java.lang.reflect.Method.invoke(Method.java:511)
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:798)
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:565)
     at dalvik.system.NativeStart.main(Native Method)


问:
How can I select random words from an external file in java processing?
I have this assignment that I have to make a word cloud of the most common words used in an external text file which all words will start from the center and expand/animate to a word cloud... I already made a word counter to determine which words are most often used in the text file, now that I know which words are most often used, how can I select at least 15 random words from the top 50 most used words in the text file?

if that question can be easily answered how can I overlap all the selected words on the canvas?

note: I am very noob at java and processing so a code would help...

here is my code:

```<code>    String[] words;
    IntDict concordance;
    int index = 0;

    void setup() {
      size(500, 500);
      background(0);
      String[] lines = loadStrings("alice_just_text.txt");
      String entireplay = join(lines, " ");
      words = splitTokens(entireplay, ",.?!:-;:()03 ");
      concordance = new IntDict();
      frameRate(5);

      for (int i = 0; i < words.length; i++) {
        concordance.increment(words[i].toLowerCase());
      }
      concordance.sortValuesReverse();

      String[] keys = concordance.keyArray();
      for (int i = 0; i < keys.length; i++) {
        int count = concordance.get(keys[i]); //word counts
        println(keys[i], count);

      }

    }

    void draw() {

      background(0);
      textSize(64);
      textAlign(CENTER);
      text(words[index], width / 2, height / 2);
      index++;

    }
</code>```

答:
Using Java8 Streams you can do that in a really nice way IMO:</p>

```<code>Path file = Paths.get("YOUR_FILE.txt");
Map<String, Integer> wordCounts = new HashMap<>();

// Create a Map of Word -> Count
try (Stream<String> lines = Files.lines(file)) {
    lines.map((line) -> line.split("\\s+")).forEach((words) -> {
        for (String word : words) {
            wordCounts.put(word, wordCounts.getOrDefault(word, 0) + 1);
        }
    });
}

// Process the Map
List<String> top50Words = wordCounts.entrySet().stream()
        .sorted((entry1, entry2) -> -Integer.compare(entry1.getValue(), entry2.getValue()))// Sort by Count (- for Reversed)
        .map(Map.Entry::getKey)// You don't need the Count anymore
        .limit(50L)// Limit to Top 50
        .collect(Collectors.toList());// Collect them as List

Collections.shuffle(top50Words);// Shuffle Top 50

List<String> _15RandomWordsOfTop15 = top50Words.stream()
        .limit(15L)// Limit to the first 15 in the shuffled List
        .collect(Collectors.toList());// Collect as List

System.out.println(_15RandomWordsOfTop15);
</code>```

Body:
I have this assignment that I have to make a word cloud of the most common words used in an external text file which all words will start from the center and expand/animate to a word cloud... I already made a word counter to determine which words are most often used in the text file, now that I know which words are most often used, how can I select at least 15 random words from the top 50 most used words in the text file?

if that question can be easily answered how can I overlap all the selected words on the canvas?

note: I am very noob at java and processing so a code would help...

here is my code:

    String[] words;
    IntDict concordance;
    int index = 0;

    void setup() {
      size(500, 500);
      background(0);
      String[] lines = loadStrings("alice_just_text.txt");
      String entireplay = join(lines, " ");
      words = splitTokens(entireplay, ",.?!:-;:()03 ");
      concordance = new IntDict();
      frameRate(5);

      for (int i = 0; i < words.length; i++) {
        concordance.increment(words[i].toLowerCase());
      }
      concordance.sortValuesReverse();

      String[] keys = concordance.keyArray();
      for (int i = 0; i < keys.length; i++) {
        int count = concordance.get(keys[i]); //word counts
        println(keys[i], count);

      }

    }

    void draw() {

      background(0);
      textSize(64);
      textAlign(CENTER);
      text(words[index], width / 2, height / 2);
      index++;

    }

Body:
Using Java8 Streams you can do that in a really nice way IMO:

Path file = Paths.get("YOUR_FILE.txt");
Map<String, Integer> wordCounts = new HashMap<>();

// Create a Map of Word -> Count
try (Stream<String> lines = Files.lines(file)) {
    lines.map((line) -> line.split("\\s+")).forEach((words) -> {
        for (String word : words) {
            wordCounts.put(word, wordCounts.getOrDefault(word, 0) + 1);
        }
    });
}

// Process the Map
List<String> top50Words = wordCounts.entrySet().stream()
        .sorted((entry1, entry2) -> -Integer.compare(entry1.getValue(), entry2.getValue()))// Sort by Count (- for Reversed)
        .map(Map.Entry::getKey)// You don't need the Count anymore
        .limit(50L)// Limit to Top 50
        .collect(Collectors.toList());// Collect them as List

Collections.shuffle(top50Words);// Shuffle Top 50

List<String> _15RandomWordsOfTop15 = top50Words.stream()
        .limit(15L)// Limit to the first 15 in the shuffled List
        .collect(Collectors.toList());// Collect as List

System.out.println(_15RandomWordsOfTop15);


问:
unable to load a local resource OR virtual path error
Situation

I have two applications that both read and save images / documents to one specific folder. Example if the user uploads their image in one program, a user of program B is supposed to view and even edit that image.

What I have done

In one of my application I have created a setting in settings for the string of my path. So to save an image path I call

```<code> path = System.IO.Path.Combine(Properties.Settings.Default.imagePath, Fimage);
</code>```

this works fine.
However, my issue is when I try to view the image in my edit view.

Controller

```<code> ViewBag.imagePath =   Properties.Settings.Default.imagePath;
</code>```

View

```<code> <img src="@ViewBag.imagePath/@Url.Content(@Model.image)" alt="Image" style="height: 255px;  " />
</code>```

Problem

The problem is upon attempting to view the image I get the error, Not allowed to load local resource: I have full access to the folder and when I attempt to browse to the file in the error message the picture is displayed. I was advised from other questions to use, server.MapPath however when I do  Server.MapPath(Properties.Settings.Default.imagePath); I get the error physical path received, expected virtual path.

This viewbag holds the entire string of folder my files are stored with the EVERYONE user having full access. So i'm really unsure of why it's making a fuse.

P.S I cant say something like "~/content/images" because the path to that file is in an entirely different application, I think I need to give it the entire location.

Any assistance will be appreciated.

Gratitude

答:
Looks like your defaultImage variable holds a physical path, which will work for saving the image since the API requires a path in the form e.g. c:\website\images\.... but for viewing, you need the VirtualPath, something of the form http://mycoolsite/images/image.jpg and this is what the error is telling you.

Your Controller; therefore, should return something like

```<code>ViewBag.imagePath = Properties.Settings.Default.imagePath.Replace(Request.ServerVariables["APPL_PHYSICAL_PATH"], String.Empty);
</code>```

In order to get the Relative Path. See this other related question.

EDIT I just saw your "PS..."

If that's the case, then you need to pass the full URL to the other application: (e.g. http://someothersite.com/images/image.jpg).

Body:
Situation

I have two applications that both read and save images / documents to one specific folder. Example if the user uploads their image in one program, a user of program B is supposed to view and even edit that image.

What I have done

In one of my application I have created a setting in settings for the string of my path. So to save an image path I call

 path = System.IO.Path.Combine(Properties.Settings.Default.imagePath, Fimage);

this works fine.
However, my issue is when I try to view the image in my edit view.

Controller

 ViewBag.imagePath =   Properties.Settings.Default.imagePath;

View

Problem

The problem is upon attempting to view the image I get the error, Not allowed to load local resource: I have full access to the folder and when I attempt to browse to the file in the error message the picture is displayed. I was advised from other questions to use, server.MapPath however when I do  Server.MapPath(Properties.Settings.Default.imagePath); I get the error physical path received, expected virtual path.

This viewbag holds the entire string of folder my files are stored with the EVERYONE user having full access. So i'm really unsure of why it's making a fuse.

P.S I cant say something like "~/content/images" because the path to that file is in an entirely different application, I think I need to give it the entire location.

Any assistance will be appreciated.

Gratitude

Body:
Looks like your defaultImage variable holds a physical path, which will work for saving the image since the API requires a path in the form e.g. c:\website\images\.... but for viewing, you need the VirtualPath, something of the form http://mycoolsite/images/image.jpg and this is what the error is telling you.

Your Controller; therefore, should return something like

ViewBag.imagePath = Properties.Settings.Default.imagePath.Replace(Request.ServerVariables["APPL_PHYSICAL_PATH"], String.Empty);

In order to get the Relative Path. See this other related question.

EDIT I just saw your "PS..."

If that's the case, then you need to pass the full URL to the other application: (e.g. http://someothersite.com/images/image.jpg).


问:
JSONiq: Java implementation as library?
Looking at the implementation of the JSONiq specification (www.jsoniq.org).

Most of them are standalone deployment. e.g. Zorba, VXQuery, etc and are designed to query JSON based databases or process large JSON documents.

I am surprised to find all implementations are trying to solve such problem without modularizing the JSONiq execution as library. It should have been much like Apache Lucene(library) to Apache Solr(Search Server+Rest API) and other indexing solution.

Is there a java library available (similar to Saxon for XQuery), which can be embeded into java apps and can execute the JSONiq specs defined as functions in .xq or .xquery files ?
Or How can Saxon be extended to parse and execute the JSONiq specification ?

答: JSONiq is an XQuery-like language for processing JSON. Most of its good ideas were incorporated into XQuery 3.1, but in a way that integrated the XML and JSON data models. I don't believe JSONiq offers any functionality that's not in XQuery 3.1, and it's not an open standard, so there would be little point in implementing it in Saxon.</p>

Title: JSONiq: Java implementation as library?


问:
How does platypus "guess" bold and italic styles?
Here's my code. My first function is based on the /Lib/site-packages/reportlab/lib/styles.py source code, to create an array of style:

```<code>def create_styles(p_tuples):
    retour = StyleSheet1()
    parent = None
    for p_name, font_name, font in p_tuples:
        # (!) change path if Linux:
        ttf_file = "C:/Windows/Fonts/{}.ttf".format(font)
        pdfmetrics.registerFont(TTFont(font_name, ttf_file))
        if parent is None:
            p = ParagraphStyle(name=p_name,
                               fontName=font_name,
                               fontSize=10,
                               leading=12)
            retour.add(p)
            parent = p
        else:
            retour.add(ParagraphStyle(name=p_name,
                                      parent=parent,
                                      fontName=font_name,
                                      fontSize=10,
                                      leading=12))
    return retour
</code>```

Then I build my own array with my installed fonts:

```<code>def render_to_response(self, context, **response_kwargs):
    # this is a response for Django, but the question is about styles
    response = HttpResponse(content_type='application/pdf; charset=utf-8')
    # ! Hint : no filename -> the browser extracts it from the URL!
    #   -> create URLs like http://pdfreportlab.com/extract/myfilename.pdf
    #   this is the way to go to have 100% working UTF-8 filenames!
    response['Content-Disposition'] = 'attachment; filename=""'

    my_styles = self.create_styles([
        ('ms-regular', 'montserrat-regular',
         'Montserrat-Regular'),
        ('ms-black', 'montserrat-black',
         'Montserrat-Black'),
        ('ms-black-italic', 'montserrat-black-italic',
         'Montserrat-BlackItalic'),
        ('ms-bold', 'montserrat-bold',
         'Montserrat-Bold'),
        ('ms-bold-italic', 'montserrat-bold-italic',
         'Montserrat-BoldItalic'),
    ])
    doc = SimpleDocTemplate(response)
    elements = []
    c = canvas.Canvas(response, pagesize=A4, )
    for idx in my_styles.byName:
        p = Paragraph("Hello World <i>italic</i> <b>bold</b>",
                      style=my_styles[idx])
        width, height = p.wrapOn(c, A4[0], A4[1])
        elements.append(p)
    doc.build(elements)
    return response
</code>```

Everything is working except the (very annoying) fact that the  and  tags are ignored! It only uses the current font in the style.

How could you modify my code so that it takes in account the tags and I finally get styles with the tags in the text itself?

答:
You need to register a font family if you want Platypus to auto-select fonts - you're creating a different style for every font variant so of course the  and  tags have no effect - it doesn't know what fonts to use for them as the passed style references a single font.

Here's how to build a style using a font family:

```<code>from reportlab.lib.styles import ParagraphStyle
from reportlab.pdfbase.pdfmetrics import registerFont, registerFontFamily
from reportlab.pdfbase.ttfonts import TTFont

def create_paragraph_style(name, font_name, **kwargs):
    ttf_path = "C:/Windows/Fonts/{}.ttf"
    family_args = {}  # store arguments for the font family creation
    for font_type in ("normal", "bold", "italic", "boldItalic"):  # recognized font variants
        if font_type in kwargs:  # if this type was passed...
            font_variant = "{}-{}".format(font_name, font_type)  # create font variant name
            registerFont(TTFont(font_variant, ttf_path.format(kwargs[font_type])))
            family_args[font_type] = font_variant  # add it to font family arguments
    registerFontFamily(font_name, **family_args)  # register a font family
    return ParagraphStyle(name=name, fontName=font_name, fontSize=10, leading=12)
</code>```

Then you can create your paragraph style as:

```<code>pstyle = create_paragraph_style("ms", "montserrat",
                                normal="Montserrat-Regular",
                                bold="Montserrat-Bold",
                                boldItalic="Montserrat-BoldItalic")
</code>```

assuming, of course, that you have TTF files with those names in your fonts directory.

You can then add it to your stylesheet (especially if you want parent inheritance - make sure you add it as an argument to be forwarded to the ParagraphStyle creation) or directly use it as:

```<code>p = Paragraph("Hello World <i>italic</i> <b>bold</b> <b><i>boldItalic</i></b>", style=pstyle)
</code>```

(the standalone italic won't be affected as we didn't define it in the family, tho).

Body:
Here's my code. My first function is based on the /Lib/site-packages/reportlab/lib/styles.py source code, to create an array of style:

def create_styles(p_tuples):
    retour = StyleSheet1()
    parent = None
    for p_name, font_name, font in p_tuples:
        # (!) change path if Linux:
        ttf_file = "C:/Windows/Fonts/{}.ttf".format(font)
        pdfmetrics.registerFont(TTFont(font_name, ttf_file))
        if parent is None:
            p = ParagraphStyle(name=p_name,
                               fontName=font_name,
                               fontSize=10,
                               leading=12)
            retour.add(p)
            parent = p
        else:
            retour.add(ParagraphStyle(name=p_name,
                                      parent=parent,
                                      fontName=font_name,
                                      fontSize=10,
                                      leading=12))
    return retour

Then I build my own array with my installed fonts:

def render_to_response(self, context, **response_kwargs):
    # this is a response for Django, but the question is about styles
    response = HttpResponse(content_type='application/pdf; charset=utf-8')
    # ! Hint : no filename -> the browser extracts it from the URL!
    #   -> create URLs like http://pdfreportlab.com/extract/myfilename.pdf
    #   this is the way to go to have 100% working UTF-8 filenames!
    response['Content-Disposition'] = 'attachment; filename=""'

    my_styles = self.create_styles([
        ('ms-regular', 'montserrat-regular',
         'Montserrat-Regular'),
        ('ms-black', 'montserrat-black',
         'Montserrat-Black'),
        ('ms-black-italic', 'montserrat-black-italic',
         'Montserrat-BlackItalic'),
        ('ms-bold', 'montserrat-bold',
         'Montserrat-Bold'),
        ('ms-bold-italic', 'montserrat-bold-italic',
         'Montserrat-BoldItalic'),
    ])
    doc = SimpleDocTemplate(response)
    elements = []
    c = canvas.Canvas(response, pagesize=A4, )
    for idx in my_styles.byName:
        p = Paragraph("Hello World italic bold",
                      style=my_styles[idx])
        width, height = p.wrapOn(c, A4[0], A4[1])
        elements.append(p)
    doc.build(elements)
    return response

Everything is working except the (very annoying) fact that the  and  tags are ignored! It only uses the current font in the style.

How could you modify my code so that it takes in account the tags and I finally get styles with the tags in the text itself?

Body:
You need to register a font family if you want Platypus to auto-select fonts - you're creating a different style for every font variant so of course the <i> and <b> tags have no effect - it doesn't know what fonts to use for them as the passed style references a single font.

Here's how to build a style using a font family:

from reportlab.lib.styles import ParagraphStyle
from reportlab.pdfbase.pdfmetrics import registerFont, registerFontFamily
from reportlab.pdfbase.ttfonts import TTFont

def create_paragraph_style(name, font_name, **kwargs):
    ttf_path = "C:/Windows/Fonts/{}.ttf"
    family_args = {}  # store arguments for the font family creation
    for font_type in ("normal", "bold", "italic", "boldItalic"):  # recognized font variants
        if font_type in kwargs:  # if this type was passed...
            font_variant = "{}-{}".format(font_name, font_type)  # create font variant name
            registerFont(TTFont(font_variant, ttf_path.format(kwargs[font_type])))
            family_args[font_type] = font_variant  # add it to font family arguments
    registerFontFamily(font_name, **family_args)  # register a font family
    return ParagraphStyle(name=name, fontName=font_name, fontSize=10, leading=12)

Then you can create your paragraph style as:

pstyle = create_paragraph_style("ms", "montserrat",
                                normal="Montserrat-Regular",
                                bold="Montserrat-Bold",
                                boldItalic="Montserrat-BoldItalic")

assuming, of course, that you have TTF files with those names in your fonts directory.

You can then add it to your stylesheet (especially if you want parent inheritance - make sure you add it as an argument to be forwarded to the ParagraphStyle creation) or directly use it as:

p = Paragraph("Hello World <i>italic</i> <b>bold</b> <b><i>boldItalic</i></b>", style=pstyle)

(the standalone italic won't be affected as we didn't define it in the family, tho).


问:
How do I filter the dates of the current week from a general date list in Javascript or Typescript?
I have an array that contains multiple Dates and, from this array, I want to return an array that contains only the Dates that belong to the current week. How can I do this?</p>

答:
Here's an example using filter.

```<code>let outOfWeek = new Date();
outOfWeek.setDate(outOfWeek.getDate() + 7)

const dateList = [
  new Date(),
  outOfWeek
]
const monthDay = new Date().getDate();
const weekDay = new Date().getDay();
const daysToSunday = 7 - weekDay;
const daysFromSunday = weekDay;

const setDateToMidnight = (date) =>{
  date.setHours(0);
  date.setMinutes(0);
  date.setSeconds(0);
  date.setMilliseconds(0);
}

let maxDate = new Date();
maxDate.setDate(monthDay + daysToSunday);
setDateToMidnight(maxDate);

let minDate = new Date();
minDate.setDate(monthDay - daysFromSunday);
setDateToMidnight(minDate);

filteredDates = dateList.filter((date) => {
  if (date.getTime() < maxDate.getTime() && date.getTime() >= minDate.getTime()) {
    return true;
  } else {
    return false;
  }
})

console.log(dateList);
console.log(filteredDates);
</code>```

https://jsfiddle.net/qorb6ruL/5/

Body:
Here's an example using filter.

let outOfWeek = new Date();
outOfWeek.setDate(outOfWeek.getDate() + 7)

const dateList = [
  new Date(),
  outOfWeek
]
const monthDay = new Date().getDate();
const weekDay = new Date().getDay();
const daysToSunday = 7 - weekDay;
const daysFromSunday = weekDay;

const setDateToMidnight = (date) =>{
  date.setHours(0);
  date.setMinutes(0);
  date.setSeconds(0);
  date.setMilliseconds(0);
}

let maxDate = new Date();
maxDate.setDate(monthDay + daysToSunday);
setDateToMidnight(maxDate);

let minDate = new Date();
minDate.setDate(monthDay - daysFromSunday);
setDateToMidnight(minDate);

filteredDates = dateList.filter((date) => {
  if (date.getTime() < maxDate.getTime() && date.getTime() >= minDate.getTime()) {
    return true;
  } else {
    return false;
  }
})

console.log(dateList);
console.log(filteredDates);

https://jsfiddle.net/qorb6ruL/5/


问:
What is the correct "Document Name" of an Access ADP/MDB to use in the GetObject("Document Name") call?
According to http://support.microsoft.com/kb/288902/en-us

You can attach to a specific instance
if you know the name of an open
document in that instance. For
example, if an instance of Excel is
running with an open workbook named
Book2, the following code attaches
successfully to that instance even if
it is not the earliest instance that
was launched:

```<code>Set xlApp = GetObject("Book2").Application
</code>```

Th example works for Excel, mainly because the "Document Name" is nearly the same as the filename. I need to get this to work for Access.

I have users running multiple instances of different Access Applications (.ADP) and I need to get one with a specific name. I do NOT know the complete filepath, otherwise I could do a simple

```<code>Set app = GetObject("c:\my\app\myapp.adp", "Access.Application")
</code>```

Currently, I go with calling

```<code>Set app = GetObject(, "Access.Application")
</code>```

and check the returned Application.Name. If it's good, I use it to call some functions on it, if not it fails. I have heard about the Running Objects Table, but since I have to get the object inside a VBScript, it's a bit too much API-calls.

Bottom Line:
What is the correct "Document Name" of an Access ADP to use in the GetObject("Document Name") call and what type of object does it return?

答:
Coming back to this question because @phoog posted an answer, it occurs to me that since Access can have only one database open at a time, you'd need to look at each instance of Access and check its CurrentDB.Name. Now, with an ADP, I don't know what you'd check instead, but perhaps it's CurrentProject.Path.

I don't believe any of that actually addresses the original question, which seems to want to find the instance with just the filename, but I don't think that even if that worked it would be a good idea. You could easily have independent Access apps that return the same application name and filename but are stored in different locations in the file system.

Body:
According to http://support.microsoft.com/kb/288902/en-us

You can attach to a specific instance
if you know the name of an open
document in that instance. For
example, if an instance of Excel is
running with an open workbook named
Book2, the following code attaches
successfully to that instance even if
it is not the earliest instance that
was launched:

Set xlApp = GetObject("Book2").Application

Th example works for Excel, mainly because the "Document Name" is nearly the same as the filename. I need to get this to work for Access.

I have users running multiple instances of different Access Applications (.ADP) and I need to get one with a specific name. I do NOT know the complete filepath, otherwise I could do a simple

Set app = GetObject("c:\my\app\myapp.adp", "Access.Application")

Currently, I go with calling

Set app = GetObject(, "Access.Application")

and check the returned Application.Name. If it's good, I use it to call some functions on it, if not it fails. I have heard about the Running Objects Table, but since I have to get the object inside a VBScript, it's a bit too much API-calls.

Bottom Line:
What is the correct "Document Name" of an Access ADP to use in the GetObject("Document Name") call and what type of object does it return?


问:
Message "the term 'ng' is not recognized as the name of a cmdlet"
Today, while working through some basic AngularJS introduction, I ran into a problem.

I opened PowerShell to get going on the project. NPM worked.

I was able to install Angular using:

```<code>npm install -g @angular/cli
</code>```

Anytime I tried to run ng, I would get:

the term 'ng' is not recognized as the name of a cmdlet

答:
The first path in the path variable needs to be the NPM path. Opening the Node.js command prompt I found that the ng command worked there. I dug into the shortcut and found that it references a command to ensure the first Path variable is NPM.
To Fix:

Right Clicked on My Computer (windows)

Selected Advanced System Settings

Clicked "Environment Variables"

Under "Path" variable, made the FIRST value listed %AppData%\npm

Once I did that I was able to close powershell and reopen and all worked.

ContentLicense: CC BY-SA 4.0

Body:
Today, while working through some basic AngularJS introduction, I ran into a problem.

I opened PowerShell to get going on the project. NPM worked.

I was able to install Angular using:

npm install -g @angular/cli

Anytime I tried to run ng, I would get:

the term 'ng' is not recognized as the name of a cmdlet


问:
How to maniputlate the size of margins in RTF file
I have made a program that takes in an RTF document, sorts it, and then outputs another RTF doc. I have this print statement and I need to manipulate the marigins to make them smaller. I have tried a couple things without success.

```<code>                if ($_ =~ "ERROR"){
                $rtf->prolog(
                'title' => "Color Test",
                'colors' => [
                undef,
                [0,0,0],     # 1 - black
                [255,0,0],   # 2-red
                [0,255,0],   # 3-green
                [0,0,255],   # 4-blue
                [255,128,0], # 5-orange
                [255,255,0], # 6-yellow
                ],
                );
        #PRINT ERRORS IN RED
                $rtf->printf( \'{\fs20\lang1036\noproof\cf2\highlight1  %s} \par ', "$_");

        }
</code>```

I read that the command is marglN and margrN but I have not been successful in using these. Any ideas?

答:
In the docs:

```<code>my ( $type, $argument, $param ) = get_token();
</code>```

$type is one of text, control, group, escape or eof.
I'm guessing you're interested in the text tokens.

the entry for text says: $argument contains the actual text.

So I would suggest trying:

```<code>for my $token ( @tokens ){
    my ( $type, $arg ) = @$token;
    next unless $type eq 'text';
    print "$arg\n";
}
</code>```

This code is untested.

Body:
I have made a program that takes in an RTF document, sorts it, and then outputs another RTF doc. I have this print statement and I need to manipulate the marigins to make them smaller. I have tried a couple things without success.

                if ($_ =~ "ERROR"){
                $rtf->prolog(
                'title' => "Color Test",
                'colors' => [
                undef,
                [0,0,0],     # 1 - black
                [255,0,0],   # 2-red
                [0,255,0],   # 3-green
                [0,0,255],   # 4-blue
                [255,128,0], # 5-orange
                [255,255,0], # 6-yellow
                ],
                );
        #PRINT ERRORS IN RED
                $rtf->printf( \'{\fs20\lang1036\noproof\cf2\highlight1  %s} \par ', "$_");

        }

I read that the command is marglN and margrN but I have not been successful in using these. Any ideas?

Body:
In the docs:

my ( $type, $argument, $param ) = get_token();

$type is one of text, control, group, escape or eof.
I'm guessing you're interested in the text tokens.

the entry for text says: $argument contains the actual text.

So I would suggest trying:

for my $token ( @tokens ){
    my ( $type, $arg ) = @$token;
    next unless $type eq 'text';
    print "$arg\n";
}

This code is untested.


问:
KendoUI TimePicker
I'm using Kendo UI and the time picker is not showing a value also there is a value.

I'm using ASP MVC 4 and loading passing model data to the view. All the data is there in the model.. but for a reason i cannot explain the actual UI is not showing the time.

Code in HTML-View Binding Model to KendoUI:

```<code>@Html.LabelFor(model => model.StartTime)
                            @(Html.Kendo().TimePickerFor(model => model.StartTime)
                                .Events(e => e.Change("startChange"))
                            )
 @Html.LabelFor(model => model.EndTime)
                        @Html.Kendo().TimePickerFor(model => model.EndTime)
</code>```

JS: For startChange

```<code>function startChange() {
    var startTime = this.value(),
        endPicker = $("#EndTime").data("kendoTimePicker");

    if (startTime) {
        startTime = new Date(startTime);

        endPicker.max(startTime);
        startTime.setMinutes(startTime.getMinutes() + this.options.interval);
        endPicker.min(startTime);
        startTime.setMinutes(startTime.getMinutes() + 450);
        endPicker.value(startTime);
    }
}
</code>```

答:
First you need to select the time value, then it will bind with your model,
then try for this: use the .text() or .val()

```<code>endPicker = $("#EndTime").data("kendoTimePicker").text();
</code>```

Title: KendoUI TimePicker

Body:
I'm using Kendo UI and the time picker is not showing a value also there is a value.

I'm using ASP MVC 4 and loading passing model data to the view. All the data is there in the model.. but for a reason i cannot explain the actual UI is not showing the time.

Code in HTML-View Binding Model to KendoUI:

@Html.LabelFor(model => model.StartTime)
                            @(Html.Kendo().TimePickerFor(model => model.StartTime)
                                .Events(e => e.Change("startChange"))
                            )
 @Html.LabelFor(model => model.EndTime)
                        @Html.Kendo().TimePickerFor(model => model.EndTime)

JS: For startChange

function startChange() {
    var startTime = this.value(),
        endPicker = $("#EndTime").data("kendoTimePicker");

    if (startTime) {
        startTime = new Date(startTime);

        endPicker.max(startTime);
        startTime.setMinutes(startTime.getMinutes() + this.options.interval);
        endPicker.min(startTime);
        startTime.setMinutes(startTime.getMinutes() + 450);
        endPicker.value(startTime);
    }
}

Body:
First you need to select the time value, then it will bind with your model,
then try for this: use the .text() or .val()

endPicker = $("#EndTime").data("kendoTimePicker").text();


问:
list query using if and .split() taking too long Python
Sorry if something along these lines has already been answered.

I am trying to find values in the list that are "after" 2004q2 (where 2004 is the year and 2 is the quarter.) I was looking for members of the list either in a year after 2004 or in 2004 but after quarter 2. To do this I tried the following code:

```<code>get_recession_start() is a separate function that returns '2004q2'
(changed value cause online class question)

def get_recession_start():
        return '2004q4'

two_q_growth =['2000q1', '2000q2', '2000q3', '2000q4', '2001q1', '2001q2', '2001q3',
 '2001q4', '2002q1', '2002q2', '2002q3', '2002q4', '2003q1', '2003q2', '2003q3', '2003q4',
 '2004q1', '2004q2', '2004q3', '2004q4', '2005q1', '2005q2', '2005q3', '2005q4', '2006q1',
 '2006q2', '2006q3', '2006q4', '2007q1', '2007q2', '2007q3', '2007q4', '2008q3', '2009q4',
 '2010q1', '2010q2', '2010q3', '2010q4', '2011q1', '2011q2', '2011q3', '2011q4', '2012q1',
 '2012q2', '2012q3', '2012q4', '2013q1', '2013q2', '2013q3', '2013q4', '2014q1', '2014q2',
 '2014q3', '2014q4', '2015q1', '2015q2', '2015q3', '2015q4', '2016q1', '2016q2']

for year in two_q_growth:
    start_year = get_recession_start().split('q')[0]
    start_q = get_recession_start().split('q')[1]
    if ((year.split('q')[0] > start_year)
        | ((year.split('q')[0] == start_year) &
        (year.split('q')[1] > start_q))):
        recession_end.append(year)
</code>```

This code has been taking forever and a day to run and I am not sure why. (I'm still new to Python and trying to figure out how to optimize things.)

Thanks!

Technically I just need the first value so I am working on writing something with break but I would like to get this faster too

答:
You can clean this up by assigning year.split('q') to a variable instead of calling the split function every time. Try this</p>

```<code>for year in two_q_growth:
    start_year, start_q = get_recession_start().split('q')
    year_split = year.split('q')
    if ((year_split[0] > start_year) or
        ((year_split[0] == start_year) and (year_split[1] > start_q))):
        recession_end.append(year)
</code>```

Body:
Sorry if something along these lines has already been answered.

I am trying to find values in the list that are "after" 2004q2 (where 2004 is the year and 2 is the quarter.) I was looking for members of the list either in a year after 2004 or in 2004 but after quarter 2. To do this I tried the following code:

get_recession_start() is a separate function that returns '2004q2'
(changed value cause online class question)

def get_recession_start():
        return '2004q4'

two_q_growth =['2000q1', '2000q2', '2000q3', '2000q4', '2001q1', '2001q2', '2001q3',
 '2001q4', '2002q1', '2002q2', '2002q3', '2002q4', '2003q1', '2003q2', '2003q3', '2003q4',
 '2004q1', '2004q2', '2004q3', '2004q4', '2005q1', '2005q2', '2005q3', '2005q4', '2006q1',
 '2006q2', '2006q3', '2006q4', '2007q1', '2007q2', '2007q3', '2007q4', '2008q3', '2009q4',
 '2010q1', '2010q2', '2010q3', '2010q4', '2011q1', '2011q2', '2011q3', '2011q4', '2012q1',
 '2012q2', '2012q3', '2012q4', '2013q1', '2013q2', '2013q3', '2013q4', '2014q1', '2014q2',
 '2014q3', '2014q4', '2015q1', '2015q2', '2015q3', '2015q4', '2016q1', '2016q2']

for year in two_q_growth:
    start_year = get_recession_start().split('q')[0]
    start_q = get_recession_start().split('q')[1]
    if ((year.split('q')[0] > start_year)
        | ((year.split('q')[0] == start_year) &
        (year.split('q')[1] > start_q))):
        recession_end.append(year)

This code has been taking forever and a day to run and I am not sure why. (I'm still new to Python and trying to figure out how to optimize things.)

Thanks!

Technically I just need the first value so I am working on writing something with break but I would like to get this faster too

Body:
You can clean this up by assigning year.split('q') to a variable instead of calling the split function every time. Try this

for year in two_q_growth:
    start_year, start_q = get_recession_start().split('q')
    year_split = year.split('q')
    if ((year_split[0] > start_year) or
        ((year_split[0] == start_year) and (year_split[1] > start_q))):
        recession_end.append(year)