问:
Unable to merger the value of 1 column that is in multiple tables
I am having trouble updating a column that is found in multiple tables with this script. I would like to use this to prevent duplicate UnitId's throughout the DB. I keep getting this error messages:

The UPDATE statement conflicted with the FOREIGN KEY constraint
  "Ppt${FA40D62B-B45A-46B2-A5C5-24BA8E5B6318}". The conflict occurred in
  database "MQS-demo", table "dbo.Unit", column 'UnitID'.

and

The DELETE statement conflicted with the REFERENCE constraint
  "Ppt${FA40D62B-B45A-46B2-A5C5-24BA8E5B6318}". The conflict occurred in
  database "MQS-demo", table "dbo.Ppt", column 'UnitID'.

Here is the query

```<code>declare @oldUnitID as int=0;
declare @newUnitID as int=0;
declare @temp as TABLE
(
     bincode nvarchar(200),
     cnt     int
)

insert into @temp
select bincode, Count(*)
from   unit
group  by bincode -- HAVING count(*)=2

--select * from @temp

WHILE (SELECT Count(*) from   @temp) > 0 BEGIN

      DECLARE @bincodetodedup as nvarchar(200);

      select top(1) @bincodetodedup = bcode
      from   @temp;

      DECLARE @unitstodedup as TABLE
      (
           unitid int,
           num    int
      )

      insert into @unitstodedup
      select distinct UnitID, ROW_NUMBER() OVER(ORDER BY unitid) as num
      from   unit
      where  bincode = @bincodetodedup
      order  by unitid

      WHILE (SELECT Count(*) from @unitstodedup) > 0 BEGIN
            SELECT TOP(1) @oldUnitID = Unitid
            from   @unitstodedup
            where  num = 1

            SELECT TOP(1) @newUnitID = Unitid
            from   @unitstodedup
            where  num > 1

            update Compatibility
            set    UnitID = @newUnitID
            where  UnitID = @oldUnitID

            update PriceList
            set    UnitID = @newUnitID
            where  UnitID = @oldUnitID

            update Project
            set    UnitID = @newUnitID
            where  UnitID = @oldUnitID

            update ProjectNum
            set    UnitID = @newUnitID
            where  UnitID = @oldUnitID

            update Rate
            set    UnitID = @newUnitID
            where  UnitID = @oldUnitID

            update Resolve
            set    UnitID = @newUnitID
            where  UnitID = @oldUnitID

            update Services
            set    UnitID = @newUnitID
            where  UnitID = @oldUnitID

            update TrainingDate
            set    UnitID = @newUnitID
            where  UnitID = @oldUnitID

            update Form
            set    UnitID = @newUnitID
            where  UnitID = @oldUnitID

            update Ppt
            set    UnitID = @newUnitID
            where  UnitID = @oldUnitID

            --update Unit set UnitID=@newUnitID where UnitID=@oldUnitID
            update Manager
            set    UnitID = @newUnitID
            where  UnitID = @oldUnitID
      END

      DELETE FROM unit
      where  unitid = @oldUnitID

      DELETE TOP(1) from @unitstodedup

      DELETE TOP(1) from @temp
END
</code>```

答:
Why do not you do the delete at the end with the variables you are assigning?</p>

```<code>    DELETE from @temp where bcode = @bincodetodedup
    DELETE from @unitstodedup where num=1
    DELETE from @unitstodedup where num>1
</code>```

Body:
I am having trouble updating a column that is found in multiple tables with this script. I would like to use this to prevent duplicate UnitId's throughout the DB. I keep getting this error messages:

The UPDATE statement conflicted with the FOREIGN KEY constraint
  "Ppt${FA40D62B-B45A-46B2-A5C5-24BA8E5B6318}". The conflict occurred in
  database "MQS-demo", table "dbo.Unit", column 'UnitID'.

and

The DELETE statement conflicted with the REFERENCE constraint
  "Ppt${FA40D62B-B45A-46B2-A5C5-24BA8E5B6318}". The conflict occurred in
  database "MQS-demo", table "dbo.Ppt", column 'UnitID'.

Here is the query

declare @oldUnitID as int=0;
declare @newUnitID as int=0;
declare @temp as TABLE
(
     bincode nvarchar(200),
     cnt     int
)

insert into @temp
select bincode, Count(*)
from   unit
group  by bincode -- HAVING count(*)=2

--select * from @temp

WHILE (SELECT Count(*) from   @temp) > 0 BEGIN

      DECLARE @bincodetodedup as nvarchar(200);

      select top(1) @bincodetodedup = bcode
      from   @temp;

      DECLARE @unitstodedup as TABLE
      (
           unitid int,
           num    int
      )

      insert into @unitstodedup
      select distinct UnitID, ROW_NUMBER() OVER(ORDER BY unitid) as num
      from   unit
      where  bincode = @bincodetodedup
      order  by unitid

      WHILE (SELECT Count(*) from @unitstodedup) > 0 BEGIN
            SELECT TOP(1) @oldUnitID = Unitid
            from   @unitstodedup
            where  num = 1

            SELECT TOP(1) @newUnitID = Unitid
            from   @unitstodedup
            where  num > 1

            update Compatibility
            set    UnitID = @newUnitID
            where  UnitID = @oldUnitID

            update PriceList
            set    UnitID = @newUnitID
            where  UnitID = @oldUnitID

            update Project
            set    UnitID = @newUnitID
            where  UnitID = @oldUnitID

            update ProjectNum
            set    UnitID = @newUnitID
            where  UnitID = @oldUnitID

            update Rate
            set    UnitID = @newUnitID
            where  UnitID = @oldUnitID

            update Resolve
            set    UnitID = @newUnitID
            where  UnitID = @oldUnitID

            update Services
            set    UnitID = @newUnitID
            where  UnitID = @oldUnitID

            update TrainingDate
            set    UnitID = @newUnitID
            where  UnitID = @oldUnitID

            update Form
            set    UnitID = @newUnitID
            where  UnitID = @oldUnitID

            update Ppt
            set    UnitID = @newUnitID
            where  UnitID = @oldUnitID

            --update Unit set UnitID=@newUnitID where UnitID=@oldUnitID
            update Manager
            set    UnitID = @newUnitID
            where  UnitID = @oldUnitID
      END

      DELETE FROM unit
      where  unitid = @oldUnitID

      DELETE TOP(1) from @unitstodedup

      DELETE TOP(1) from @temp
END

Body:
Why do not you do the delete at the end with the variables you are assigning?

    DELETE from @temp where bcode = @bincodetodedup
    DELETE from @unitstodedup where num=1
    DELETE from @unitstodedup where num>1


来源: stackexchange

问:
Numpy searchsorted descending order
I am trying to understand how to correctly use numpy.searchsorted to find the correct index where to insert an element. When i run the following:

```<code>e = np.array([9,8,7,6])
np.searchsorted(e,5)
</code>```

The output I get is 0, which is wrong as I would expect 4 as the answer. Is searchsorted usable for arrays ordered in descending order? What options do I have if I need to keep the array in descending order? Thanks a lot!

答:
You can search the reversed array, and then reverse the index later:

```<code>e = np.array([9,8,7,6])
e.size - np.searchsorted(e[::-1], 5, side = "right")
# 4
</code>```

Notice the side parameter here needs to be opposite to directly search the original array if you want the result to be consistent.

ContentLicense: CC BY-SA 3.0

Title: Numpy searchsorted descending order

Body:
I am trying to understand how to correctly use numpy.searchsorted to find the correct index where to insert an element. When i run the following:

e = np.array([9,8,7,6])
np.searchsorted(e,5)

The output I get is 0, which is wrong as I would expect 4 as the answer. Is searchsorted usable for arrays ordered in descending order? What options do I have if I need to keep the array in descending order? Thanks a lot!

Body:
You can search the reversed array, and then reverse the index later:

e = np.array([9,8,7,6])
e.size - np.searchsorted(e[::-1], 5, side = "right")
# 4

Notice the side parameter here needs to be opposite to directly search the original array if you want the result to be consistent.


答:
As is described in the documentation:

numpy.searchsorted(a, v, side='left', sorter=None)

Find indices where elements should be inserted to maintain order.

Find the indices into a sorted array a such that, if the corresponding
  elements in v were inserted before the indices, the order of a would
  be preserved.

Parameters:

a : 1-D array_like

Input array. If sorter is None, then it must be sorted in ascending order, otherwise sorter must be an array of indices that
  sort it.

(...)

(formatting added)

So you have to provide an array sorted in ascending order.

Nevertheless it is easy to solve this issue for numerical data: you simply use the negation:

```<code>e = np.array([9,8,7,6])
np.searchsorted(<b>-</b>e,<b>-</b>5)
#               ^  ^</code>```

You can also use the reversed array (for instance for non-numerical data) as is proposed by @Psidom.

Title: Numpy searchsorted descending order

Body:
As is described in the documentation:

numpy.searchsorted(a, v, side='left', sorter=None)

Find indices where elements should be inserted to maintain order.

Find the indices into a sorted array a such that, if the corresponding
  elements in v were inserted before the indices, the order of a would
  be preserved.

Parameters:

a : 1-D array_like

Input array. If sorter is None, then it must be sorted in ascending order, otherwise sorter must be an array of indices that
  sort it.

(...)

(formatting added)

So you have to provide an array sorted in ascending order.

Nevertheless it is easy to solve this issue for numerical data: you simply use the negation:

e = np.array([9,8,7,6])
np.searchsorted(-e,-5)
#               ^  ^

You can also use the reversed array (for instance for non-numerical data) as is proposed by @Psidom.


问:
Process n objects each time by condition
I have next object struct:

```<code>{
1698452536:Object {url: "1", isProcessed: false}
1701673991:Object {url: "2", isProcessed: false}
1717724454:Object {url: "3", isProcessed: false}
1756233961:Object {url: "4", isProcessed: false}
1797093325:Object {url: "5", isProcessed: false}
1857721095:Object {url: "6", isProcessed: false}
2095153396:Object {url: "7", isProcessed: false}
2098466246:Object {url: "8", isProcessed: false}
2131427779:Object {url: "9", isProcessed: false}
89975:Object {url: "10", isProcessed: false}
21591836:Object {url: "11", isProcessed: false}
80794211:Object {url: "12", isProcessed: false}
116460496:Object {url: "13", isProcessed: false}
159798435:Object {url: "14", isProcessed: false}
223366448:Object {url: "15", isProcessed: false}
361352239:Object {url: "16", isProcessed: false}
498790092:Object {url: "17", isProcessed: false}
508072650:Object {url: "18", isProcessed: false}
514973525:Object {url: "19", isProcessed: false}
560440401:Object {url: "20", isProcessed: false}
}
</code>```

I need to process five inner objects each time and only after first five is completed take another five.
Is there is a way to do such implementation?

UPDATE:

I`d tried next code in order to transform object to chunked array, but how to call bulk by bulk async and only after full bulk is succeed take another?

```<code>chunkArray(Object.values(images),5).forEach((array)=>{});
function chunkArray(array, groupsize) {
var sets = [],
    chunks, i = 0;
chunks = array.length / groupsize;

while (i < chunks) {
    sets[i] = array.splice(0, groupsize);
    i++;
}
return sets;
</code>```

}

答:
The following promise-based solution transfers batches of size n = 5 items to your asynchronous callback function and continues as soon as the callback signals completion:

// Process items in batches of size n via callback cb:
function process(items, n, cb, offset = 0) {
  if (offset >= items.length) return;
  new Promise((resolve, reject) => {
    cb(items.slice(offset, offset + n), resolve, reject);
  }).then(() => process(items, n, cb, offset + n));
}

// Example:
let items = [0,1,2,3,4,5,6,7,8,9,10,11,12];

process(items, 5, (batch, resolve) => {
  console.log("processing " + batch);
  setTimeout(resolve, 1000); // Async processig...
});```

In case your asynchronous callback can only handle one item at a time, you might want to create 5 promises and wait till all have resolved before recursing to the next batch.

Body:
I have next object struct:

{
1698452536:Object {url: "1", isProcessed: false}
1701673991:Object {url: "2", isProcessed: false}
1717724454:Object {url: "3", isProcessed: false}
1756233961:Object {url: "4", isProcessed: false}
1797093325:Object {url: "5", isProcessed: false}
1857721095:Object {url: "6", isProcessed: false}
2095153396:Object {url: "7", isProcessed: false}
2098466246:Object {url: "8", isProcessed: false}
2131427779:Object {url: "9", isProcessed: false}
89975:Object {url: "10", isProcessed: false}
21591836:Object {url: "11", isProcessed: false}
80794211:Object {url: "12", isProcessed: false}
116460496:Object {url: "13", isProcessed: false}
159798435:Object {url: "14", isProcessed: false}
223366448:Object {url: "15", isProcessed: false}
361352239:Object {url: "16", isProcessed: false}
498790092:Object {url: "17", isProcessed: false}
508072650:Object {url: "18", isProcessed: false}
514973525:Object {url: "19", isProcessed: false}
560440401:Object {url: "20", isProcessed: false}
}

I need to process five inner objects each time and only after first five is completed take another five.
Is there is a way to do such implementation?

UPDATE:

I`d tried next code in order to transform object to chunked array, but how to call bulk by bulk async and only after full bulk is succeed take another?

chunkArray(Object.values(images),5).forEach((array)=>{});
function chunkArray(array, groupsize) {
var sets = [],
    chunks, i = 0;
chunks = array.length / groupsize;

while (i < chunks) {
    sets[i] = array.splice(0, groupsize);
    i++;
}
return sets;

}

Body:
The following promise-based solution transfers batches of size n = 5 items to your asynchronous callback function and continues as soon as the callback signals completion:

// Process items in batches of size n via callback cb:
function process(items, n, cb, offset = 0) {
  if (offset >= items.length) return;
  new Promise((resolve, reject) => {
    cb(items.slice(offset, offset + n), resolve, reject);
  }).then(() => process(items, n, cb, offset + n));
}

// Example:
let items = [0,1,2,3,4,5,6,7,8,9,10,11,12];

process(items, 5, (batch, resolve) => {
  console.log("processing " + batch);
  setTimeout(resolve, 1000); // Async processig...
});

In case your asynchronous callback can only handle one item at a time, you might want to create 5 promises and wait till all have resolved before recursing to the next batch.


问:
Time series graph does not show a fluid line
I am quite new to r and am trying to perform ARIMA time series forecast. The data I am looking into in electricity load per 15 min. My data looks as follows:

```<code> day month year PTE periode_van periode_tm gemeten_uitwisseling
 1   1    01 2010   1      0 secs   900 secs                 2636
 2   1    01 2010   2    900 secs  1800 secs                 2621
 3   1    01 2010   3   1800 secs  2700 secs                 2617
 4   1    01 2010   4   2700 secs  3600 secs                 2600
 5   1    01 2010   5   3600 secs  4500 secs                 2582
 geplande_import geplande_export                date weekend
 1             719            -284 2010-01-01 00:00:00       0
 2             719            -284 2010-01-01 00:15:00       0
 3             719            -284 2010-01-01 00:30:00       0
 4             719            -284 2010-01-01 00:45:00       0
 5             650            -253 2010-01-01 01:00:00       0
 weekday Month gu_ma
 1       5    01    NA
 2       5    01    NA
 3       5    01    NA
 4       5    01    NA
 5       5    01    NA
</code>```

to create a time series I have used the following code

```<code>library("zoo")
ZOO <- zoo(NLData$gemeten_uitwisseling,
order.by=as.POSIXct(NLData$date, format="%Y-%m-%d %H:%M:%S"))

ZOO <- na.approx(ZOO)
tsNLData <- ts(ZOO)

plot(tsNLData)
</code>```

I have also tried the following

```<code>NLDatats <- ts(NLData$gemeten_uitwisseling, frequency = 96)
</code>```

However when I plot the data I get the following;

How can I solve this?

答:
There doesn't seem to be any problem with your graph, but your data come in 15 minute intervals, and you are plotting 4 years worth of data. So naturally it will look like a dark shaded region because there is no way to show the thousands of data points you have in your series in a single plot.

If you are struggling to handle this much data, you can consider sampling from your data frame before plotting, although this will remove seasonality and autocorrelation from the outcome. That can be helpful if you want to know average values of your outcome over time, but not as helpful to see the seasonal and autocorrelative structure in the data.

See the code below that uses dplyr and ggplot2 to plot some simulated time series that illustrates these issues. It's always best to start with simulated data and then work with your own data.

```<code>require(ggplot2)
require(dplyr)

sim_data <- arima.sim(model=list(ar=.88,order=c(1,0,0)),n=10000,sd=.3)

#Too many points
data_frame(y=as.numeric(sim_data),x=1:10000) %>% ggplot(aes(y=y,x=x)) + geom_line() +
  theme_minimal() + xlab('Time') + ylab('Y_t')

#Sample from data (random sample)
#However, this will remove autocorrelation/seasonality
data_frame(y=as.numeric(sim_data),x=1:10000) %>% sample_n(500) %>%
  ggplot(aes(y=y,x=x)) + geom_line() + theme_minimal() + xlab('Time') + ylab('Y_t')

# Plot a subset, which preserves autocorrelation and seasonality
data_frame(y=as.numeric(sim_data),x=1:10000) %>% slice(1:300) %>%
  ggplot(aes(y=y,x=x)) + geom_line() + theme_minimal() + xlab('Time') + ylab('Y_t')
</code>```

Body:
I am quite new to r and am trying to perform ARIMA time series forecast. The data I am looking into in electricity load per 15 min. My data looks as follows:

 day month year PTE periode_van periode_tm gemeten_uitwisseling
 1   1    01 2010   1      0 secs   900 secs                 2636
 2   1    01 2010   2    900 secs  1800 secs                 2621
 3   1    01 2010   3   1800 secs  2700 secs                 2617
 4   1    01 2010   4   2700 secs  3600 secs                 2600
 5   1    01 2010   5   3600 secs  4500 secs                 2582
 geplande_import geplande_export                date weekend
 1             719            -284 2010-01-01 00:00:00       0
 2             719            -284 2010-01-01 00:15:00       0
 3             719            -284 2010-01-01 00:30:00       0
 4             719            -284 2010-01-01 00:45:00       0
 5             650            -253 2010-01-01 01:00:00       0
 weekday Month gu_ma
 1       5    01    NA
 2       5    01    NA
 3       5    01    NA
 4       5    01    NA
 5       5    01    NA

to create a time series I have used the following code

library("zoo")
ZOO <- zoo(NLData$gemeten_uitwisseling,
order.by=as.POSIXct(NLData$date, format="%Y-%m-%d %H:%M:%S"))

ZOO <- na.approx(ZOO)
tsNLData <- ts(ZOO)

plot(tsNLData)

I have also tried the following

NLDatats <- ts(NLData$gemeten_uitwisseling, frequency = 96)

However when I plot the data I get the following;

How can I solve this?

Body:
There doesn't seem to be any problem with your graph, but your data come in 15 minute intervals, and you are plotting 4 years worth of data. So naturally it will look like a dark shaded region because there is no way to show the thousands of data points you have in your series in a single plot.

If you are struggling to handle this much data, you can consider sampling from your data frame before plotting, although this will remove seasonality and autocorrelation from the outcome. That can be helpful if you want to know average values of your outcome over time, but not as helpful to see the seasonal and autocorrelative structure in the data.

See the code below that uses dplyr and ggplot2 to plot some simulated time series that illustrates these issues. It's always best to start with simulated data and then work with your own data.

require(ggplot2)
require(dplyr)

sim_data <- arima.sim(model=list(ar=.88,order=c(1,0,0)),n=10000,sd=.3)

#Too many points
data_frame(y=as.numeric(sim_data),x=1:10000) %>% ggplot(aes(y=y,x=x)) + geom_line() +
  theme_minimal() + xlab('Time') + ylab('Y_t')

#Sample from data (random sample)
#However, this will remove autocorrelation/seasonality
data_frame(y=as.numeric(sim_data),x=1:10000) %>% sample_n(500) %>%
  ggplot(aes(y=y,x=x)) + geom_line() + theme_minimal() + xlab('Time') + ylab('Y_t')

# Plot a subset, which preserves autocorrelation and seasonality
data_frame(y=as.numeric(sim_data),x=1:10000) %>% slice(1:300) %>%
  ggplot(aes(y=y,x=x)) + geom_line() + theme_minimal() + xlab('Time') + ylab('Y_t')


问:
Hyperlink works - Html Form with a Submit button doesn't
I have a PHP script that pushes the headers to allow a file to download. This script works fine when it called via a hyperlink or through the browser using link. This is how it looks like:

```<code><a href="download.php?file=test.mp3&properFilename=Testing File">Download</a>
</code>```

I want this to be a button (sbumit) instead, so I did this:

```<code><form action="download.php?file=test.mp3&properFilename=Testing File" method="get">
<input type="submit" value="Download Audio" name="download"/>
</form>
</code>```

However, this doesn't work. When I click on it. It initiates the download dialog box but the filename is empty. It shows file name as ".mp3" (without quotes)! That same link via the hyperlink shows the exact file name "Testing File". Why is this?? Here is the PHP snippet concerned:

```<code>$filename = '../'.$_GET['file'];
$properFilename = $_GET['properFilename'].'.mp3';

header("Content-Disposition: attachment; filename=\"".basename($properFilename)."\";" );
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".filesize($filename));
readfile("$filename");
exit();
</code>```

Thank you for any help. This has been driving me mad all day and night!!!

答:
Instead of using <input type='button'> as CMS suggests, you can also use the button element (which is actually the semantic correct one here since your not in a form)

```<code><button onclick="document.location = 'bla.php?f=vars'">Download</button>
</code>```

Even better would be off course be to move the onclick event out of the button into a seperate javascript file.

OwnerDisplayName: Abs

ContentLicense: CC BY-SA 2.5

Body:
I have a PHP script that pushes the headers to allow a file to download. This script works fine when it called via a hyperlink or through the browser using link. This is how it looks like:

Download

I want this to be a button (sbumit) instead, so I did this:

<form action="download.php?file=test.mp3&properFilename=Testing File" method="get">
<input type="submit" value="Download Audio" name="download"/>
</form>

However, this doesn't work. When I click on it. It initiates the download dialog box but the filename is empty. It shows file name as ".mp3" (without quotes)! That same link via the hyperlink shows the exact file name "Testing File". Why is this?? Here is the PHP snippet concerned:

$filename = '../'.$_GET['file'];
$properFilename = $_GET['properFilename'].'.mp3';

header("Content-Disposition: attachment; filename=\"".basename($properFilename)."\";" );
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".filesize($filename));
readfile("$filename");
exit();

Thank you for any help. This has been driving me mad all day and night!!!

Body:
Instead of using <input type='button'> as CMS suggests, you can also use the button element (which is actually the semantic correct one here since your not in a form)

<button onclick="document.location = 'bla.php?f=vars'">Download</button>

Even better would be off course be to move the onclick event out of the button into a seperate javascript file.

OwnerDisplayName: Pim Jager


问:
strcat segmentation fault
The second call to strcat here is generating a segmentation fault, why?

```<code>#include <unistd.h>
#include<stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>

int main (int argc, char * argv[])
{
         char command[250];

         //if(scanf("%199s", command) == 1)

            gets(command);
            puts(command);

         int pipeIntId;

         char whitespaceseparator[2]=" ";

         char pidstring [30];

         int pid= getpid();

         sprintf(pidstring,"%d", pid);

         char * whitespace_and_pid;

         whitespace_and_pid = strcat(whitespaceseparator,pidstring);

         char * command_and_pid;

         command_and_pid=strcat(command,whitespace_and_pid); // here's the problem, I guess

          if((mkfifo("pipe"/*pipeName*/,0666))==-1)
          {
              perror("error creating pipe 1");
          exit(1);
          }

         if((pipeIntId=open("pipe",/*pipeName*/O_WRONLY))==-1)
         {
          perror("error creating pipe 2");
          exit(1);
         }

         int written;

         written=write(pipeIntId,command_and_pid,250); // send the command + the pid

         close(pipeIntId);

    return 0;
}
</code>```

答: Your gets call could have added sufficient characters already to cause undefined behavior at about anytime.</p>

Title: strcat segmentation fault

Body:
The second call to strcat here is generating a segmentation fault, why?

#include <unistd.h>
#include<stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>

int main (int argc, char * argv[])
{
         char command[250];

         //if(scanf("%199s", command) == 1)

            gets(command);
            puts(command);

         int pipeIntId;

         char whitespaceseparator[2]=" ";

         char pidstring [30];

         int pid= getpid();

         sprintf(pidstring,"%d", pid);

         char * whitespace_and_pid;

         whitespace_and_pid = strcat(whitespaceseparator,pidstring);

         char * command_and_pid;

         command_and_pid=strcat(command,whitespace_and_pid); // here's the problem, I guess

          if((mkfifo("pipe"/*pipeName*/,0666))==-1)
          {
              perror("error creating pipe 1");
          exit(1);
          }

         if((pipeIntId=open("pipe",/*pipeName*/O_WRONLY))==-1)
         {
          perror("error creating pipe 2");
          exit(1);
         }

         int written;

         written=write(pipeIntId,command_and_pid,250); // send the command + the pid

         close(pipeIntId);

    return 0;
}


问:
@angular - Defualt/NoPreloading strategy opens blank page, component is not initialized at all
Preloading routes using default route strategy or NoPreloadingStrategy changes the url but do not initialize the component at all (the page is blank).

app.module.ts

```<code>imports: [
    BrowserModule,
    SharedModule,
    CoreModule.forRoot(),
    AppRoutingModule,
  ],
</code>```

app.routing.module.ts

```<code>const appRoutes: Routes = [
  { path: 'cart', canActivate: [CartGuardService], component: CartComponent },
  { path: 'login', loadChildren: './login/login.module#LoginModule' },

  { path: '', redirectTo: '/cart', pathMatch: 'full' },
];

@NgModule({
  imports: [
    RouterModule.forRoot(appRoutes)
  ],
  exports: [
    RouterModule
  ],
  providers: [
  ]
})
export class AppRoutingModule { }
</code>```

login-routing.module.ts

```<code>const routes: Routes = [
    { path: 'login', canActivate: [LoginGuardService], component: LoginComponent }
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule],
  providers: []
})
export class LoginRoutingModule { }
</code>```

in my app.component.html button click navigates to login url using.

```<code>this.router.navigate(['/login'])
</code>```

in login.component.ts neither constructor or ngOnInit is called, have placed console.log in both of them, nothing in console gets printed, the url in the address bar is changed but it opens blank page.

ng --version

```<code>@angular/cli: 1.0.0
node: 6.9.1
os: win32 x64
@angular/common: 4.0.0
@angular/compiler: 4.0.0
@angular/core: 4.0.0
@angular/forms: 4.0.0
@angular/http: 4.0.0
@angular/platform-browser: 4.0.0
@angular/platform-browser-dynamic: 4.0.0
@angular/router: 4.0.0
@angular/animations: 4.0.0
@angular/cli: 1.0.0
@angular/compiler-cli: 4.0.0
</code>```

答:
I think you should check the guards. Am sure the CartGuardService redirects to the login if the user has not login.

If it does successfully navigate to the login then nothing happens then the issue is coming from the LoginGuardService.

Are you not using an observable that doesn't close?

Body:
Preloading routes using default route strategy or NoPreloadingStrategy changes the url but do not initialize the component at all (the page is blank).

app.module.ts

imports: [
    BrowserModule,
    SharedModule,
    CoreModule.forRoot(),
    AppRoutingModule,
  ],

app.routing.module.ts

const appRoutes: Routes = [
  { path: 'cart', canActivate: [CartGuardService], component: CartComponent },
  { path: 'login', loadChildren: './login/login.module#LoginModule' },

  { path: '', redirectTo: '/cart', pathMatch: 'full' },
];

@NgModule({
  imports: [
    RouterModule.forRoot(appRoutes)
  ],
  exports: [
    RouterModule
  ],
  providers: [
  ]
})
export class AppRoutingModule { }

login-routing.module.ts

const routes: Routes = [
    { path: 'login', canActivate: [LoginGuardService], component: LoginComponent }
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule],
  providers: []
})
export class LoginRoutingModule { }

in my app.component.html button click navigates to login url using.

this.router.navigate(['/login'])

in login.component.ts neither constructor or ngOnInit is called, have placed console.log in both of them, nothing in console gets printed, the url in the address bar is changed but it opens blank page.

ng --version

@angular/cli: 1.0.0
node: 6.9.1
os: win32 x64
@angular/common: 4.0.0
@angular/compiler: 4.0.0
@angular/core: 4.0.0
@angular/forms: 4.0.0
@angular/http: 4.0.0
@angular/platform-browser: 4.0.0
@angular/platform-browser-dynamic: 4.0.0
@angular/router: 4.0.0
@angular/animations: 4.0.0
@angular/cli: 1.0.0
@angular/compiler-cli: 4.0.0


问:
F# remove duplicates from a string [] list
I have a program that results in an [] list, and I'm trying to remove near duplicated arrays from the list. An example of the list is...

```<code>[
   [|
      "Jackson";
      "Stentzke";
      "22";
      "001"
    |];
    [|
      "Jackson";
      "Stentzke";
      "22";
      "002"
    |];
    [|
      "Alec";
      "Stentzke";
      "18";
      "003"
    |]
]
</code>```

Basically I'm trying to write a function that would read over the list and remove all examples of near identical data. So the final returned [] list should look like...

```<code>[
    [|
      "Alec";
      "Stentzke";
      "18";
      "003"
    |]
]
</code>```

I've tried a number of functions to try and get this result or something close to it that can work with. My current attempt is this...

```<code>let removeDuplicates (arrayList: string[]list) =
    let list = arrayList|> List.map(fun aL ->
        let a = arrayList|> List.map(fun aL2 ->
                try
                    match (aL.GetValue(0).Equals(aL2.GetValue(0))) && (aL.GetValue(2).Equals(aL2.GetValue(2))) && (aL.GetValue(3).Equals(aL2.GetValue(3))) with
                    | false -> aL2
                    | _ -> [|""|]
                with
                | ex -> [|""|]
            )
        a
                                              )
    list |> List.concat |> List.distinct
</code>```

But all this returns is the a reversed version on the input []list.

Does anyone know how to remove near duplicated arrays from a list?

答:
Using some Linq:

```<code>let comparer (atMost) =
    { new System.Collections.Generic.IEqualityComparer<string[]> with
            member __.Equals(a, b) =
                Seq.zip a b
                    |> Seq.sumBy (fun (a',b') -> System.StringComparer.InvariantCulture.Compare(a', b') |> abs |> min 1)
                    |> ((>=) atMost)
            member __.GetHashCode(a) = 1
    }

System.Linq.Enumerable.GroupBy(data, id, comparer 1)
    |> Seq.choose (fun g -> match Seq.length g with | 1 -> Some g.Key | _ -> None)
</code>```

The comparer allows for atMost : int number of differences between two arrays.

Body:
I have a program that results in an [] list, and I'm trying to remove near duplicated arrays from the list. An example of the list is...

[
   [|
      "Jackson";
      "Stentzke";
      "22";
      "001"
    |];
    [|
      "Jackson";
      "Stentzke";
      "22";
      "002"
    |];
    [|
      "Alec";
      "Stentzke";
      "18";
      "003"
    |]
]

Basically I'm trying to write a function that would read over the list and remove all examples of near identical data. So the final returned [] list should look like...

[
    [|
      "Alec";
      "Stentzke";
      "18";
      "003"
    |]
]

I've tried a number of functions to try and get this result or something close to it that can work with. My current attempt is this...

let removeDuplicates (arrayList: string[]list) =
    let list = arrayList|> List.map(fun aL ->
        let a = arrayList|> List.map(fun aL2 ->
                try
                    match (aL.GetValue(0).Equals(aL2.GetValue(0))) && (aL.GetValue(2).Equals(aL2.GetValue(2))) && (aL.GetValue(3).Equals(aL2.GetValue(3))) with
                    | false -> aL2
                    | _ -> [|""|]
                with
                | ex -> [|""|]
            )
        a
                                              )
    list |> List.concat |> List.distinct

But all this returns is the a reversed version on the input []list.

Does anyone know how to remove near duplicated arrays from a list?

Body:
Using some Linq:

let comparer (atMost) =
    { new System.Collections.Generic.IEqualityComparer<string[]> with
            member __.Equals(a, b) =
                Seq.zip a b
                    |> Seq.sumBy (fun (a',b') -> System.StringComparer.InvariantCulture.Compare(a', b') |> abs |> min 1)
                    |> ((>=) atMost)
            member __.GetHashCode(a) = 1
    }

System.Linq.Enumerable.GroupBy(data, id, comparer 1)
    |> Seq.choose (fun g -> match Seq.length g with | 1 -> Some g.Key | _ -> None)

The comparer allows for atMost : int number of differences between two arrays.


问:
Sending terms instead of iolists to an Erlang driver
Is there an equivalent of driver_output_term in the other direction, i.e. sending an Erlang term to the driver without converting it to an iolist first? If not, I presumably should convert my term using term_to_binary and parse it on the C side with ei; any good examples?

答:
According to the docs, you can only send stuff that's in iodata() format.

If all you want send to the driver is integers and strings, it might be more efficient (and a lot easier) to use your own term-to-iodata encoding, as in this tutorial from the Erlang documentation. They use a function to convert their calls to a mapping that can be sent to the driver directly and therefore doesn't need to be encoded using term_to_binary().

```<code>encode({foo, X}) -> [1, X];
encode({bar, Y}) -> [2, Y].
</code>```

This mapping is feasible if X and Y are assumed to be small integers.
On the C side, the first byte of the input buffer is switched upon to call the appropriate function using the second byte as the argument:

```<code>static void example_drv_output(ErlDrvData handle, char *buff, int bufflen)
{
    example_data* d = (example_data*)handle;
    char fn = buff[0], arg = buff[1], res;
    if (fn == 1) {
        res = foo(arg);
    } else if (fn == 2) {
        res = bar(arg);
    }
    driver_output(d->port, &res, 1);
}
</code>```

Body:
According to the docs, you can only send stuff that's in iodata() format.

If all you want send to the driver is integers and strings, it might be more efficient (and a lot easier) to use your own term-to-iodata encoding, as in this tutorial from the Erlang documentation. They use a function to convert their calls to a mapping that can be sent to the driver directly and therefore doesn't need to be encoded using term_to_binary().

encode({foo, X}) -> [1, X];
encode({bar, Y}) -> [2, Y].

This mapping is feasible if X and Y are assumed to be small integers.
On the C side, the first byte of the input buffer is switched upon to call the appropriate function using the second byte as the argument:

static void example_drv_output(ErlDrvData handle, char *buff, int bufflen)
{
    example_data* d = (example_data*)handle;
    char fn = buff[0], arg = buff[1], res;
    if (fn == 1) {
        res = foo(arg);
    } else if (fn == 2) {
        res = bar(arg);
    }
    driver_output(d->port, &res, 1);
}


问:
Vba: ‘On error’ statement safety
I made a macro that records, then changes the local settings (in my case the decimal separator). At the end of the macro it would restore the settings.

When there is an error I make the program also restore the local settings using the ‘on error’ statement.
(A simplified  example of the program is given below)

So far I got no issues; however, as I am now planning to transfer the program to my working colleagues, I really wish to not interfere with them and overwrite their own local settings.

Does the On error statement is here safe enough to use and make sure that the settings are restored?

Is there any case where the program could run into an error that the On error would fail to redirect to the error handler?

PS: I already know I can convert all my numbers using String = Replace(Number, ",", ".") but for some reasons I cannot afford to go through all the many variables of the macro.

Example Code:

```<code>Private Declare Function GetUserDefaultLCID% Lib "kernel32" ()
Private Declare Function GetLocaleInfoA Lib "kernel32" (ByVal Locale As Long, ByVal LCType As Long, ByVal lpLCData As String, ByVal cchData As Long) As Long
Private Declare Function SetLocaleInfoA Lib "kernel32" (ByVal Locale As Long, ByVal LCType As Long, ByVal lpLCData As String) As Boolean

Sub test()
  ' what to do on error
  On Error GoTo ErrorHandler:
  ' define a number (Your local settings are set up to
  Dim MyNumber As Single
  MyNumber = 0.03
  MsgBox ("Number is 0,03 ->" & MyNumber)
  ' record the settings in the variable LocalSettingsDecimal
  Dim LocalSettingsDecimal As String
  Dim Buffer As String
  Buffer = String(256, 0)
  Dim le As Integer
  le = GetLocaleInfoA(GetUserDefaultLCID(), 14, Buffer, Len(Buffer))
  LocalSettingsDecimal = Left(Buffer, le - 1)

  ' force decimal settings to '.'
  Call SetLocaleInfoA(GetUserDefaultLCID(), 14, ".")

  ' Now is the program body
  MsgBox ("Number is now 0.03 ->" & MyNumber)
  ' an unfortunate error:
  MyNumber = "aa"

  Call SetLocaleInfoA(GetUserDefaultLCID(), 14, LocalSettingsDecimal)
  MsgBox ("Number should be back 0,03 ->" & MyNumber)
  Exit Sub
  ErrorHandler:
  Call SetLocaleInfoA(GetUserDefaultLCID(), 14, LocalSettingsDecimal)
  MsgBox ("There was an error but it's ok, it should be back to 0,03 ->" & MyNumber)
End Sub
</code>```

答:
There are many ways VBA code can get interrupted, some not even involving a clever user that would break on a MsgBox and hit the Stop button: If the host crashes for of something completely unrelated to your code (some KB updates come to mind), in the middle of a procedure's execution, then your error handlers won't be jumped into and there's nothing you can do to prevent that.

Don't tamper with user's local settings. Fix your code instead.

I already know I can convert all my numbers using String = Replace(Number, ",", ".")

Your code is treating numbers as strings, or vice-versa. If the number came from a cell in a worksheet, you can read it into a Double without having to think about what the user's decimal separator is.

```<code>Dim myNumber As Double
With ActiveSheet
    If IsNumeric(.Range("A1").Value) And Not IsError(.Range("A1").Value) Then myNumber = CDbl(.Range("A1").Value)
    'myNumber contains a valid numeric value
End With
</code>```

If the number came from a textbox on a UserForm you crafted, and you allowed the user to enter a comma when your code requires that to be a dot, then you need to fix your data entry code and add some input validation to prevent that. One way to do this is to handle the KeyPress event of the TextBox control that's receiving the user's input - and "swallow" any invalid keys:

```<code>Private Sub txtInput_KeyPress(ByVal keyAscii As MSForms.ReturnInteger)
    If Not IsValidKeyAscii(keyAscii, txtInput.Value) Then keyAscii = 0
End Sub

Private Function IsValidKeyAscii(ByVal keyAscii As Integer, ByVal value As String) As Boolean
'returns true if specified keyAscii is a number, or if it's a dot and value doesn't already contain one
    IsValidKeyAscii = (keyAscii = vbKeyDot And InStr(1, value, Chr$(vbKeyDot)) = 0) Or (keyAscii >= vbKey0 And keyAscii <= vbKey9)
End Function
</code>```

If the number came from an InputBox, you won't be able to prevent the user from entering whatever they want, but you can still validate the input and prevent bad input from being propagated further into your code.

```<code>Private Function PromptForNumber() As Double
    Dim isValid As Boolean
    Dim userInput As String
    Do
        userInput = InputBox("Enter a decimal number:")
        isValid = IsNumeric(userInput) And InStr(userInput, ",") = 0
        If Not isValid Then MsgBox "Value '" & userInput & "' is not numeric. Please make sure to use [en-US] decimal separator."
    While Not isValid
    PromptForNumber = CDbl(userInput)
End Function
</code>```

There's simply no excuse for messing with the user's Control Panel settings.

Title: Vba: ‘On error’ statement safety

Body:
I made a macro that records, then changes the local settings (in my case the decimal separator). At the end of the macro it would restore the settings.

When there is an error I make the program also restore the local settings using the ‘on error’ statement.
(A simplified  example of the program is given below)

So far I got no issues; however, as I am now planning to transfer the program to my working colleagues, I really wish to not interfere with them and overwrite their own local settings.

Does the On error statement is here safe enough to use and make sure that the settings are restored?

Is there any case where the program could run into an error that the On error would fail to redirect to the error handler?

PS: I already know I can convert all my numbers using String = Replace(Number, ",", ".") but for some reasons I cannot afford to go through all the many variables of the macro.

Example Code:

Private Declare Function GetUserDefaultLCID% Lib "kernel32" ()
Private Declare Function GetLocaleInfoA Lib "kernel32" (ByVal Locale As Long, ByVal LCType As Long, ByVal lpLCData As String, ByVal cchData As Long) As Long
Private Declare Function SetLocaleInfoA Lib "kernel32" (ByVal Locale As Long, ByVal LCType As Long, ByVal lpLCData As String) As Boolean

Sub test()
  ' what to do on error
  On Error GoTo ErrorHandler:
  ' define a number (Your local settings are set up to
  Dim MyNumber As Single
  MyNumber = 0.03
  MsgBox ("Number is 0,03 ->" & MyNumber)
  ' record the settings in the variable LocalSettingsDecimal
  Dim LocalSettingsDecimal As String
  Dim Buffer As String
  Buffer = String(256, 0)
  Dim le As Integer
  le = GetLocaleInfoA(GetUserDefaultLCID(), 14, Buffer, Len(Buffer))
  LocalSettingsDecimal = Left(Buffer, le - 1)

  ' force decimal settings to '.'
  Call SetLocaleInfoA(GetUserDefaultLCID(), 14, ".")

  ' Now is the program body
  MsgBox ("Number is now 0.03 ->" & MyNumber)
  ' an unfortunate error:
  MyNumber = "aa"

  Call SetLocaleInfoA(GetUserDefaultLCID(), 14, LocalSettingsDecimal)
  MsgBox ("Number should be back 0,03 ->" & MyNumber)
  Exit Sub
  ErrorHandler:
  Call SetLocaleInfoA(GetUserDefaultLCID(), 14, LocalSettingsDecimal)
  MsgBox ("There was an error but it's ok, it should be back to 0,03 ->" & MyNumber)
End Sub

Body:
There are many ways VBA code can get interrupted, some not even involving a clever user that would break on a MsgBox and hit the Stop button: If the host crashes for of something completely unrelated to your code (some KB updates come to mind), in the middle of a procedure's execution, then your error handlers won't be jumped into and there's nothing you can do to prevent that.

Don't tamper with user's local settings. Fix your code instead.

I already know I can convert all my numbers using String = Replace(Number, ",", ".")

Your code is treating numbers as strings, or vice-versa. If the number came from a cell in a worksheet, you can read it into a Double without having to think about what the user's decimal separator is.

Dim myNumber As Double
With ActiveSheet
    If IsNumeric(.Range("A1").Value) And Not IsError(.Range("A1").Value) Then myNumber = CDbl(.Range("A1").Value)
    'myNumber contains a valid numeric value
End With

If the number came from a textbox on a UserForm you crafted, and you allowed the user to enter a comma when your code requires that to be a dot, then you need to fix your data entry code and add some input validation to prevent that. One way to do this is to handle the KeyPress event of the TextBox control that's receiving the user's input - and "swallow" any invalid keys:

Private Sub txtInput_KeyPress(ByVal keyAscii As MSForms.ReturnInteger)
    If Not IsValidKeyAscii(keyAscii, txtInput.Value) Then keyAscii = 0
End Sub

Private Function IsValidKeyAscii(ByVal keyAscii As Integer, ByVal value As String) As Boolean
'returns true if specified keyAscii is a number, or if it's a dot and value doesn't already contain one
    IsValidKeyAscii = (keyAscii = vbKeyDot And InStr(1, value, Chr$(vbKeyDot)) = 0) Or (keyAscii >= vbKey0 And keyAscii <= vbKey9)
End Function

If the number came from an InputBox, you won't be able to prevent the user from entering whatever they want, but you can still validate the input and prevent bad input from being propagated further into your code.

Private Function PromptForNumber() As Double
    Dim isValid As Boolean
    Dim userInput As String
    Do
        userInput = InputBox("Enter a decimal number:")
        isValid = IsNumeric(userInput) And InStr(userInput, ",") = 0
        If Not isValid Then MsgBox "Value '" & userInput & "' is not numeric. Please make sure to use [en-US] decimal separator."
    While Not isValid
    PromptForNumber = CDbl(userInput)
End Function

There's simply no excuse for messing with the user's Control Panel settings.


问:
How to use "literal string tokens" in Bison
I am learning Flex/Bison. The manual of Bison says:

A literal string token is written like a C string constant; for
  example, "<=" is a literal string token. A literal string token
  doesn’t need to be declared unless you need to specify its semantic
  value data type

But I do not figure how to use it and I do not find an example.

I have the following code for testing:

example.l

```<code>%option noyywrap nodefault

%{
#include "example.tab.h"
%}

%%

[ \t\n] {;}
[0-9] { return NUMBER; }
. { return yytext[0]; }

%%
</code>```

example.y

```<code>%{
#include <stdio.h>
#define YYSTYPE char *
%}

%token NUMBER

%%

start: %empty | start tokens

tokens:
       NUMBER "<=" NUMBER { printf("<="); }
     | NUMBER "=>" NUMBER { printf("=>\n"); }
     | NUMBER '>' NUMBER { printf(">\n"); }
     | NUMBER '<' NUMBER { printf("<\n"); }

%%

main(int argc, char **argv) {
   yyparse();
}

yyerror(char *s) {
   fprintf(stderr, "error: %s\n", s);
}
</code>```

Makefile

```<code>#!/usr/bin/make
# by RAM

all: example

example.tab.c example.tab.h: example.y
    bison -d $<

lex.yy.c: example.l example.tab.h
    flex $<

example: lex.yy.c example.tab.c
    cc -o $@ example.tab.c lex.yy.c -lfl

clean:
    rm -fr example.tab.c example.tab.h lex.yy.c example
</code>```

And when I run it:

```<code>$ ./example
3<4
<
6>9
>
6=>9
error: syntax error
</code>```

Any idea?

UPDATE: I want to clarify that I know alternative ways to solve it, but I want to use literal string tokens.

One Alternative: using multiple "literal character tokens":

```<code>tokens:
       NUMBER '<' '=' NUMBER { printf("<="); }
     | NUMBER '=' '>' NUMBER { printf("=>\n"); }
     | NUMBER '>' NUMBER { printf(">\n"); }
     | NUMBER '<' NUMBER { printf("<\n"); }
</code>```

When I run it:

```<code>$ ./example
3<=9
<=
</code>```

Other alternative:

In example.l:

```<code>"<="  { return LE; }
"=>"  { return GE; }
</code>```

In example.y:

```<code>...
%token NUMBER
%token LE "<="
%token GE "=>"

%%

start: %empty | start tokens

tokens:
       NUMBER "<=" NUMBER { printf("<="); }
     | NUMBER "=>" NUMBER { printf("=>\n"); }
     | NUMBER '>' NUMBER { printf(">\n"); }
     | NUMBER '<' NUMBER { printf("<\n"); }
...
</code>```

When I run it:

```<code>$ ./example
3<=4
<=
</code>```

But the manual says:

A literal string token doesn’t need to be declared unless you need to
  specify its semantic value data type

答:
I havent used flex/bison for a while but two things:

. as far as I remember only matches a single character. yytext is a pointer to a null terminated string char* so yytext[0] is a char which means that you can't match strings this way. You probably need to change it to return yytext. Otherwise . will probably create a token PER character and you'd probably have to write NUMBER '<' '=' NUMBER.

Body:
I am learning Flex/Bison. The manual of Bison says:

A literal string token is written like a C string constant; for
  example, "<=" is a literal string token. A literal string token
  doesn’t need to be declared unless you need to specify its semantic
  value data type

But I do not figure how to use it and I do not find an example.

I have the following code for testing:

example.l

%option noyywrap nodefault

%{
#include "example.tab.h"
%}

%%

[ \t\n] {;}
[0-9] { return NUMBER; }
. { return yytext[0]; }

%%

example.y

%{
#include <stdio.h>
#define YYSTYPE char *
%}

%token NUMBER

%%

start: %empty | start tokens

tokens:
       NUMBER "<=" NUMBER { printf("<="); }
     | NUMBER "=>" NUMBER { printf("=>\n"); }
     | NUMBER '>' NUMBER { printf(">\n"); }
     | NUMBER '<' NUMBER { printf("<\n"); }

%%

main(int argc, char **argv) {
   yyparse();
}

yyerror(char *s) {
   fprintf(stderr, "error: %s\n", s);
}

Makefile

#!/usr/bin/make
# by RAM

all: example

example.tab.c example.tab.h: example.y
    bison -d $<

lex.yy.c: example.l example.tab.h
    flex $<

example: lex.yy.c example.tab.c
    cc -o $@ example.tab.c lex.yy.c -lfl

clean:
    rm -fr example.tab.c example.tab.h lex.yy.c example

And when I run it:

$ ./example
3<4
<
6>9
>
6=>9
error: syntax error

Any idea?

UPDATE: I want to clarify that I know alternative ways to solve it, but I want to use literal string tokens.

One Alternative: using multiple "literal character tokens":

tokens:
       NUMBER '<' '=' NUMBER { printf("<="); }
     | NUMBER '=' '>' NUMBER { printf("=>\n"); }
     | NUMBER '>' NUMBER { printf(">\n"); }
     | NUMBER '<' NUMBER { printf("<\n"); }

When I run it:

$ ./example
3<=9
<=

Other alternative:

In example.l:

"<="  { return LE; }
"=>"  { return GE; }

In example.y:

...
%token NUMBER
%token LE "<="
%token GE "=>"

%%

start: %empty | start tokens

tokens:
       NUMBER "<=" NUMBER { printf("<="); }
     | NUMBER "=>" NUMBER { printf("=>\n"); }
     | NUMBER '>' NUMBER { printf(">\n"); }
     | NUMBER '<' NUMBER { printf("<\n"); }
...

When I run it:

$ ./example
3<=4
<=

But the manual says:

A literal string token doesn’t need to be declared unless you need to
  specify its semantic value data type


问:
Search and replace div content with another div content
I am trying to find a way to replace a DIV that has a few other divs inside with another div that also has a few other divs inside. Tried to do it with a few different programs: Atom, Sublime, Visual Studio Code, PhpStorm but it didn't work.

It could probably be done using regex since the first div starts with
 and ends with

```<code>...id="submitbtn_intakeFormShortAutofillSubmit"/>
    </form>
</div>
                    </div>
</code>```

but my problem is probably the number of tabs, spaces and newlines.

Just to mention, I don't have to make this active on a webpage, but inside hundreds of html pages on my hard drive, so if you can recommend some free software that can do it, it's also good.

答:
You can use the regex

```<code><div class="short-form">[\s\S]*?id="submitbtn_intakeFormShortAutofillSubmit"\/>\s*<\/form>\s*<\/div>\s*<\/div>
</code>```

see it live

Body:
I am trying to find a way to replace a DIV that has a few other divs inside with another div that also has a few other divs inside. Tried to do it with a few different programs: Atom, Sublime, Visual Studio Code, PhpStorm but it didn't work.

It could probably be done using regex since the first div starts with
 and ends with

...id="submitbtn_intakeFormShortAutofillSubmit"/>
    </form>

but my problem is probably the number of tabs, spaces and newlines.

Just to mention, I don't have to make this active on a webpage, but inside hundreds of html pages on my hard drive, so if you can recommend some free software that can do it, it's also good.

Body:
You can use the regex

<div class="short-form">[\s\S]*?id="submitbtn_intakeFormShortAutofillSubmit"\/>\s*<\/form>\s*<\/div>\s*<\/div>

see it live


问:
How to define a function which returns a map
I am attempting to define a function which returns an initialized map:

```<code>package main

import "fmt"
import "os"

func defaults() map {
  m := make(map[string]string)
  m["start"] = "1"
  m["from"]  = "encrypted"
  m["to"]    = "loaded"
  return m
}

func main() {
  args := os.Args[1:]
  fmt.Println(args)
  runvals := defaults()
  fmt.Println(runvals)
}
</code>```

Errors I'm getting:

```<code>Line 6 col 21 error| expected '[', found '{'
Line 7 col 5 error| expected ']', found ':='
Line 11 col 3 error| expected declaration, found 'return'
</code>```

Can someone help me get the syntax right? Or am I trying to do something that Go doesn't do?

答:
```<code>func defaults() map[string] string {
    m := make(map[string]string)
    m["start"] = "1"
    ...
    return m
}
</code>```

The problem with your defaults function is the return type map has no types.

Body:
I am attempting to define a function which returns an initialized map:

package main

import "fmt"
import "os"

func defaults() map {
  m := make(map[string]string)
  m["start"] = "1"
  m["from"]  = "encrypted"
  m["to"]    = "loaded"
  return m
}

func main() {
  args := os.Args[1:]
  fmt.Println(args)
  runvals := defaults()
  fmt.Println(runvals)
}

Errors I'm getting:

Line 6 col 21 error| expected '[', found '{'
Line 7 col 5 error| expected ']', found ':='
Line 11 col 3 error| expected declaration, found 'return'

Can someone help me get the syntax right? Or am I trying to do something that Go doesn't do?

Body:
func defaults() map[string] string {
    m := make(map[string]string)
    m["start"] = "1"
    ...
    return m
}

The problem with your defaults function is the return type map has no types.


问:
Get the current URL
I'm trying to set a variable to the current URL using:

```<code>Dim url As String = HttpContext.Current.Request.url.AbsoluteUri
</code>```

Which is returning:

http://localhost/xxxxx2015/xxxx.asmx/xxxx

This seems to be the file name followed by the web function name.

What it's supposed to return/what it's displaying in IE is:

http://localhost/xxxxx2015/Default.aspx?form=xxxx

Why is this?

答:
You are apparently in a WebRequest, so the current request is the request for that method. However, it is sent from some page, so possibly a "referrer" is set with the URL you are looking for.

See Getting the HTTP Referrer in ASP.NET for more details on how to get it. Basically: use Request.UrlReferrer

Title: Get the current URL

Body:
I'm trying to set a variable to the current URL using:

Dim url As String = HttpContext.Current.Request.url.AbsoluteUri

Which is returning:

http://localhost/xxxxx2015/xxxx.asmx/xxxx

This seems to be the file name followed by the web function name.

What it's supposed to return/what it's displaying in IE is:

http://localhost/xxxxx2015/Default.aspx?form=xxxx

Why is this?


问:
How to make RecyclerView stops recycling defined positions?
My problem is: I have a video streaming happening on one of the views inside the RecyclerView.

When the user scrolls, the view gets recycled and other cameras starts their own streaming on that recycled viewholder. This is bad for user interface since the streaming process takes some seconds to start.

How can I say to the RecyclerView: "Hey Recycler, please, do not recycle that exact position x and give that position ALWAYS the same viewholder you gave it the first time, instead of random one"?

Please someone help me =(

答:
Perform viewHolder.setIsRecyclable(false) on the ViewHolder you want not to be recycled.

From docs of ViewHolder#setIsRecyclable(boolean):

Informs the recycler whether this item can be recycled. Views which are not recyclable will not be reused for other items until setIsRecyclable() is later set to true.

This will cause only one ViewHolder to be created.

```<code>public class MyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    ...
    @Override
    public void onViewAttachedToWindow(final RecyclerView.ViewHolder holder) {
        if (holder instanceof VideoViewHolder) {
            holder.setIsRecyclable(false);
        }
        super.onViewAttachedToWindow(holder);
    }

    @Override
    public void onViewDetachedFromWindow(final RecyclerView.ViewHolder holder) {
        if (holder instanceof VideoViewHolder){
            holder.setIsRecyclable(true);
        }
        super.onViewDetachedFromWindow(holder);
    }
    ...
}
</code>```

Body:
Perform viewHolder.setIsRecyclable(false) on the ViewHolder you want not to be recycled.

From docs of ViewHolder#setIsRecyclable(boolean):

Informs the recycler whether this item can be recycled. Views which are not recyclable will not be reused for other items until setIsRecyclable() is later set to true.

This will cause only one ViewHolder to be created.

public class MyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    ...
    @Override
    public void onViewAttachedToWindow(final RecyclerView.ViewHolder holder) {
        if (holder instanceof VideoViewHolder) {
            holder.setIsRecyclable(false);
        }
        super.onViewAttachedToWindow(holder);
    }

    @Override
    public void onViewDetachedFromWindow(final RecyclerView.ViewHolder holder) {
        if (holder instanceof VideoViewHolder){
            holder.setIsRecyclable(true);
        }
        super.onViewDetachedFromWindow(holder);
    }
    ...
}


问:
Keep count down after closing app
Good morning guys, please I'm building an application to run tasks every hour, and I want to show countdown. But when I left the app and came back, the count restarts.

Can someone help me ?

答:
read the Data Storage developer guide.

you can save data in sharedpreperence
read the data
and set data to timer in Resume

Title: Keep count down after closing app


问:
Show fallback message when a video format cannot be played on browser
I am using video tag as below,

```<code><div>
    <video ng-src="{{item.videoPath}}" type="video/mp4">
        <!--Below message will be visible when audio tag is not supported by browser-->
        <table>
            <tr>
                <td class="break-word">
                    <div data-ng-bind="::'NOT_SUPPORTED_MSG' | translate"></div>
                </td>
            </tr>
        </table>
    </video>
</div>
</code>```

For my mp4 videos, the server returns, Content-Type:"video/mp4" and they get rendered properly.

However, for avi videos, the server returns Content-Type:"application/octet-stream".

And on firefox console, I see below error:

```<code>HTTP "Content-Type" of "application/octet-stream" is not supported.
Load of media resource failed.

Cannot play media. No decoders for requested formats: application/octet-stream
</code>```

Since I already added a fallback message, I'm not sure why I'm not able see it when browser can't render the avi video. I just want to show the fallback message when some video can't be played.

P.S. At this point of project, the content-type my server returning is ok.

答:
Use canPlayType, its a method of the HTML5 media (video/audio) object:
https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/canPlayType</p>

Body:
I am using video tag as below,

    <video ng-src="{{item.videoPath}}" type="video/mp4">

    </video>

For my mp4 videos, the server returns, Content-Type:"video/mp4" and they get rendered properly.

However, for avi videos, the server returns Content-Type:"application/octet-stream".

And on firefox console, I see below error:

HTTP "Content-Type" of "application/octet-stream" is not supported.
Load of media resource failed.

Cannot play media. No decoders for requested formats: application/octet-stream

Since I already added a fallback message, I'm not sure why I'm not able see it when browser can't render the avi video. I just want to show the fallback message when some video can't be played.

P.S. At this point of project, the content-type my server returning is ok.


问:
jquery - find center part of image you are looking at on the screen
I am trying to add a graphic indicator on top of an image that I am looking at. I would basically put the DIV containing object with higher z-index on top of image I am looking at. The main image can be ANY SIZE.

So any ideas on how when I click "Add indicator", the indicator graphic would always be popped into view on top of the main image container (and not outside it) and viewable by me?

Another case is if image is very high (like 3000px height, it would require scrolling). So I might be viewing the bottom part of the image.

Any suggestions welcomed!

答:
It should be very easy to do

1) Get the offset of the image you want

http://api.jquery.com/offset/

it provides you the top and left property's then use that position your div

make the div absolute position and give a better z-index.

Regarding the scroll problem use , document height and calculate the remaining space, based on that you can position your call out.

There are lot of plugins already availabe like tooltips, call outs etc, search in google also


问:
Cut String at Special Position VBA
I got this string here: \server\Documents\test\\954076
how i check if there is a \ a second time and how i cut it then off?
So that \server\Documents\test\\954076 is gonna be \server\Documents\test\954076</p>

答:
Here's a general solution to reduce any consecutive repetitions of a given character:

```<code>Sub RemoveRepetitions(s As String, c As String)
    Dim len1 As Long, len2 As Long
    Do
        len1 = Len(s)
        s = Replace(s, c & c, c)
        len2 = Len(s)
    Loop Until len2 = len1
End Sub

Sub testing()
    Dim s As String: s = "\\server\\\\\\Documents\\\\\test\\954076"
    RemoveRepetitions s, "\"
    Debug.Print s
End Sub
</code>```

\server\Documents\test\954076

Title: Cut String at Special Position VBA

Body:
Here's a general solution to reduce any consecutive repetitions of a given character:

Sub RemoveRepetitions(s As String, c As String)
    Dim len1 As Long, len2 As Long
    Do
        len1 = Len(s)
        s = Replace(s, c & c, c)
        len2 = Len(s)
    Loop Until len2 = len1
End Sub

Sub testing()
    Dim s As String: s = "\\server\\\\\\Documents\\\\\test\\954076"
    RemoveRepetitions s, "\"
    Debug.Print s
End Sub

\server\Documents\test\954076


问:
Microsoft Azure DocumentDB vs Azure Table Storage
For several recent years, Microsoft offers a "NoSQL" key/value storage, called "Table Storage" (http://azure.microsoft.com/en-us/documentation/articles/storage-dotnet-how-to-use-tables/)

Table Storage offers a high performance, scalability (via partitioning) and relatively low cost. A primary drawback of Tables that only Partition and Row keys can be indexed - so making queries on values is very inefficient.

Recently Microsoft announced a new "NoSQL" service, called "DocumentDB" (http://azure.microsoft.com/en-us/documentation/services/documentdb/)

Instead of storing a list of properties (like Tables do), DocumentDB stores JSON objects. The whole object being indexed - so efficient queries may be created based on every property and any nested property of stored objects.

Microsoft says that DocumentDB provides high performance and scalability as well.

If that's so - why anyone would use Table Storage over DocumentDB? It sounds like DocumentDB provides the same functionality as Tables, but with additional capabilities such as the ability to index anything.

I will glad if someone could make a comparison between DocumentDB and Table Storage, highlighting cons and pros of each one.

答:
I think that the comparison is all about trading price for performance. Table Services are just Storage Services, which seem to cap out at 20,000 ops/second, but paying for that kind of throughput all the time (because Storage gives it to us all the time) is $1,200/month. Crazy money.

Table services have simple indexes, so queries are very limited. Good for anything that is written and read via IDs. DocumentDB indexes the entire document, so a query can be done on any property.

And lastly, Table services are bound by the storage constraint of the Storage account it's on (which could get crazy high given negotiation with Microsoft directly), where DocumentDB storage seems unlimited.

So it's a balance. Do you have a LOT of data (hundreds of gigs, or terabytes) that you need in one place? DocumentDB. Do you need to support complex queries? DocumentDB. Do you have data that needs to come and go fast, but based on a 1-to-2 property lookup? Table services. Would you trade having to code around a simple index in order to avoid paying through the nose for throughput? Table services.

And Redis, someone mentioned that... man, I dunno. Even the existence of persistence in a caching framework (which Redis offers) doesn't turn it into a tech of choice... There is a huge difference between a persistent store that holds data that is "often used, but may be missing or time-retired", like a cache would, and a persistent store that guarantees your data to be there.


问:
Deserialize a JSON that has a key variable jackson map ObjectMapper
JSON: </p>

```<code>  {
    "id": "1704",
    "title": "Choice of Drink",
    "multiselect": 0,
    "maximum_selection": 1,
    "ac_items": 1,
    "Choice of Drink": [{
        "id": "8151",
        "name": "Lemon Ice Tea",
        "price": 0,
        "orig_price": 0
    }, {
        "id": "8152",
        "name": "Fresh Lime",
        "price": 0,
        "orig_price": 0
    }]
}
</code>```

<p>The problem is that the key "Choice of Drink" is a variable.How can I put this in a @JsonProperty, when I don't have the name? </p>

答:
You can use Jackson's @JsonAnySetter annotation to direct all variable keys to one method and there you can assign/handle them as you wish:

```<code>public class Bar
{
    // known/fixed properties
    public String id;
    public String title;
    public int multiselect;
    public int maximum_selection;
    public int ac_items;

    // unknown/variable properties will go here
    @JsonAnySetter
    public void setDrinks(String key, Object value)
    {
        System.out.println("variable key = '" + key + "'");
        System.out.println("value is of type = " + value.getClass());
        System.out.println("value toString = '" + value.toString() + "'");
    }
}
</code>```

in the case of the sample input, the output is:

```<code>variable key = 'Choice of Drink'
value is of type = class java.util.ArrayList
value toString = '[{id=8151, name=Lemon Ice Tea, price=0, orig_price=0}, {id=8152, name=Fresh Lime, price=0, orig_price=0}]'
</code>```

Body:
JSON:

  {
    "id": "1704",
    "title": "Choice of Drink",
    "multiselect": 0,
    "maximum_selection": 1,
    "ac_items": 1,
    "Choice of Drink": [{
        "id": "8151",
        "name": "Lemon Ice Tea",
        "price": 0,
        "orig_price": 0
    }, {
        "id": "8152",
        "name": "Fresh Lime",
        "price": 0,
        "orig_price": 0
    }]
}

The problem is that the key "Choice of Drink" is a variable.How can I put this in a @JsonProperty, when I don't have the name?

Body:
You can use Jackson's @JsonAnySetter annotation to direct all variable keys to one method and there you can assign/handle them as you wish:

public class Bar
{
    // known/fixed properties
    public String id;
    public String title;
    public int multiselect;
    public int maximum_selection;
    public int ac_items;

    // unknown/variable properties will go here
    @JsonAnySetter
    public void setDrinks(String key, Object value)
    {
        System.out.println("variable key = '" + key + "'");
        System.out.println("value is of type = " + value.getClass());
        System.out.println("value toString = '" + value.toString() + "'");
    }
}

in the case of the sample input, the output is:

variable key = 'Choice of Drink'
value is of type = class java.util.ArrayList
value toString = '[{id=8151, name=Lemon Ice Tea, price=0, orig_price=0}, {id=8152, name=Fresh Lime, price=0, orig_price=0}]'


答: strcat doesn't do what you think. It modifies the string pointed to by its first parameter. In this case, that string is contained in a 2-byte array, which is therefore overrun.

Title: strcat segmentation fault

Body:
The second call to strcat here is generating a segmentation fault, why?

#include <unistd.h>
#include<stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>

int main (int argc, char * argv[])
{
         char command[250];

         //if(scanf("%199s", command) == 1)

            gets(command);
            puts(command);

         int pipeIntId;

         char whitespaceseparator[2]=" ";

         char pidstring [30];

         int pid= getpid();

         sprintf(pidstring,"%d", pid);

         char * whitespace_and_pid;

         whitespace_and_pid = strcat(whitespaceseparator,pidstring);

         char * command_and_pid;

         command_and_pid=strcat(command,whitespace_and_pid); // here's the problem, I guess

          if((mkfifo("pipe"/*pipeName*/,0666))==-1)
          {
              perror("error creating pipe 1");
          exit(1);
          }

         if((pipeIntId=open("pipe",/*pipeName*/O_WRONLY))==-1)
         {
          perror("error creating pipe 2");
          exit(1);
         }

         int written;

         written=write(pipeIntId,command_and_pid,250); // send the command + the pid

         close(pipeIntId);

    return 0;
}


问:
React Native on iOS returns HTTP 406 Not Acceptable error message
I'm trying to show a React Native view in my iOS application using Swift 2. React Native returns the HTTP 406 Not Acceptable error message.

```<code>let bridge = RCTBridge(bundleURL: jsCodeLocation, moduleProvider: nil, launchOptions: ["controller":self])
let reactRootView: RCTRootView = RCTRootView(bridge: bridge, moduleName: moduleName, initialProperties: initialProperties)
reactRootView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
reactRootView.delegate = self
let viewController = UIViewController()
viewController.view.addSubview(reactRootView)
self.navigationController?.pushViewController(viewController, animated: true)
</code>```

Could you suggest a decision to fix?

答: I have found the cause of the failure: a wrong JS code location URL.</p>

Body:
I'm trying to show a React Native view in my iOS application using Swift 2. React Native returns the HTTP 406 Not Acceptable error message.

let bridge = RCTBridge(bundleURL: jsCodeLocation, moduleProvider: nil, launchOptions: ["controller":self])
let reactRootView: RCTRootView = RCTRootView(bridge: bridge, moduleName: moduleName, initialProperties: initialProperties)
reactRootView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
reactRootView.delegate = self
let viewController = UIViewController()
viewController.view.addSubview(reactRootView)
self.navigationController?.pushViewController(viewController, animated: true)

Could you suggest a decision to fix?


问:
How to get all client info from website visitors?
I want to collect all the information that we could when someone is visiting a webpage: e.g.:

```<code>clients screen resolution: <script type='text/javascript'>document.write(screen.width+'x'+screen.height); </script>
referer: <?php print ($_SERVER['HTTP_REFERER']); ?>
client ip: <?php print ($_SERVER['REMOTE_ADDR']); ?>
user agent:  <?php print ($_SERVER['HTTP_USER_AGENT']); ?>
</code>```

what else is there?

答:
```<code>phpinfo(32);
</code>```

Prints a table with the whole extractable information. You can simply copy and paste the variables directly into your php code.

e.g:

```<code>_SERVER["GEOIP_COUNTRY_CODE"]   AT
</code>```

would be in php code:

```<code>echo $_SERVER["GEOIP_COUNTRY_CODE"];
</code>```

OwnerDisplayName: LanceBaynes

Body:
I want to collect all the information that we could when someone is visiting a webpage: e.g.:

clients screen resolution:
referer: <?php print ($_SERVER['HTTP_REFERER']); ?>
client ip: <?php print ($_SERVER['REMOTE_ADDR']); ?>
user agent:  <?php print ($_SERVER['HTTP_USER_AGENT']); ?>

what else is there?

Body:
phpinfo(32);

Prints a table with the whole extractable information. You can simply copy and paste the variables directly into your php code.

e.g:

_SERVER["GEOIP_COUNTRY_CODE"]   AT

would be in php code:

echo $_SERVER["GEOIP_COUNTRY_CODE"];


问:
change active menu-items font on click
So, i've got this menu which is linked to some dynamically displayed content, I've been trying to write some js-code that changes the font of the currently active item. My problem is now that it never deselects that item if it isn't active anymore.

jsfiddle:

https://jsfiddle.net/z4uhL5wv/2/

jquery:

```<code>$(document).ready(function() {

  $("a.menu2").click(function(e) {
  $('.ShowClickedContent').html($($(this).attr('href')).html()); //dynamic content
  var clicks = 0;

      if(clicks % 2 == 0){
          $(this).css('font-family','gillsans');
      }else{
          $(this).css('font-family','gillsanslight');
      }
      ++clicks;

});

});
</code>```

Any help would be greatful. Note: i need to use that exact showClickedContent query in the final solution due to problems arising with margin otherwise.

答:
You can do it with CSS! I didn't mess with fonts, but I did it with font-size as an example:

```<code>a:active, a:focus {font-size:15px;}
</code>```

Just replace the font-size with font-family and whatever...

Title: change active menu-items font on click

Body:
So, i've got this menu which is linked to some dynamically displayed content, I've been trying to write some js-code that changes the font of the currently active item. My problem is now that it never deselects that item if it isn't active anymore.

jsfiddle:

https://jsfiddle.net/z4uhL5wv/2/

jquery:

$(document).ready(function() {

  $("a.menu2").click(function(e) {
  $('.ShowClickedContent').html($($(this).attr('href')).html()); //dynamic content
  var clicks = 0;

      if(clicks % 2 == 0){
          $(this).css('font-family','gillsans');
      }else{
          $(this).css('font-family','gillsanslight');
      }
      ++clicks;

});

});

Any help would be greatful. Note: i need to use that exact showClickedContent query in the final solution due to problems arising with margin otherwise.

Body:
You can do it with CSS! I didn't mess with fonts, but I did it with font-size as an example:

a:active, a:focus {font-size:15px;}

Just replace the font-size with font-family and whatever...


问:
Django. Does not removes files when upload new one
Django does not deletes old file when new one is uploading. Instead of it adds '_' to the a new file name and keep old file in the storage. How it can be solved?

答: I will agree with the comments that this is a feature and not a bug but I will point out that there was a ticket opened (and later closed as wontfix) against Django that might be helpful if you would like to try to "fix" this. See http://code.djangoproject.com/ticket/11663 for a patch and additional comments/guidance.</p>


问:
angular2-flash-messages prod build failing
I am using angular2-flash-messages in my angular(4) application.
and I have added in app.module.ts

```<code>import { FlashMessagesModule } from 'angular2-flash-messages';
imports: [
    FlashMessagesModule,
  ],
</code>```

on dev build every thing working fine.Getting flash messages.
But the prod build getting fail (ng build --prod) and getting this error.

```<code>ERROR in D:/<>/src/$$_gendir/node_modules/angular2-flash-messages/module/flash-messages.component.ngfactory.ts (1,1):
Property 'classes' does not exist on type 'FlashMessagesComponent'.
</code>```

答:
Find the FlashMessagesComponent under node-modules->angular2-flash-messages->module->flash-messages.component.ts.

Just add a property names as 'classes' in FlashMessagesComponent and build again.
Screenshot

Body:
I am using angular2-flash-messages in my angular(4) application.
and I have added in app.module.ts

import { FlashMessagesModule } from 'angular2-flash-messages';
imports: [
    FlashMessagesModule,
  ],

on dev build every thing working fine.Getting flash messages.
But the prod build getting fail (ng build --prod) and getting this error.

ERROR in D:/<>/src/$$_gendir/node_modules/angular2-flash-messages/module/flash-messages.component.ngfactory.ts (1,1):
Property 'classes' does not exist on type 'FlashMessagesComponent'.


问:
Select from literal values not in table in PostgreSQL?
I have some values in Excel, I copy the values and it look like this:

1
2
3
4

I want to write a query that select from above data that is not present in a table. Somethink like:

```<code>SELECT * FROM [1, 2, 3, 4] as foo where foo IS NOT ( SELECT id from table )
</code>```

Supposing id column have 1,2,4 the query answer will be 3.

Preferably a query that can work in postgres and sql server

Thank you!

答:
You need a left join or something similar for this.  Here is one method:

```<code>SELECT v.*
FROM (VALUES (1), (2), (3), (4)) v(foo)
WHERE foo NOT IN ( SELECT id from table );
</code>```

Body:
I have some values in Excel, I copy the values and it look like this:

1
2
3
4

I want to write a query that select from above data that is not present in a table. Somethink like:

SELECT * FROM [1, 2, 3, 4] as foo where foo IS NOT ( SELECT id from table )

Supposing id column have 1,2,4 the query answer will be 3.

Preferably a query that can work in postgres and sql server

Thank you!

Body:
You need a left join or something similar for this.  Here is one method:

SELECT v.*
FROM (VALUES (1), (2), (3), (4)) v(foo)
WHERE foo NOT IN ( SELECT id from table );


问:
Two AND/OR in one bash if statement
I have a special condition to test in a bash script.
I thought about something like:

```<code>if [[ $categorie = "DG" || $categorie = "DI" ]] && [[ $client != "host1" || $client != "host2" ]]; then
    echo "requirements are met"
else
    echo "requirements not met"
fi
</code>```

In words: If categorie is DG OR DI AND client is NOT host1 OR host2 then do stuff.

Is this correct?
For me it looks like it just cares about the categorie and if the categorie condition is met it's ok and prints "requirements are met" and doesn't care about the condition for the client at all.

答: You are correct. Since any string is always unequal to at least one of two differing strings, the part after the && is always true.

Title: Two AND/OR in one bash if statement

Body:
I have a special condition to test in a bash script.
I thought about something like:

if [[ $categorie = "DG" || $categorie = "DI" ]] && [[ $client != "host1" || $client != "host2" ]]; then
    echo "requirements are met"
else
    echo "requirements not met"
fi

In words: If categorie is DG OR DI AND client is NOT host1 OR host2 then do stuff.

Is this correct?
For me it looks like it just cares about the categorie and if the categorie condition is met it's ok and prints "requirements are met" and doesn't care about the condition for the client at all.


问:
Run PHP shell_exec() like root user
I building one PHP application where I create command line functionality for Linux debian Jessie. All works fne but I need to be able use some commands like root user.

Is there a way to use shell_exec() or similar command to access like root user via PHP?

Idea of this command line is to people who have access to that server can handle with it over internet from any place or device.

Here is image of console:

答:
Executing commands as root via PHP will leave yourself wide open to all sorts of malicious hackery.

Have a look at the "sudo" documentation.

You should be able to set up all the commands you need as "sudo"able scripts. It is much better to write specific scripts with limited functions than to expose the underlying priviledged command.

As in:

```<code>exec ('sudo getCurrentUser.sh')
</code>```

First, you need to add the user that PHP is using to run (most of the time it is www-data) to the sudo group if it is not already assigned.

Then, in your php file:

use sudo -S, so you can pass the password via echo

```<code>$exec = "echo your_passwd | /usr/bin/sudo -S your command";
exec($exec,$out,$rcode);
</code>```

if you have trouble with the paths - use

```<code>"bash -lc 'echo your_passwd | /usr/bin/sudo -S your command'"
</code>```

so you get a new bash that acts like a login shell and has the paths set

Title: Run PHP shell_exec() like root user

Body:
Executing commands as root via PHP will leave yourself wide open to all sorts of malicious hackery.

Have a look at the "sudo" documentation.

You should be able to set up all the commands you need as "sudo"able scripts. It is much better to write specific scripts with limited functions than to expose the underlying priviledged command.

As in:

exec ('sudo getCurrentUser.sh')

First, you need to add the user that PHP is using to run (most of the time it is www-data) to the sudo group if it is not already assigned.

Then, in your php file:

use sudo -S, so you can pass the password via echo

$exec = "echo your_passwd | /usr/bin/sudo -S your command";
exec($exec,$out,$rcode);

if you have trouble with the paths - use

"bash -lc 'echo your_passwd | /usr/bin/sudo -S your command'"

so you get a new bash that acts like a login shell and has the paths set


问:
Specific Column Dump from Parquet File using Parquet-tools.jar
I want to dump only a specific column on some text file using parquet-tools-1.8.1.jar.But not able to do so. I am trying below command. Please note my column name has forward slash.</p>

```<code>parquet-tools-1.8.1.jar dump --column 'dir1/log1/job12121' '/hdfs-path/to/parquet file with space.parquet' > /home/local/parquet/output.text
</code>```

答:
Please use the following:

hadoop jar parquet-tools-1.8.1.jar dump -c dir1 log1 job12121 -m /hdfs-path/to/parquet file with space.parquet >> /home/local/parquet/output.text

Note:No single quotes for input arguments.

Body:
I want to dump only a specific column on some text file using parquet-tools-1.8.1.jar.But not able to do so. I am trying below command. Please note my column name has forward slash.

parquet-tools-1.8.1.jar dump --column 'dir1/log1/job12121' '/hdfs-path/to/parquet file with space.parquet' > /home/local/parquet/output.text


问:
strcat segmentation fault
The second call to strcat here is generating a segmentation fault, why?

```<code>#include <unistd.h>
#include<stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>

int main (int argc, char * argv[])
{
         char command[250];

         //if(scanf("%199s", command) == 1)

            gets(command);
            puts(command);

         int pipeIntId;

         char whitespaceseparator[2]=" ";

         char pidstring [30];

         int pid= getpid();

         sprintf(pidstring,"%d", pid);

         char * whitespace_and_pid;

         whitespace_and_pid = strcat(whitespaceseparator,pidstring);

         char * command_and_pid;

         command_and_pid=strcat(command,whitespace_and_pid); // here's the problem, I guess

          if((mkfifo("pipe"/*pipeName*/,0666))==-1)
          {
              perror("error creating pipe 1");
          exit(1);
          }

         if((pipeIntId=open("pipe",/*pipeName*/O_WRONLY))==-1)
         {
          perror("error creating pipe 2");
          exit(1);
         }

         int written;

         written=write(pipeIntId,command_and_pid,250); // send the command + the pid

         close(pipeIntId);

    return 0;
}
</code>```

答:
whitespaceseparator isn't big enough to contain the concatenated string, so you're causing undefined behaviour.

Using gets is normally frowned upon, too.

Title: strcat segmentation fault


问:
Need help in JavaScript , openWindow ();
I am trying to run the following JavaScript program,

function myFunction() {
  var x;
  if (confirm("Press a button!") == true) {
    x = "You pressed Ok!";
  } else {
    x = "You pressed Cancel!";
  }
  document.getElementById("demo").innerHTML = x;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>Click the button to display a confirm box.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p></code>```

But I really need is not just saying "You pressed Ok" instead of that it need to open a link. Help me please.

I hope

```<code>openWindow("http://fb.com")
</code>```

this line will help, but don't know where to place it and make a working program.

答:
```<code>if (confirm("Press a button!")) {
    window.open('www.google.com')
}
</code>```

Body:
I am trying to run the following JavaScript program,

function myFunction() {
  var x;
  if (confirm("Press a button!") == true) {
    x = "You pressed Ok!";
  } else {
    x = "You pressed Cancel!";
  }
  document.getElementById("demo").innerHTML = x;
}

Click the button to display a confirm box.

<button onclick="myFunction()">Try it</button>

But I really need is not just saying "You pressed Ok" instead of that it need to open a link. Help me please.

I hope

openWindow("http://fb.com")

this line will help, but don't know where to place it and make a working program.


问:
Flask and Angular Ui-Router
I am trying to setup angular ui-router with Flask as the server-side language. I am having trouble loading up partials in my ui-view. Here is my directory structure

and my routes look like this:

```<code>(function () {
    'use strict';

    angular
        .module('dvgo-admin')
        .config(config);

    config.$inject = ['$stateProvider', '$urlRouterProvider', '$locationProvider'];

    function config($stateProvider, $urlRouterProvider, $locationProvider) {

        $locationProvider.html5Mode({
          enabled: true,
          requireBase: false
        });

        $urlRouterProvider.otherwise('/');

        $stateProvider.
            state('matching-console', {
                url: '/matching-console',
                templateUrl: '/dogvacay-admin/templates/matching-console.view.html',
                controller: 'MatchingConsoleController as vm'
            })
    }

}());
</code>```

What is the proper way to have flask serve my partials correctly?

答:
Your folder Structure is fine But you need to serve index.html for "/"
route through flask.
In flask you can define a route for "/" like:

```<code>basedir = os.path.abspath( os.path.join( os.path.dirname(__file__), os.pardir ))

app.static_folder = os.path.join(basedir, 'client') # Add static folder directory

@app.route("/")
    def index():
        return app.send_static_file('index.html')
</code>```

This way you can render index.html file from flask. Once the index is loaded angular ui-router will take care of browser routings.

Title: Flask and Angular Ui-Router

Body:
I am trying to setup angular ui-router with Flask as the server-side language. I am having trouble loading up partials in my ui-view. Here is my directory structure

and my routes look like this:

(function () {
    'use strict';

    angular
        .module('dvgo-admin')
        .config(config);

    config.$inject = ['$stateProvider', '$urlRouterProvider', '$locationProvider'];

    function config($stateProvider, $urlRouterProvider, $locationProvider) {

        $locationProvider.html5Mode({
          enabled: true,
          requireBase: false
        });

        $urlRouterProvider.otherwise('/');

        $stateProvider.
            state('matching-console', {
                url: '/matching-console',
                templateUrl: '/dogvacay-admin/templates/matching-console.view.html',
                controller: 'MatchingConsoleController as vm'
            })
    }

}());

What is the proper way to have flask serve my partials correctly?

Body:
Your folder Structure is fine But you need to serve index.html for "/"
route through flask.
In flask you can define a route for "/" like:

basedir = os.path.abspath( os.path.join( os.path.dirname(__file__), os.pardir ))

app.static_folder = os.path.join(basedir, 'client') # Add static folder directory

@app.route("/")
    def index():
        return app.send_static_file('index.html')

This way you can render index.html file from flask. Once the index is loaded angular ui-router will take care of browser routings.


问:
Class Dependency Tools for Java
I know a lot of related questions have been given on SO, but I've not been able to find anything fully satisfactory - probably because my requirement is slightly different from each of those questions raised.

I have a gigantic codebase that I'd like to break down into smaller logic units. To do this, I need to find all the tangled/circular dependencies and resolve them. Due to the size of the existing spaghetti, the only feasible strategy appears to be divide-and-conquer, so I need to divide the huge project into smaller pieces first or peel off independent parts and tackle the smaller pieces separately.

Most of the tools I can find out there seems to only work on the class or package level, but they don't seem to support the concept of sub-packages. For example, If I have a root package, 3 packages under that, and then 5 subpackages under each of the 3, then I'll get 1+3+15=19 packages, which will give me a crazily complicated graph. Now what I hope to be able to do is to analyze the dependency relationship between the 3 top level packages first (number of incoming/outgoing packages, and which classes originate these dependencies), clean it up on that level, before diving into these top level packages to work on the next level.

Now, I've used Structure 101 for this purpose, and it works great, but when the trial expires, the price of the product is a little steep for my budget. Is there a free/open source solution out there?

Thanks in advance!

答:
project: https://github.com/lukehutch/fast-classpath-scanner

how to use latest tips/news: https://github.com/lukehutch/fast-classpath-scanner/releases

pre-compiled jars+source: https://oss.sonatype.org/#nexus-search;quick~fast-classpath-scanner

example:
https://github.com/lukehutch/fast-classpath-scanner/wiki/3.9.-Generating-a-GraphViz-dot-file-from-the-classgraph

```<code>ScanResult scanResult = new FastClasspathScanner(
  MyClass.class.getPackage().getName()).scan();
String str = scanResult.generateClassGraphDotFile(9.2f, 8.0f);

Files.write(str, new File("GraphViz.dot"), StandardCharsets.UTF_8);

System.out.println("now run this at terminal: dot -Tsvg < GraphViz.dot > GraphViz.svg");
</code>```

Title: Class Dependency Tools for Java

Body:
project: https://github.com/lukehutch/fast-classpath-scanner

how to use latest tips/news: https://github.com/lukehutch/fast-classpath-scanner/releases

pre-compiled jars+source: https://oss.sonatype.org/#nexus-search;quick~fast-classpath-scanner

example:
https://github.com/lukehutch/fast-classpath-scanner/wiki/3.9.-Generating-a-GraphViz-dot-file-from-the-classgraph

ScanResult scanResult = new FastClasspathScanner(
  MyClass.class.getPackage().getName()).scan();
String str = scanResult.generateClassGraphDotFile(9.2f, 8.0f);

Files.write(str, new File("GraphViz.dot"), StandardCharsets.UTF_8);

System.out.println("now run this at terminal: dot -Tsvg < GraphViz.dot > GraphViz.svg");


答:
You just need to change your function and place your openWindow() call inside it. Because I don't know what your openWindow() function does, I would use window.open():

```<code>function myFunction() {
  window.open("http://fb.com");
}
</code>```

Title: Need help in JavaScript , openWindow ();

Body:
You just need to change your function and place your openWindow() call inside it. Because I don't know what your openWindow() function does, I would use window.open():

function myFunction() {
  window.open("http://fb.com");
}


问:
Can I search multiple values in a "data-" element?
I have a simple search input that filters divs as you type so that only those divs with matching data attributes are shown.

This works great, but it only returns exact matches. For example, in the snippet below, I can search for "apple" but "apple california" doesn't show the proper div (even though the data attribute contains both of those values). I think this is because it's only searching for an exact match.

How might I adjust this code to search for multiple values in a "data-" element? Ideally I'd like to have it ignore common words like "and," "in," "near," so that a search for:

Apple in California or iphone near california

would still show the Apple div.

Appreciate any advice, I'm stumped! Here's the snippet:

$('[data-search]').on('keyup', function() {
  var searchVal = $(this).val();
  var filterItems = $('[data-filter-item]');

  if (searchVal != '') {
    filterItems.addClass('hidden');
    $('[data-filter-item][data-filter-name*="' + searchVal.toLowerCase() + '"]').removeClass('hidden');
  } else {
    filterItems.removeClass('hidden');
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Helvetica, sans-serif;
}

.hidden {
  display: none;
}

input {
  background: #cdcdcd;
  border: none;
  padding: 14px 20px;
}

.items {
  margin-top: 25px;
}</code>```

    <input type="text" placeholder="search" data-search />

Apple

Google

Microsoft

```

答:
You can just grab all items and use string.indexOf on each item's data to check the presence of a string in a string.

```<code>$('[data-filter-item][data-filter-name]').each(function(element){
  var isPresent = $(this).data('filter-name').indexOf(searchVal.toLowerCase()) > -1;
  if(isPresent){
    // do something
  } else {
    // do something else
  }
});
</code>```

Body:
I have a simple search input that filters divs as you type so that only those divs with matching data attributes are shown.

This works great, but it only returns exact matches. For example, in the snippet below, I can search for "apple" but "apple california" doesn't show the proper div (even though the data attribute contains both of those values). I think this is because it's only searching for an exact match.

How might I adjust this code to search for multiple values in a "data-" element? Ideally I'd like to have it ignore common words like "and," "in," "near," so that a search for:

Apple in California or iphone near california

would still show the Apple div.

Appreciate any advice, I'm stumped! Here's the snippet:

$('[data-search]').on('keyup', function() {
  var searchVal = $(this).val();
  var filterItems = $('[data-filter-item]');

  if (searchVal != '') {
    filterItems.addClass('hidden');
    $('[data-filter-item][data-filter-name*="' + searchVal.toLowerCase() + '"]').removeClass('hidden');
  } else {
    filterItems.removeClass('hidden');
  }
});

* {
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Helvetica, sans-serif;
}

.hidden {
  display: none;
}

input {
  background: #cdcdcd;
  border: none;
  padding: 14px 20px;
}

.items {
  margin-top: 25px;
}

    <input type="text" placeholder="search" data-search />

Apple

Google

Microsoft

Body:
You can just grab all items and use string.indexOf on each item's data to check the presence of a string in a string.

$('[data-filter-item][data-filter-name]').each(function(element){
  var isPresent = $(this).data('filter-name').indexOf(searchVal.toLowerCase()) > -1;
  if(isPresent){
    // do something
  } else {
    // do something else
  }
});


问:
references a foreign key that is a primary key with another key on the parent table
i have those tables :

```<code>create table t_table(t1 int, constraint tprim primary key(t1));

create table parent_table(t1 int, p1 int, p2 int, constraint pprim primary key(t1, p1));

create table child_table(t1 int, c1 int, p1 int, constraint cprim primary key(t1, c1), constraint fchild foreign key (p1) references parent_table(p1));
</code>```

i get this error when creating the second table :

```<code>ORA-02270: no matching unique or primary key for this column-list
</code>```

p1 in parent_table is not unique so i can't make it unique to resolve the problem.

in this case how to say that p1 is a foreign key in child_table that references parent_table(p1) ?

thanks in advance.

答: this is not possible you must reference a primary key</p>

Body:
i have those tables :

create table t_table(t1 int, constraint tprim primary key(t1));

create table parent_table(t1 int, p1 int, p2 int, constraint pprim primary key(t1, p1));

create table child_table(t1 int, c1 int, p1 int, constraint cprim primary key(t1, c1), constraint fchild foreign key (p1) references parent_table(p1));

i get this error when creating the second table :

ORA-02270: no matching unique or primary key for this column-list

p1 in parent_table is not unique so i can't make it unique to resolve the problem.

in this case how to say that p1 is a foreign key in child_table that references parent_table(p1) ?

thanks in advance.