问:
R Custom Max Function
```<code>data=data.frame("person"=c(1,1,1,1,2,2,2,2,3,3,3,3,4,4,4),
                "score"=c(1,2,3,2,2,1,2,3,2,3,1,4,1,4,3),
                "WANT"=c(1,2,3,3,2,1,2,3,2,3,3,4,1,4,NA))
</code>```

For each person we track their scores until they reach "proficient" (3) or excellence (4). If a person scores excellence (4) then that value is kept and the persons next score is removed (see person 4; instead of NA would just want to remove that row however). If a person scores proficient (3) that value is carried forward UNLESS they score 4 which would replace the score of 3. Otherwise the values stay how they are. I tried cummax func but not sure how to apply such a rule.

It is my attempt below

```<code>data$want = ave(data$score, data$person, FUN = function(x) cummax(replace(x, is.na(x), -1)))
</code>```

答:
You can write a custom function with the rules you specified and apply it on every person in a group by as follows,</p>

```<code>library(dplyr)

count_3_4 <- function(vec){
  max = 0
  for(i in seq_along(vec)){
    if(vec[i] > max){
      max = vec[i]
      if(max == 3 || max == 4){
        vec[i] = max
      }
    }else if(max == 4 && vec[i] < max){
      vec[i] = NA
    }else{
      if(max == 3 || max == 4){
        vec[i] = max
      }
    }
  }
  return(vec)
}

data=data.frame("person"=c(1,1,1,1,2,2,2,2,3,3,3,3,4,4,4),
                "score"=c(1,2,3,2,2,1,2,3,2,3,1,4,1,4,3),
                "WANT"=c(1,2,3,3,2,1,2,3,2,3,3,4,1,4,NA))

data%>%
  group_by(person)%>%
  mutate(TestVal = count_3_4(score)) %>%
  ungroup()
</code>```

Title: R Custom Max Function

Body:
data=data.frame("person"=c(1,1,1,1,2,2,2,2,3,3,3,3,4,4,4),
                "score"=c(1,2,3,2,2,1,2,3,2,3,1,4,1,4,3),
                "WANT"=c(1,2,3,3,2,1,2,3,2,3,3,4,1,4,NA))

For each person we track their scores until they reach "proficient" (3) or excellence (4). If a person scores excellence (4) then that value is kept and the persons next score is removed (see person 4; instead of NA would just want to remove that row however). If a person scores proficient (3) that value is carried forward UNLESS they score 4 which would replace the score of 3. Otherwise the values stay how they are. I tried cummax func but not sure how to apply such a rule.

It is my attempt below

data$want = ave(data$score, data$person, FUN = function(x) cummax(replace(x, is.na(x), -1)))

Body:
You can write a custom function with the rules you specified and apply it on every person in a group by as follows,

library(dplyr)

count_3_4 <- function(vec){
  max = 0
  for(i in seq_along(vec)){
    if(vec[i] > max){
      max = vec[i]
      if(max == 3 || max == 4){
        vec[i] = max
      }
    }else if(max == 4 && vec[i] < max){
      vec[i] = NA
    }else{
      if(max == 3 || max == 4){
        vec[i] = max
      }
    }
  }
  return(vec)
}

data=data.frame("person"=c(1,1,1,1,2,2,2,2,3,3,3,3,4,4,4),
                "score"=c(1,2,3,2,2,1,2,3,2,3,1,4,1,4,3),
                "WANT"=c(1,2,3,3,2,1,2,3,2,3,3,4,1,4,NA))

data%>%
  group_by(person)%>%
  mutate(TestVal = count_3_4(score)) %>%
  ungroup()


来源: stackexchange

问:
Material UI card will not center. React JS
Trying to use a card for the main part of my home page.  However, nothing I will do will center the card, and I have tried putting justify, alignItems, alignContent, however, none of them seem to resolve the issue.  I honestly have no idea what else to do to align this to the center.  I don't see how it's even possible.  Here is the code:</p>

```<code>import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core/styles';
import Card from '@material-ui/core/Card';
import CardActionArea from '@material-ui/core/CardActionArea';
import CardActions from '@material-ui/core/CardActions';
import CardContent from '@material-ui/core/CardContent';
import CardMedia from '@material-ui/core/CardMedia';
import Button from '@material-ui/core/Button';
import Typography from '@material-ui/core/Typography';
import reactImage from '../images/djangoreact.png'

const styles = {
  card: {
    width: "100%",
    backgroundColor: 'black',
    textAlign: 'center',
    justifyContent: 'center',
    alignContent: 'center',
    padding: '30px'
  },
  media: {
    height: 325,
    // textAlign: 'center',
    // justifyContent: 'center',
    // alignContent: 'center',
  },
  font: {
    color: 'white',
    // textAlign: 'center',
    // justifyContent: 'center',
    // alignContent: 'center',
  },
  header:{
    textAlign: 'center',
    justify: 'center',
    alignContent: 'center',
    width: '100%'

  }
};

function MediaCard(props) {
  const { classes } = props;
  return (
      <div className={classes.header} style={{
        justify: 'center',
        alignContent: 'center',
        alignItems: 'center'
      }}>
    <Card className={classes.card} style={{
        justify: 'center',
        alignContent: 'center',
        alignItems: 'center'
      }}>
      <CardActionArea>
        <CardMedia
          className={classes.media}
          image={reactImage}
          title="Contemplative Reptile"
        />
        <CardContent>
          <Typography gutterBottom variant="h5" component="h2" className={classes.font}>
            Welcome to the KB
          </Typography>
          <Typography component="p" className={classes.font}>
            Check out the tutorial for the Djanog/React boilerplate used to make this site!
          </Typography>
        </CardContent>
      </CardActionArea>
      <CardActions>
        <Button size="small" color="primary">
          Learn More
        </Button>
      </CardActions>
    </Card>
    </div>
  );
}

MediaCard.propTypes = {
  classes: PropTypes.object.isRequired,
};

export default withStyles(styles)(MediaCard);
</code>```

答:
Alternatively to switching to <Grid>, I put a
 wrapper around the <CardMedia> element and used

```<code>style={{ display:'flex', justifyContent:'center' }}
</code>```

on the outer
 tag to achieve the same result.

ContentLicense: CC BY-SA 4.0

Body:
Trying to use a card for the main part of my home page.  However, nothing I will do will center the card, and I have tried putting justify, alignItems, alignContent, however, none of them seem to resolve the issue.  I honestly have no idea what else to do to align this to the center.  I don't see how it's even possible.  Here is the code:

import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core/styles';
import Card from '@material-ui/core/Card';
import CardActionArea from '@material-ui/core/CardActionArea';
import CardActions from '@material-ui/core/CardActions';
import CardContent from '@material-ui/core/CardContent';
import CardMedia from '@material-ui/core/CardMedia';
import Button from '@material-ui/core/Button';
import Typography from '@material-ui/core/Typography';
import reactImage from '../images/djangoreact.png'

const styles = {
  card: {
    width: "100%",
    backgroundColor: 'black',
    textAlign: 'center',
    justifyContent: 'center',
    alignContent: 'center',
    padding: '30px'
  },
  media: {
    height: 325,
    // textAlign: 'center',
    // justifyContent: 'center',
    // alignContent: 'center',
  },
  font: {
    color: 'white',
    // textAlign: 'center',
    // justifyContent: 'center',
    // alignContent: 'center',
  },
  header:{
    textAlign: 'center',
    justify: 'center',
    alignContent: 'center',
    width: '100%'

  }
};

function MediaCard(props) {
  const { classes } = props;
  return (

    <Card className={classes.card} style={{
        justify: 'center',
        alignContent: 'center',
        alignItems: 'center'
      }}>
      <CardActionArea>
        <CardMedia
          className={classes.media}
          image={reactImage}
          title="Contemplative Reptile"
        />
        <CardContent>
          <Typography gutterBottom variant="h5" component="h2" className={classes.font}>
            Welcome to the KB
          </Typography>
          <Typography component="p" className={classes.font}>
            Check out the tutorial for the Djanog/React boilerplate used to make this site!
          </Typography>
        </CardContent>
      </CardActionArea>
      <CardActions>
        <Button size="small" color="primary">
          Learn More
        </Button>
      </CardActions>
    </Card>

  );
}

MediaCard.propTypes = {
  classes: PropTypes.object.isRequired,
};

export default withStyles(styles)(MediaCard);

Body:
Alternatively to switching to <Grid>, I put a <div> wrapper around the <CardMedia> element and used

style={{ display:'flex', justifyContent:'center' }}

on the outer <div> tag to achieve the same result.


问:
Compiling v8js extension after V8 was built with gn build (as opposed to gyp)
Google has decided to deprecate gyp builds of V8. The recommended method is to build with gn.

However, PHP extension v8js fails to find required libraries and exits with:

```<code>checking for V8 Javascript Engine... yes, shared
checking for g++... g++
checking whether we are using the GNU C++ compiler... yes
checking whether g++ accepts -g... yes
checking how to run the C++ preprocessor... g++ -E
checking for C standard version... c++11
checking how to allow c++11 narrowing... -Wno-narrowing
checking for V8 version... NONE
configure: error: could not determine libv8 version
</code>```

What needs to be done to compile PHP v8js extension after V8 is compiled with gn?

Thanks!

答:
echo -e "create/usr/lib/libv8_libplatform.a\naddlib /usr/local/src/v8/out.gn/x64.release/obj/libv8_libplatform.a\nsave\nend" | sudo ar -M

print : /usr/local/src/v8/out.gn/x64.release/obj/libv8_libplatform.a: No such file or directory

ContentLicense: CC BY-SA 3.0

Body:
Google has decided to deprecate gyp builds of V8. The recommended method is to build with gn.

However, PHP extension v8js fails to find required libraries and exits with:

checking for V8 Javascript Engine... yes, shared
checking for g++... g++
checking whether we are using the GNU C++ compiler... yes
checking whether g++ accepts -g... yes
checking how to run the C++ preprocessor... g++ -E
checking for C standard version... c++11
checking how to allow c++11 narrowing... -Wno-narrowing
checking for V8 version... NONE
configure: error: could not determine libv8 version

What needs to be done to compile PHP v8js extension after V8 is compiled with gn?

Thanks!


问:
Android Studio emulator shuts down after launch
Android Studio installed a few days ago. First project.
Worked fine, but after being in the background for a couple of days, the emulator was frozen. Had to force it down with Task Manager.

There was some message about "partially.." something. Then starting the emulator, it shut down after few seconds. Not even running an app. Just launching it fails.

Tried setting AVD (Nexus 5X API 26) graphics to software, no difference.
Tried uninstalling/reinstalling Nexus 5X AVD, no difference.
Tried uninstalling/reinstalling Android 8.0, no difference.

What to try next..?

答:
As of Android 3.4.1 update, you can solve these types of issues by right-clicking on the name of your virtual device and select "wipe data". Then run your device once complete.
It should work. </p>


问:
PHP mike42/escpos-php print from iPhone (remote website) to localhost printer
I have a website (on a remote server)and this is viewed by the user on the iPhone (Safari).

I'm trying to achieve the user being able to print a text file from that site to a POS Printer (REGO Thermal Printer, RG-MTP58B). This printer does not support AirPrint but is a wifi printer and lives on 172.20.10.2:9100 IP and port.

As far as I understand I cannot directly print from the server as the Printer is not in the server network but local network.

I'm using this package: https://github.com/mike42/escpos-php as I see is the only still maintained.

I've tried this way:

$connector = new FilePrintConnector("php://stdout");
$printer   = new Printer($connector);
$printer->text("Hello World!\n");
$printer->cut();
$printer->close();
```

<p>But this just gives a white page and the printer does not receive anything.</p>

<p>I've tried saving the file in the server, open it in Safari but Safari doesn't provide an option to print it (not even in the "Share" area).</p>

<p>So i found out the package Author does this:</p>

<pre class="lang-php prettyprint-override"><code>$connector = new DummyPrintConnector();
$profile = CapabilityProfile::load("TSP600");
$printer = new Printer($connector);
$printer->text("Hello world!\n");
$printer->cut();
// Get the data out as a string
$data = $connector->getData();
// Return it, check the manual for specifics.
header('Content-type: application/octet-stream');
header('Content-Length: '.strlen($data));
echo $data;
// Close the printer when done.
$printer->close();
</code>```

(original code: here)

In this case it creates a file and it shows it like this:

Again it does not provide an option to print it (not even in the "Share" area).

The file content is a binary:

```<code><0x1b>@Hello world!
<0x1d>VA<0x03>
</code>```

How do I send this data to the printer?

答:
Here is one possible solution is to create a simple app that is has a webview component that opens the URL to your server website.

Make a simple webview app for iPhone. You could use a wkwebview to your server
see wkwebview

Read Receipt content from the webview and parse out the receipt.

-- Be sure to format the receipt text using Esc/POS codes to format text, feed lines and cut paper.  Almost every receipt printer uses Esc/POS codes and many low cost thermal receipt printers like this actually use a Seiko Epson Corporation (SEC) engine.  That is why this PHP code likely works well with many printers.

Use Direct Socket connection to the printer on the local network from the iPhone app.  This way you can make sure that both the phone and the printer are on the same network.

If you are not a fan of swift, it is also possible to create the app with Xamarin or Apache Cordova as well as others.

Body:
I have a website (on a remote server)and this is viewed by the user on the iPhone (Safari).

I'm trying to achieve the user being able to print a text file from that site to a POS Printer (REGO Thermal Printer, RG-MTP58B). This printer does not support AirPrint but is a wifi printer and lives on 172.20.10.2:9100 IP and port.

As far as I understand I cannot directly print from the server as the Printer is not in the server network but local network.

I'm using this package: https://github.com/mike42/escpos-php as I see is the only still maintained.

I've tried this way:

$connector = new FilePrintConnector("php://stdout");
$printer   = new Printer($connector);
$printer->text("Hello World!\n");
$printer->cut();
$printer->close();

But this just gives a white page and the printer does not receive anything.

I've tried saving the file in the server, open it in Safari but Safari doesn't provide an option to print it (not even in the "Share" area).

So i found out the package Author does this:

$connector = new DummyPrintConnector();
$profile = CapabilityProfile::load("TSP600");
$printer = new Printer($connector);
$printer->text("Hello world!\n");
$printer->cut();
// Get the data out as a string
$data = $connector->getData();
// Return it, check the manual for specifics.
header('Content-type: application/octet-stream');
header('Content-Length: '.strlen($data));
echo $data;
// Close the printer when done.
$printer->close();

(original code: here)

In this case it creates a file and it shows it like this:

Again it does not provide an option to print it (not even in the "Share" area).

The file content is a binary:

<0x1b>@Hello world!
<0x1d>VA<0x03>

How do I send this data to the printer?


问:
Selecting table rows with jquery, but also selecting rows when clicking button, how do I prevent this?
When you click on a table row it adds a class that changes it's appearance to reflect it's selected.

```<code>    $('#my_table tbody').on( 'click', 'tr', function () {
        $(this).toggleClass('selected');
    } );
</code>```

However, I also have some buttons in a column that let you do things specific to the row:

```<code>Item    Amount    Action
--------------------------------
Apple   10        [Buy] [Delete]
Banana  5         [Buy] [Delete]
Orange  14        [Buy] [Delete]
</code>```

When I click one of the individual buttons, it also triggers the table row '.selected' class to be added, but I don't want this to occur when clicking buttons.

答:
You can use stopPropagation() or preventDefault() on buttons onclick event. This will prevent event bubling to parent elements of button (td, tr, table and so on). Assuming your buttons class as 'row-button' following is a sample code:</p>

```<code>$('.row-button').on('click', function(event)){
    event.stopPropagation();
    //Do what are intended upon button click.
}
</code>```

Body:
When you click on a table row it adds a class that changes it's appearance to reflect it's selected.

    $('#my_table tbody').on( 'click', 'tr', function () {
        $(this).toggleClass('selected');
    } );

However, I also have some buttons in a column that let you do things specific to the row:

Item    Amount    Action
--------------------------------
Apple   10        [Buy] [Delete]
Banana  5         [Buy] [Delete]
Orange  14        [Buy] [Delete]

When I click one of the individual buttons, it also triggers the table row '.selected' class to be added, but I don't want this to occur when clicking buttons.

Body:
You can use stopPropagation() or preventDefault() on buttons onclick event. This will prevent event bubling to parent elements of button (td, tr, table and so on). Assuming your buttons class as 'row-button' following is a sample code:

$('.row-button').on('click', function(event)){
    event.stopPropagation();
    //Do what are intended upon button click.
}


问:
Reliably checking wget log for errors using grep or ack
In a bash file, I have logfileA.txt that contains output from wget that I'd like to run grep on to check for any instances of the words "error" or "fail", etc, as so:

```<code>grep -ni --color=never -e "error" -e "fail" logfileA.txt | awk -F: '{print "Line "$1": "$2}'
# grep -n line number, -i ignore case; awk to add better format to the line numbers (https://stackoverflow.com/questions/3968103)
</code>```

Trouble is though, I think the wget output in logfileA.txt is full of characters that may be messing up the input for grep, as I'm not getting reliable matches.

Troubleshooting this, I cannot even cat the contents of the log file reliably. For instance, with cat logfileA.txt, all I get is the last line which is garbled:

```<code>FINISHED --2019-05-29 17:08:52--me@here:/home/n$ 71913592/3871913592]atmed out). Retrying.
</code>```

The contents of logfileA.txt is:

```<code>--2019-05-29 15:26:50--  http://somesite.com/somepath/a0_FooBar/BarFile.dat
Reusing existing connection to somesite.com:80.
HTTP request sent, awaiting response... 302 Found
Location: http://cdn.somesite.com/storage/a0_FooBar/BarFile.dat [following]
--2019-05-29 15:26:50--  http://cdn.somesite.com/storage/a0_FooBar/BarFile.dat
Resolving cdn.somesite.com (cdn.somesite.com)... xxx.xxx.xx.xx
Connecting to cdn.somesite.com (cdn.somesite.com)|xxx.xxx.xx.xx|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 3871913592 (3.6G) [application/octet-stream]
Saving to: 'a0_FooBar/BarFile.dat’

a0_FooBar/BarFile.dat   0%[                    ]       0  --.-KB/s
a0_FooBar/BarFile.dat   0%[                    ]  15.47K  70.5KB/s
...
a0_FooBar/BarFile.dat  49%[========>           ]   1.80G  --.-KB/s    in 50m 32s

2019-05-29 16:17:23 (622 KB/s) - Read error at byte 1931163840/3871913592 (Connection timed out). Retrying.

--2019-05-29 16:17:24--  (try: 2)  http://cdn.somesite.com/storage/a0_FooBar/BarFile.dat
Connecting to cdn.somesite.com (cdn.somesite.com)|xxx.xxx.xx.xx|:80... connected.
HTTP request sent, awaiting response... 206 Partial Content
Length: 3871913592 (3.6G), 1940749752 (1.8G) remaining [application/octet-stream]
Saving to: 'a0_FooBar/BarFile.dat’

a0_FooBar/BarFile.dat  49%[+++++++++           ]   1.80G  --.-KB/s
...
a0_FooBar/BarFile.dat 100%[+++++++++==========>]   3.61G  1.09MB/s    in 34m 44s

2019-05-29 16:52:09 (909 KB/s) - 'a0_FooBar/BarFile.dat’ saved [3871913592/3871913592]

FINISHED --2019-05-29 17:08:52--
</code>```

I assume the problem could be the /s or ---s or >s or ==>s or |s?

But since the output from wget could vary, how do I anticipate and escape anything problematical for grep?

Command:

```<code>grep -ni --color=never -e "error" -e "fail" logfileA.txt | awk -F: '{print "Line "$1": "$2}'
</code>```

Expected output:

```<code>Line 17: 2019-05-29 16:17:23 (622 KB/s) - Read error at byte 1931163840/3871913592 (Connection timed out). Retrying.
</code>```

Also, would an ack line be better at this job? And if so, what/how?

答:
Wrt I assume the problem could be the /s or ---s or >s or ==>s or |s? - no, there's nothing special about any of those characters/strings. It sounds like you might have DOS line endings (\r\n), see Why does my tool output overwrite itself and how do I fix it?. Since you said with cat logfileA.txt, all I get is the last line which is garbled I wonder if you ONLY have \rs and no \ns as line endings. If you do then tr '\r' '\n' < logfileA.txt > tmp && mv tmp logfileA.txt would fix that. If that IS the issue then going forward you can use awk -v RS='\r' 'script' to change the record separator from it's default \n to \r and then you won't need to do that tr step.

You don't need grep when you're using awk though. This:

```<code>grep -ni --color=never -e "error" -e "fail" logfileA.txt |
    awk -F: '{print "Line "$1": "$2}'
</code>```

can be written as just:

```<code>awk 'tolower($0) ~ /error|fail/{print "Line "NR":"$0}' logfileA.txt
</code>```

but the awk-only version is more robust as it'll correctly display full lines that contain :s where the grep+awk version will truncate them to the first :.

You can handle the DOS line endings, if any, by tweaking the script to:

```<code>awk 'tolower($0) ~ /error|fail/{sub(/\r$/,""); print "Line "NR":"$0}' logfileA.txt
</code>```

and you can make it look for error or fail as standalone words (as opposed to part of other strings like terror or failles) by doing this with GNU awk:

```<code>awk -v IGNORECASE=1 -v RS='\r?\n' '/\<(error|fail)\>/{print "Line "NR":"$0}' logfileA.txt
</code>```

or this with any awk:

```<code>awk 'tolower($0) ~ /(^|[^[:alnum:]_])(error|fail)([^[:alnum:]_]|$)/{sub(/\r$/,""); print "Line "NR":"$0}' logfileA.txt
</code>```

Body:
In a bash file, I have logfileA.txt that contains output from wget that I'd like to run grep on to check for any instances of the words "error" or "fail", etc, as so:

grep -ni --color=never -e "error" -e "fail" logfileA.txt | awk -F: '{print "Line "$1": "$2}'
# grep -n line number, -i ignore case; awk to add better format to the line numbers (https://stackoverflow.com/questions/3968103)

Trouble is though, I think the wget output in logfileA.txt is full of characters that may be messing up the input for grep, as I'm not getting reliable matches.

Troubleshooting this, I cannot even cat the contents of the log file reliably. For instance, with cat logfileA.txt, all I get is the last line which is garbled:

FINISHED --2019-05-29 17:08:52--me@here:/home/n$ 71913592/3871913592]atmed out). Retrying.

The contents of logfileA.txt is:

--2019-05-29 15:26:50--  http://somesite.com/somepath/a0_FooBar/BarFile.dat
Reusing existing connection to somesite.com:80.
HTTP request sent, awaiting response... 302 Found
Location: http://cdn.somesite.com/storage/a0_FooBar/BarFile.dat [following]
--2019-05-29 15:26:50--  http://cdn.somesite.com/storage/a0_FooBar/BarFile.dat
Resolving cdn.somesite.com (cdn.somesite.com)... xxx.xxx.xx.xx
Connecting to cdn.somesite.com (cdn.somesite.com)|xxx.xxx.xx.xx|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 3871913592 (3.6G) [application/octet-stream]
Saving to: 'a0_FooBar/BarFile.dat’

a0_FooBar/BarFile.dat   0%[                    ]       0  --.-KB/s
a0_FooBar/BarFile.dat   0%[                    ]  15.47K  70.5KB/s
...
a0_FooBar/BarFile.dat  49%[========>           ]   1.80G  --.-KB/s    in 50m 32s

2019-05-29 16:17:23 (622 KB/s) - Read error at byte 1931163840/3871913592 (Connection timed out). Retrying.

--2019-05-29 16:17:24--  (try: 2)  http://cdn.somesite.com/storage/a0_FooBar/BarFile.dat
Connecting to cdn.somesite.com (cdn.somesite.com)|xxx.xxx.xx.xx|:80... connected.
HTTP request sent, awaiting response... 206 Partial Content
Length: 3871913592 (3.6G), 1940749752 (1.8G) remaining [application/octet-stream]
Saving to: 'a0_FooBar/BarFile.dat’

a0_FooBar/BarFile.dat  49%[+++++++++           ]   1.80G  --.-KB/s
...
a0_FooBar/BarFile.dat 100%[+++++++++==========>]   3.61G  1.09MB/s    in 34m 44s

2019-05-29 16:52:09 (909 KB/s) - 'a0_FooBar/BarFile.dat’ saved [3871913592/3871913592]

FINISHED --2019-05-29 17:08:52--

I assume the problem could be the /s or ---s or >s or ==>s or |s?

But since the output from wget could vary, how do I anticipate and escape anything problematical for grep?

Command:

grep -ni --color=never -e "error" -e "fail" logfileA.txt | awk -F: '{print "Line "$1": "$2}'

Expected output:

Line 17: 2019-05-29 16:17:23 (622 KB/s) - Read error at byte 1931163840/3871913592 (Connection timed out). Retrying.

Also, would an ack line be better at this job? And if so, what/how?

Body:
Wrt I assume the problem could be the /s or ---s or >s or ==>s or |s? - no, there's nothing special about any of those characters/strings. It sounds like you might have DOS line endings (\r\n), see Why does my tool output overwrite itself and how do I fix it?. Since you said with cat logfileA.txt, all I get is the last line which is garbled I wonder if you ONLY have \rs and no \ns as line endings. If you do then tr '\r' '\n' < logfileA.txt > tmp && mv tmp logfileA.txt would fix that. If that IS the issue then going forward you can use awk -v RS='\r' 'script' to change the record separator from it's default \n to \r and then you won't need to do that tr step.

You don't need grep when you're using awk though. This:

grep -ni --color=never -e "error" -e "fail" logfileA.txt |
    awk -F: '{print "Line "$1": "$2}'

can be written as just:

awk 'tolower($0) ~ /error|fail/{print "Line "NR":"$0}' logfileA.txt

but the awk-only version is more robust as it'll correctly display full lines that contain :s where the grep+awk version will truncate them to the first :.

You can handle the DOS line endings, if any, by tweaking the script to:

awk 'tolower($0) ~ /error|fail/{sub(/\r$/,""); print "Line "NR":"$0}' logfileA.txt

and you can make it look for error or fail as standalone words (as opposed to part of other strings like terror or failles) by doing this with GNU awk:

awk -v IGNORECASE=1 -v RS='\r?\n' '/\<(error|fail)\>/{print "Line "NR":"$0}' logfileA.txt

or this with any awk:

awk 'tolower($0) ~ /(^|[^[:alnum:]_])(error|fail)([^[:alnum:]_]|$)/{sub(/\r$/,""); print "Line "NR":"$0}' logfileA.txt


问:
Can you use POST to run a query in Solr (/select)
I have queries that I am running against out solr index that sometimes have very long query parameters, I get errors when i run these queries, which i assume are do to the limit of a GET query parameters.

Here is the method I use to query (JSON), this is to show I am using the Http Extensions (the client i use is a thin wrapper for HttpClient) not an end to end solution.  90% of the queries run fine, it is just when the params are large i get the 500 error from solr.  I have read somewhere you can use POSt's when doing the select command but have not found examples of how to do it.  Any help would be fantastic!

```<code>    public string GetJson(HttpQueryString qs)
    {
        using (var client = new DAC.US.Web.XmlHttpServiceClient(this.Uri))
        {
            client.Client.DefaultHeaders.Authorization = new Microsoft.Http.Headers.Credential("Basic", DAC.US.Encryption.Hash.WebServiceCredintials);
            qs.Add("wt", "json");

            if (!String.IsNullOrEmpty(this.Version))
                qs.Add("version", this.Version);

            using (var response = client.Get(new Uri(@"select/", UriKind.Relative), qs))
            {
                return response.Content.ReadAsString();
            }
        }
    }
</code>```

答:
Yes you can!

Simply post the data to the same path (http://localhost:8983/solr/coreName/select).

Instead of using query string parameters, POST the same data as a JSON body, within a params object key like this:

```<code>{
  "params": {
     "q": "field:value",
     "rows": 10,
     "wt": "json"
  }
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have queries that I am running against out solr index that sometimes have very long query parameters, I get errors when i run these queries, which i assume are do to the limit of a GET query parameters.

Here is the method I use to query (JSON), this is to show I am using the Http Extensions (the client i use is a thin wrapper for HttpClient) not an end to end solution.  90% of the queries run fine, it is just when the params are large i get the 500 error from solr.  I have read somewhere you can use POSt's when doing the select command but have not found examples of how to do it.  Any help would be fantastic!

    public string GetJson(HttpQueryString qs)
    {
        using (var client = new DAC.US.Web.XmlHttpServiceClient(this.Uri))
        {
            client.Client.DefaultHeaders.Authorization = new Microsoft.Http.Headers.Credential("Basic", DAC.US.Encryption.Hash.WebServiceCredintials);
            qs.Add("wt", "json");

            if (!String.IsNullOrEmpty(this.Version))
                qs.Add("version", this.Version);

            using (var response = client.Get(new Uri(@"select/", UriKind.Relative), qs))
            {
                return response.Content.ReadAsString();
            }
        }
    }

Body:
Yes you can!

Simply post the data to the same path (http://localhost:8983/solr/coreName/select).

Instead of using query string parameters, POST the same data as a JSON body, within a params object key like this:

{
  "params": {
     "q": "field:value",
     "rows": 10,
     "wt": "json"
  }
}


问:
Generate DDLs from Hive tables and write each DDLs to a different .txt file
I am trying to learn how to create DDLs for all tables in a given database of Hive automatically.

For example, I have a database named abc_db. I have written a Hive script to write all the tables into a file called abc_db.txt.The output in the file are all the tables inside abc_db line by line.

```<code> `hive -e 'show tables in abc_db' > abc_db.tx`t
</code>```

I want to be able to loop through all of its table and write the DDLs for each table to my directory with their respective table names.

Here is my start:

```<code>hive -e "show tables in abc_db" > d.txt

cat d.txt | while read LINE;
do
  echo "## Table Name:" $LINE
  mkdir $LINE
  cd $LINE
  eval "hive -e 'show create table in $LINE' | grep -v ^$ | grep -v Logging | grep -v tab_name | tee $LINE.tables.txt"
done
</code>```

Given the above information any ideas or starting points on how automatically generate all DDLs from the table and write each DDL to a separate file?

答:
Adapt as needed.  Takes the source schema (processing all tables in the schema) and the output directory as arguments.

Script: gen-ddl

```<code>#!/bin/bash
SCHEMA="$1"
OUTDIR="$2"
if [[ $# -ne 2 ]]; then
  echo "Usage: $0 <schema-name> <out-dir>"
  exit 1
fi
mkdir -p "$OUTDIR"
TABLES=$(hive -e "show tables in $SCHEMA;")
for TABLE in $TABLES; do
  DDL_FILE="$OUTDIR/$TABLE-create-ddl.sql"
  echo -e "Generating DDL ...\n... table: $TABLE\n... file:  $DDL_FILE"
  hive -e "show create table $SCHEMA.$TABLE" > "$DDL_FILE"
done
echo "Done."
</code>```

Usage:

```<code>$ ./gen-ddl <schema-name> <out-dir>
</code>```

Body:
I am trying to learn how to create DDLs for all tables in a given database of Hive automatically.

For example, I have a database named abc_db. I have written a Hive script to write all the tables into a file called abc_db.txt.The output in the file are all the tables inside abc_db line by line.

 `hive -e 'show tables in abc_db' > abc_db.tx`t

I want to be able to loop through all of its table and write the DDLs for each table to my directory with their respective table names.

Here is my start:

hive -e "show tables in abc_db" > d.txt

cat d.txt | while read LINE;
do
  echo "## Table Name:" $LINE
  mkdir $LINE
  cd $LINE
  eval "hive -e 'show create table in $LINE' | grep -v ^$ | grep -v Logging | grep -v tab_name | tee $LINE.tables.txt"
done

Given the above information any ideas or starting points on how automatically generate all DDLs from the table and write each DDL to a separate file?

Body:
Adapt as needed.  Takes the source schema (processing all tables in the schema) and the output directory as arguments.

Script: gen-ddl

#!/bin/bash
SCHEMA="$1"
OUTDIR="$2"
if [[ $# -ne 2 ]]; then
  echo "Usage: $0 <schema-name> <out-dir>"
  exit 1
fi
mkdir -p "$OUTDIR"
TABLES=$(hive -e "show tables in $SCHEMA;")
for TABLE in $TABLES; do
  DDL_FILE="$OUTDIR/$TABLE-create-ddl.sql"
  echo -e "Generating DDL ...\n... table: $TABLE\n... file:  $DDL_FILE"
  hive -e "show create table $SCHEMA.$TABLE" > "$DDL_FILE"
done
echo "Done."

Usage:

$ ./gen-ddl <schema-name> <out-dir>


问:
Mysql Explain shows that query is using index when it shouldnt be according to Mysql doc
I created a mysql multi column index on a transactions table. This index uses 3 columns as described in my rails schema :

```<code>  add_index "merchant_transactions", ["reference", "parent_ref", "kind"], name: "by_reference_parent_ref_kind", using: :btree
</code>```

Now I have this active record query :

```<code>MerchantTransaction.where(reference: "2-9020", kind: "PLACE_BATCH")
</code>```

which in pure sql gives :

```<code>"SELECT `merchant_transactions`.* FROM `merchant_transactions` WHERE `merchant_transactions`.`reference` = '2-9020' AND `merchant_transactions`.`kind` = 'PLACE_BATCH'"
</code>```

Now from what I read about mysql and multi column indexing :

If the table has a multiple-column index, any leftmost prefix of the
  index can be used by the optimizer to look up rows. For example, if
  you have a three-column index on (col1, col2, col3), you have indexed
  search capabilities on (col1), (col1, col2), and (col1, col2, col3).
  For more information, see Section 8.3.5, “Multiple-Column
  Indexes”.

To me, this means that the precedent query shouldnt be using the previous index.

However when I run EXPLAIN on my query MerchantTransaction.where(reference: "2-9020", kind: "PLACE_BATCH").explain under the keycolumn, I get by_reference_parent_ref_kind and under the Extra column I have  Using index condition which seems to imply that the index is actually used.

How is that possible ?

答:
Given

```<code>WHERE reference = '...' AND kind = '...'
</code>```

and

```<code>INDEX(reference, parent, kind)
</code>```

The optimizer can use the index, but only the reference part.

On the other hand, if the only columns mentioned in the query are those three, then that index is "covering", so the Optimizer has another reason to use that index.

Please provide EXPLAIN SELECT ....  In the Key_len column it will hint that only reference is used.  In the Extra column, Using index is the clue that it is "covering".

This would be a better index for the current query, but might be worse for some other query:

```<code>INDEX(reference, kind, parent)
</code>```

Body:
I created a mysql multi column index on a transactions table. This index uses 3 columns as described in my rails schema :

  add_index "merchant_transactions", ["reference", "parent_ref", "kind"], name: "by_reference_parent_ref_kind", using: :btree

Now I have this active record query :

MerchantTransaction.where(reference: "2-9020", kind: "PLACE_BATCH")

which in pure sql gives :

"SELECT `merchant_transactions`.* FROM `merchant_transactions` WHERE `merchant_transactions`.`reference` = '2-9020' AND `merchant_transactions`.`kind` = 'PLACE_BATCH'"

Now from what I read about mysql and multi column indexing :

If the table has a multiple-column index, any leftmost prefix of the
  index can be used by the optimizer to look up rows. For example, if
  you have a three-column index on (col1, col2, col3), you have indexed
  search capabilities on (col1), (col1, col2), and (col1, col2, col3).
  For more information, see Section 8.3.5, “Multiple-Column
  Indexes”.

To me, this means that the precedent query shouldnt be using the previous index.

However when I run EXPLAIN on my query MerchantTransaction.where(reference: "2-9020", kind: "PLACE_BATCH").explain under the keycolumn, I get by_reference_parent_ref_kind and under the Extra column I have  Using index condition which seems to imply that the index is actually used.

How is that possible ?

Body:
Given

WHERE reference = '...' AND kind = '...'

and

INDEX(reference, parent, kind)

The optimizer can use the index, but only the reference part.

On the other hand, if the only columns mentioned in the query are those three, then that index is "covering", so the Optimizer has another reason to use that index.

Please provide EXPLAIN SELECT ....  In the Key_len column it will hint that only reference is used.  In the Extra column, Using index is the clue that it is "covering".

This would be a better index for the current query, but might be worse for some other query:

INDEX(reference, kind, parent)


问:
What is the alternate to npts function of basemap in cartopy?
I want to emulate the function of ntps which is in basemap.Geod class.
Its function is described as follows:

```<code>Given a single initial point and terminus point (specified by
        python floats lon1,lat1 and lon2,lat2), returns a list of
        longitude/latitude pairs describing npts equally spaced
        intermediate points along the geodesic between the initial and
        terminus points.
</code>```

I want to do the same thing in cartopy, aparantly one way is to calculate the distance needed between each pair of successive coordinate and use that distance to compute coordinates from start to end point. Is there any other way to do so?

答:
Based on cartopy's source, https://github.com/SciTools/cartopy/tree/master/lib/cartopy/geodesic
, it is clearly that no equivalent of ntps() function is available from cartopy.

However, it is not difficult to compute locations of points along a geodesic if you know the bearing from one of the end point. Here are steps that you can follow:

Use Geodesic.inverse() with input of (long, lat) of point1 and2, and get (forward_bearing, backward_bearing, geodesic_dist) as the result.

Suppose you want to get (long, lat) of a point (say 1/4 of the whole distance) along that geodesic (in 1), use Geodesic.direct() with long1, lat1, the obtained forward_bearing and geodesic_dist/4.

A better alternative is to use pyproj and forget all the above.

Body:
I want to emulate the function of ntps which is in basemap.Geod class.
Its function is described as follows:

Given a single initial point and terminus point (specified by
        python floats lon1,lat1 and lon2,lat2), returns a list of
        longitude/latitude pairs describing npts equally spaced
        intermediate points along the geodesic between the initial and
        terminus points.

I want to do the same thing in cartopy, aparantly one way is to calculate the distance needed between each pair of successive coordinate and use that distance to compute coordinates from start to end point. Is there any other way to do so?


问:
Getting Redirect_URI to work with Google Oauth in Codename one
I am trying to get Google Oauth working with ios in CNO. I have it working fine with a web app, but I can't quite figure out how to have CNO know when to use which client ID or redirect_URI, etc. Below is my code that works fine. The CNO documentation is no help.

Login gc = GoogleConnect.getInstance();
                gc.setClientId(web_client_ID);
                gc.setRedirectURI("https://google.com");
                gc.setClientSecret(client_secret);
                doLogin(gc, new GoogleData(), false)
```

I have a different Client ID for iOS, but where would I put that? How do I change my RedirectURI when I don't want for the OAuth to go to a website, but back to my app?

答: The client ID is always the native login ID for the device. You can use the isSimulator() method to check if you're running in the simulator to use the web ID.

Body:
I am trying to get Google Oauth working with ios in CNO. I have it working fine with a web app, but I can't quite figure out how to have CNO know when to use which client ID or redirect_URI, etc. Below is my code that works fine. The CNO documentation is no help.

Login gc = GoogleConnect.getInstance();
                gc.setClientId(web_client_ID);
                gc.setRedirectURI("https://google.com");
                gc.setClientSecret(client_secret);
                doLogin(gc, new GoogleData(), false)

I have a different Client ID for iOS, but where would I put that? How do I change my RedirectURI when I don't want for the OAuth to go to a website, but back to my app?


问:
bq cmd query Google Sheet Table occur "Access Denied: BigQuery BigQuery: No OAuth token with Google Drive scope was found" Error
I have a table connect with Google Sheet, use WebUI query this table success, but if I use bq cmd query, It will echo error msg:

Access Denied: BigQuery BigQuery: No OAuth token with Google Drive
  scope was found

答:
Run auth revoke then auth login if only the latter doesn't work.

```<code>gcloud auth revoke
gcloud auth login --enable-gdrive-access
</code>```

Body:
Run auth revoke then auth login if only the latter doesn't work.

gcloud auth revoke
gcloud auth login --enable-gdrive-access


问:
Double border CSS
I have been working on a project and I was able to create a double border css with box shadow... but the problem is I need a transparency on the first box..

I tried something:

* {
  box-sizing: border-box;
}

body {
  display: flex;
  min-height: 100vh;
  justify-content: center;
  align-items: center;
}

.box {
  width: 5rem;
  height: 3rem;
  background-color: #789;
  border: 3px solid black;
  box-shadow: 8px -8px 0 -3px #ccc, 8px -8px 0 0 #000;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="box"></div></code>```

I need http://prntscr.com/nw6fed - the background of the first box should be transparent...Any help

答:
You can get your second border with a pseudo element. I used :after in this example.

.box {
  width: 200px;
  height: 200px;
  border: 3px solid cyan;
  position: relative;
  padding: 40px;
  box-sizing: border-box;
}

.box::after {
  content: '';
  height: 100%;
  width: 100%;
  position: absolute;
  display: block;
  top: 20px;
  left: 20px;
  border: 3px solid magenta;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="box">
  <h1>Text</h1>
</div></code>```

Title: Double border CSS

Body:
I have been working on a project and I was able to create a double border css with box shadow... but the problem is I need a transparency on the first box..

I tried something:

* {
  box-sizing: border-box;
}

body {
  display: flex;
  min-height: 100vh;
  justify-content: center;
  align-items: center;
}

.box {
  width: 5rem;
  height: 3rem;
  background-color: #789;
  border: 3px solid black;
  box-shadow: 8px -8px 0 -3px #ccc, 8px -8px 0 0 #000;
}

I need http://prntscr.com/nw6fed - the background of the first box should be transparent...Any help

Body:
You can get your second border with a pseudo element. I used :after in this example.

.box {
  width: 200px;
  height: 200px;
  border: 3px solid cyan;
  position: relative;
  padding: 40px;
  box-sizing: border-box;
}

.box::after {
  content: '';
  height: 100%;
  width: 100%;
  position: absolute;
  display: block;
  top: 20px;
  left: 20px;
  border: 3px solid magenta;
}

<div class="box">
  <h1>Text</h1>
</div>


问:
Convert columns into group by/counts
I have the below query that displays the result as follows:

How could I get the result displaying like this bearing in mind that more Client Types could be introduced:

```<code>Create Table #temp
(
    [Name] varchar(50),
    Country varchar(50),
    ClientType varchar(50)
)

insert into #temp
(
    Name,
    Country ,
    ClientType
)
select
    'Joe Bloggs',
    'USA',
    'Client Type 1'
union
select
    'John Doe',
    'Canada',
    'Client Type 1'
union
select
    'Jane Smith',
    'USA',
    'Client Type 2'

select
    Country,
    ClientType,
    count(*)
from
    #temp
group by
    Country,
    ClientType

drop table #temp
</code>```

答:
Try with using PIVOT. Below some idea how it should work using PIVOT-</p>

```<code>WITH CTE(Country,ClientType,Count)
AS
(
    SELECT 'Canada','Client Type 1',1 UNION ALL
    SELECT 'USA','Client Type 1',1 UNION ALL
    SELECT 'USA','Client Type 2',1
)

SELECT Country,
ISNULL([Client Type 1],0) [Client Type 1],
ISNULL([Client Type 2],0)  [Client Type 2]
FROM
(
SELECT * FROM CTE
) AS P
PIVOT
(
    SUM(Count)
    FOR ClientType IN ([Client Type 1],[Client Type 2])
)AS PVT
</code>```

Title: Convert columns into group by/counts

Body:
I have the below query that displays the result as follows:

How could I get the result displaying like this bearing in mind that more Client Types could be introduced:

Create Table #temp
(
    [Name] varchar(50),
    Country varchar(50),
    ClientType varchar(50)
)

insert into #temp
(
    Name,
    Country ,
    ClientType
)
select
    'Joe Bloggs',
    'USA',
    'Client Type 1'
union
select
    'John Doe',
    'Canada',
    'Client Type 1'
union
select
    'Jane Smith',
    'USA',
    'Client Type 2'

select
    Country,
    ClientType,
    count(*)
from
    #temp
group by
    Country,
    ClientType

drop table #temp

Body:
Try with using PIVOT. Below some idea how it should work using PIVOT-

WITH CTE(Country,ClientType,Count)
AS
(
    SELECT 'Canada','Client Type 1',1 UNION ALL
    SELECT 'USA','Client Type 1',1 UNION ALL
    SELECT 'USA','Client Type 2',1
)

SELECT Country,
ISNULL([Client Type 1],0) [Client Type 1],
ISNULL([Client Type 2],0)  [Client Type 2]
FROM
(
SELECT * FROM CTE
) AS P
PIVOT
(
    SUM(Count)
    FOR ClientType IN ([Client Type 1],[Client Type 2])
)AS PVT


答:
just you need use PIVOT like this (add to your script before drop #temp) :</p>

```<code>Select * from #temp
Pivot (Count(Name) for
ClientType in ([Client Type 1],[Client Type 2]))
As TablaPivot
</code>```

Title: Convert columns into group by/counts

Body:
just you need use PIVOT like this (add to your script before drop #temp) :

Select * from #temp
Pivot (Count(Name) for
ClientType in ([Client Type 1],[Client Type 2]))
As TablaPivot


问:
LocationManager in Service - need to stop if no fix in 1 minute
I have regular service that I start using alarms every 5 minutes.
Service Implements LocationListener to get GPS fix and save it into SqLite database.

I give service 1 minute to get best fix possible. If I get accuracy <20 before that - even better.

All that works fine. I also have code that checks if GPS disabled so I exit service.

What I want to do is: If there is no fix within 1 minute - I want to exit service. Currently since most logic (time checks, etc) is in onLocationChanged - I never have chance to do so because I never get location.

Is there timer or something like that I can use? I'm new to Java, example would be nice. I see it like this: On start I create timer with callback and in this callback function I will cleanup and shutdown. I'm not sure if there going to be any implications with possible onLocationChanged running?

Can I possibly disable timer as soon as I get onLocationChanged?

答:
You could schedule a timeout using Timer and TimerTask as follows...

Declare a global Timer object reference in your Service:

```<code>Timer timeout = null;
</code>```

In onStartCommand(), instantiate this Timer and schedule a TimerTask to execute in one minute. Do this after you've registered for location updates from the desired provider:

```<code>timeout = new Timer();
timeout.schedule(timeoutTask, 60000);
</code>```

Define timeoutTask somewhere in your Service class e.g:

```<code>private TimerTask timeoutTask = new TimerTask() {
    public void run() {
        // Handle timeouts here
    }
}
</code>```

If you get a callback via onLocationChanged() before the Timer expires, you'll want to stop timeoutTask from being executed, so inside onLocationChanged():

```<code>if(timeout != null) {
    timeout.cancel()
}
</code>```

Then just handle your location inside onLocationChanged() as normal, or call another method to do it, up to you.

There are probably better ways to do it, but this is straightforward and has worked for me on my project :) Hope it helps you too.

All the best,
Declan

Body:
You could schedule a timeout using Timer and TimerTask as follows...

Declare a global Timer object reference in your Service:

Timer timeout = null;

In onStartCommand(), instantiate this Timer and schedule a TimerTask to execute in one minute. Do this after you've registered for location updates from the desired provider:

timeout = new Timer();
timeout.schedule(timeoutTask, 60000);

Define timeoutTask somewhere in your Service class e.g:

private TimerTask timeoutTask = new TimerTask() {
    public void run() {
        // Handle timeouts here
    }
}

If you get a callback via onLocationChanged() before the Timer expires, you'll want to stop timeoutTask from being executed, so inside onLocationChanged():

if(timeout != null) {
    timeout.cancel()
}

Then just handle your location inside onLocationChanged() as normal, or call another method to do it, up to you.

There are probably better ways to do it, but this is straightforward and has worked for me on my project :) Hope it helps you too.

All the best,
Declan


问:
issues with array.concat()
I'm trying to use a recursive call to concat a return array

Directions to this problem are:
A stream of data is received and needs to be reversed.

Each segment is 8 bits long, meaning the order of these segments needs to be reversed, for example:

11111111  00000000  00001111  10101010
 (byte1)   (byte2)   (byte3)   (byte4)
should become:

10101010  00001111  00000000  11111111
 (byte4)   (byte3)   (byte2)   (byte1)
The total number of bits will always be a multiple of 8.

trying different combinations of things really...

function dataReverse(data) {
  //split incoming array into array values consisting of 8 numbers each.
  //var octGroups = data.length / 8;
  var result = [];
  //recursive call
  function shuffler(array){
    let input = array;
    //base case
    if(input.length === 0){
      return result;
    } else {
      //concat result with 8 values at a time
      let cache = input.splice(-8,8);
      result.concat(cache);
      return shuffler(input);
    }
    return result;
  }

  var reversed = shuffler(data);
//base case is if data.length === 0 return result else
//reverse iterate through array, concating to new return array
//return result
  return reversed;
}

console.log(dataReverse([1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,0,1,0,1,0,1,0]));```

it is expected to reverse through the input array, concating a result array with 8 values at a time starting at the end, but not reversing the order of the numbers.

My attempt above returns a zero length array. What have I done wrong?

答:
You can chunk the array by 8 pieces each and then just use Array.reverse and Array.flat. The benefit of this is that you get a nice functional, reusable, chain-able and very readable code.

Consider this:

let data = [1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,0,1,0,1,0,1,0]

// utility function to chunk array by number
const chunkBy = (arr, by=2) => arr.reduce((r,c,i) => (i%by==0 ? r.push([c]) : r[r.length-1] = [...r[r.length-1], c], r), [])

let result = chunkBy(data, 8).reverse().flat()

console.log('in:  ', data.join(''))
console.log('out: ', result.join(''))```
</div>
</div>
</p>

<p>Here is the <code>chunkBy</code> function in more readable form:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let data = [1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,0,1,0,1,0,1,0]

const chunkBy = (arr, by=2) => // default to chunks of 2
  arr.reduce((acc, cur, index) => {
    if(index % by == 0)        // use modulo to check for the remainder
      acc.push([cur])          // if exact then we start a new chunk
    else                       // if not we keep adding to the previous chunk
      acc[acc.length-1] = [...acc[acc.length-1], cur]
    return acc
}, [])

console.log(chunkBy(data, 8))</code>```

If you are using lodash _.chunk is already there:

let data = [1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,0,1,0,1,0,1,0]

let result = _(data)
  .chunk(8)
  .reverse()
  .flatten()
  .value()

console.log(result.join(''))```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script></code>```

Title: issues with array.concat()

Body:
I'm trying to use a recursive call to concat a return array

Directions to this problem are:
A stream of data is received and needs to be reversed.

Each segment is 8 bits long, meaning the order of these segments needs to be reversed, for example:

11111111  00000000  00001111  10101010
 (byte1)   (byte2)   (byte3)   (byte4)
should become:

10101010  00001111  00000000  11111111
 (byte4)   (byte3)   (byte2)   (byte1)
The total number of bits will always be a multiple of 8.

trying different combinations of things really...

function dataReverse(data) {
  //split incoming array into array values consisting of 8 numbers each.
  //var octGroups = data.length / 8;
  var result = [];
  //recursive call
  function shuffler(array){
    let input = array;
    //base case
    if(input.length === 0){
      return result;
    } else {
      //concat result with 8 values at a time
      let cache = input.splice(-8,8);
      result.concat(cache);
      return shuffler(input);
    }
    return result;
  }

  var reversed = shuffler(data);
//base case is if data.length === 0 return result else
//reverse iterate through array, concating to new return array
//return result
  return reversed;
}

console.log(dataReverse([1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,0,1,0,1,0,1,0]));

it is expected to reverse through the input array, concating a result array with 8 values at a time starting at the end, but not reversing the order of the numbers.

My attempt above returns a zero length array. What have I done wrong?

Body:
You can chunk the array by 8 pieces each and then just use Array.reverse and Array.flat. The benefit of this is that you get a nice functional, reusable, chain-able and very readable code.

Consider this:

let data = [1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,0,1,0,1,0,1,0]

// utility function to chunk array by number
const chunkBy = (arr, by=2) => arr.reduce((r,c,i) => (i%by==0 ? r.push([c]) : r[r.length-1] = [...r[r.length-1], c], r), [])

let result = chunkBy(data, 8).reverse().flat()

console.log('in:  ', data.join(''))
console.log('out: ', result.join(''))

Here is the chunkBy function in more readable form:

let data = [1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,0,1,0,1,0,1,0]

const chunkBy = (arr, by=2) => // default to chunks of 2
  arr.reduce((acc, cur, index) => {
    if(index % by == 0)        // use modulo to check for the remainder
      acc.push([cur])          // if exact then we start a new chunk
    else                       // if not we keep adding to the previous chunk
      acc[acc.length-1] = [...acc[acc.length-1], cur]
    return acc
}, [])

console.log(chunkBy(data, 8))

If you are using lodash _.chunk is already there:

let data = [1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,0,1,0,1,0,1,0]

let result = _(data)
  .chunk(8)
  .reverse()
  .flatten()
  .value()

console.log(result.join(''))

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>


问:
Mongodb Atlas: not authorized on admin to execute command
I have a MongoDB Atlas cluster within which I am trying to simply copy a database within the same instance. Unfortunately, every time I try to run db.copyDatabase() or copydb admin command, I get the following error:

```<code>not authorized on admin to execute command
</code>```

Which is very strange, because I just have one user, and it has access to everything, at least as far as I can tell on atlas:

I did some search in stackoverflow, but it looked like most of the answers pertain to mongod instances running locally, and not ones running in atlas... Did I setup the user wrong?

答: In case you have been using mongoose, I solved a similar error updating mongoose to latest version (based on this post).</p>

Body:
I have a MongoDB Atlas cluster within which I am trying to simply copy a database within the same instance. Unfortunately, every time I try to run db.copyDatabase() or copydb admin command, I get the following error:

not authorized on admin to execute command

Which is very strange, because I just have one user, and it has access to everything, at least as far as I can tell on atlas:

I did some search in stackoverflow, but it looked like most of the answers pertain to mongod instances running locally, and not ones running in atlas... Did I setup the user wrong?


问:
How to add waits in-between pictures
I want to make two pictures that go on top of each other after I press the 'w' key to create a walking animation:

```<code>#Imports
import turtle
import time

#Registers Gifs
turtle.register_shape("ZeldaBackToolless1.gif")
turtle.register_shape("ZeldaBackToolless2.gif")

Zelda = turtle.Turtle()
Zelda.penup()

def move_up():
    if Waiting == True:
        time.sleep(.2)
        Zelda.shape("ZeldaBackToolless1.gif")
        Waiting = False
    else:
        time.sleep(.2)
        Zelda.shape("ZeldaBackToolless2.gif")
        Waiting = True

turtle.listen()
turtle.onkeypress(move_up, "w")
</code>```

If there's a way to make a boolean statement in the move_up() function with the boolean statement saving which state it was previously at, that would work great, I think.

答:
I feel that both your solution, and that of @Prune, are ill-considered.  By using time.sleep() you're blocking other turtle events.  If this is eventually intended as a wait image, then the last thing you want to do is block the thing you're waiting on.  This really should instead be done with timer events:

```<code>from turtle import Screen, Turtle

def walk():
    screen.onkeypress(None, "w")  # disable handler in handler

    def stop_walk():
        zelda.shape("image_2.gif")

        screen.onkeypress(walk, "w")  # restore event handler

    zelda.shape("image_1.gif")

    screen.ontimer(stop_walk, 200)  # in the future, in milliseconds

screen = Screen()

# Registers Gifs
screen.register_shape("image_1.gif")
screen.register_shape("image_2.gif")

zelda = Turtle()
zelda.penup()

screen.onkeypress(walk, "w")

screen.listen()
screen.mainloop()
</code>```

This will allow other turtle events to continue during the waiting period.

Title: How to add waits in-between pictures

Body:
I want to make two pictures that go on top of each other after I press the 'w' key to create a walking animation:

#Imports
import turtle
import time

#Registers Gifs
turtle.register_shape("ZeldaBackToolless1.gif")
turtle.register_shape("ZeldaBackToolless2.gif")

Zelda = turtle.Turtle()
Zelda.penup()

def move_up():
    if Waiting == True:
        time.sleep(.2)
        Zelda.shape("ZeldaBackToolless1.gif")
        Waiting = False
    else:
        time.sleep(.2)
        Zelda.shape("ZeldaBackToolless2.gif")
        Waiting = True

turtle.listen()
turtle.onkeypress(move_up, "w")

If there's a way to make a boolean statement in the move_up() function with the boolean statement saving which state it was previously at, that would work great, I think.

Body:
I feel that both your solution, and that of @Prune, are ill-considered.  By using time.sleep() you're blocking other turtle events.  If this is eventually intended as a wait image, then the last thing you want to do is block the thing you're waiting on.  This really should instead be done with timer events:

from turtle import Screen, Turtle

def walk():
    screen.onkeypress(None, "w")  # disable handler in handler

    def stop_walk():
        zelda.shape("image_2.gif")

        screen.onkeypress(walk, "w")  # restore event handler

    zelda.shape("image_1.gif")

    screen.ontimer(stop_walk, 200)  # in the future, in milliseconds

screen = Screen()

# Registers Gifs
screen.register_shape("image_1.gif")
screen.register_shape("image_2.gif")

zelda = Turtle()
zelda.penup()

screen.onkeypress(walk, "w")

screen.listen()
screen.mainloop()

This will allow other turtle events to continue during the waiting period.


问:
can I distinguish between a string literal argument and a parameter which evaluates to a string?
I'm creating a domain-specific language. One of the macro calls looks something like this:

(my-macro foo (bar "baz" qux) yay)

With the way I've written my-macro, the second argument here is supposed to be a list of strings inside a pair of parentheses. So my-macro works as long as bar and qux evaluate to strings. Let's just say they evaluate eponymously to "bar" and "qux" and my-macro treats the second argument as "bar baz qux".

But now I've realized that I really want "baz" to retain its quotes; I want my-macro to treat the second argument as "bar \"baz\" qux". Is this possible? Inside my-macro, can I tell when I  can just use a string as-is vs when I need to add back the double quotes?

Thanks in advance!

答:
To treat the second argument as a string  "bar \"baz\" qux" you can simply write it to a string, as in:

```<code>(defmacro my-macro (arg1 (&rest arg2) arg3)
  (list arg1 (write-to-string arg2 :case :downcase) arg3))

(macroexpand '(my-macro foo (bar "baz" qux) yay))
</code>```

=> (FOO "(bar \"baz\" qux)" YAY)

Body:
To treat the second argument as a string  "bar \"baz\" qux" you can simply write it to a string, as in:

(defmacro my-macro (arg1 (&rest arg2) arg3)
  (list arg1 (write-to-string arg2 :case :downcase) arg3))

(macroexpand '(my-macro foo (bar "baz" qux) yay))

=> (FOO "(bar \"baz\" qux)" YAY)


问:
how to gather elements of specific indices in numpy?
I want to gather elements of specified indices in specified axis like following. </p>

```<code>x = [[1,2,3], [4,5,6]]
index = [[2,1], [0, 1]]
x[:, index] = [[3, 2], [4, 5]]
</code>```

<p>This is essentially gather operation in pytorch, but as you know, this is not achievable in numpy this way. I am wondering if there is such a "gather" operation in numpy? </p>

答: Use numpy.take() function which has most of PyTorch's gather function functionalities.</p>

Body:
I want to gather elements of specified indices in specified axis like following.

x = [[1,2,3], [4,5,6]]
index = [[2,1], [0, 1]]
x[:, index] = [[3, 2], [4, 5]]

This is essentially gather operation in pytorch, but as you know, this is not achievable in numpy this way. I am wondering if there is such a "gather" operation in numpy?


问:
Getting react-datepicker to appear correctly when using react-testing-library
I've been trying to figure out how to get react-testing-library working with react-datepicker.

So far, I've been able to get the input box wrapped correctly, and can access it via the getByLabelText function, but I can't seem to get the date picker to appear no matter what event I fire on the textbox.

I've been able to use the base Enzyme method for getting the date picker to appear, but it doesn't seem to want to work through react-testing-library.
Here is a working version of the issue that I'm facing: https://codesandbox.io/s/compassionate-bose-8gpbt

答:
I don't think getByLabelText will work since the input from react-datepicker is nested within a div (which doesn't match any of the example usages in react-testing-library).

The best I could do was target the From: text using getByText and then look for this month/year to be in the document: https://codesandbox.io/s/sleepy-neumann-hnpr5


问:
When Using Order By Clause the Execution time is 40 Times high
I have a table with 200,000 records that I'm trying to filter and sort with some conditions.

Without ORDER BY p.date_time desc, the query takes 0.078 seconds.

With ORDER BY p.date_time desc it takes 2.225 seconds

Query:

```<code>SELECT p.*
        , s.*
        ,  (SELECT  COUNT(1)
            FROM    gbs_comments
            WHERE   product_short_url = p.product_short_url
        ) AS comment_count
        ,( EXISTS
            ( SELECT *
              FROM  `gbs_likes`
              WHERE `product_short_url` = p.product_short_url
              AND `ip_address` = '1'
             )
        ) AS like_status
FROM   gbs_products p, gbs_store s
WHERE  p.deal_type = 1
  AND  p.product_store = s.sid
ORDER BY p.date_time DESC
</code>```

Table Indexes:

Explain Plan:

Table Indexes:

GBS_COMMENTS

GBS_LIKES INDEX

GBS PRODUCT INDEX

答:
gbs_comments needs INDEX(product_short_url)

gbs_likes needs INDEX(ip_address, product_short_url), in either order.

gbs_products needs INDEX(deal_type, date_time), in this order.

Body:
I have a table with 200,000 records that I'm trying to filter and sort with some conditions.

Without ORDER BY p.date_time desc, the query takes 0.078 seconds.

With ORDER BY p.date_time desc it takes 2.225 seconds

Query:

SELECT p.*
        , s.*
        ,  (SELECT  COUNT(1)
            FROM    gbs_comments
            WHERE   product_short_url = p.product_short_url
        ) AS comment_count
        ,( EXISTS
            ( SELECT *
              FROM  `gbs_likes`
              WHERE `product_short_url` = p.product_short_url
              AND `ip_address` = '1'
             )
        ) AS like_status
FROM   gbs_products p, gbs_store s
WHERE  p.deal_type = 1
  AND  p.product_store = s.sid
ORDER BY p.date_time DESC

Table Indexes:

Explain Plan:

Table Indexes:

GBS_COMMENTS

GBS_LIKES INDEX

GBS PRODUCT INDEX


问:
How do I properly hook Interrupt 28h in assembly for DOS, and restore it?
I'm trying to set the handler of Interrupt 28h to my own routine, restore all the registers and flags involved, and restore the original Interrupt handler.
I'm using NASM Assembler, under DOSBox and MS-DOS 6.22 in VirtualBox.

I've thought about debugging, but doing so on a TSR program sounds impossible. I've tried pushing the Data Segment onto the Code Segment, and saving the original Data Segment for restoring later, but it seems to hang the machine even after restoring the Data Segment.

```<code>section .text   ;Code Section
org 100h        ;DOS Executable Start
mov ah,35h      ;Get Interrupt Vector
mov al,28h      ;Of Interrupt 28h
int 21h         ;Call DOS Kernel
push cs         ;Push Code Segment
pop ds          ;Onto Data Segment
mov [oldseg],es ;Save Old Interrupt Vector Segment
mov [oldoff],bx ;Save Old Interrupt Vector Offset
mov ah,25h      ;Set Interrupt Vector
mov dx,resstart ;To Resstart
int 21h         ;Call DOS Kernel
mov dx,resend   ;Set Data Offset to Resend
sub dx,resstart ;Subtract Resstart
shr dx,4h       ;Shift Right 4 Bits for Paragraph
inc dx          ;One Extra Paragraph for PSP
mov ah,31h      ;Terminate and Stay Resident
xor al,al       ;Return Code
int 21h         ;Call DOS Kernel

resstart:       ;Resident Code Start
push ax         ;Save AX
push es         ;Save ES
push di         ;Save DI
push cx         ;Save CX
push ds         ;Save DS
push dx         ;Save DX
mov ah,00h      ;Set Video Mode
mov al,13h      ;To Mode 13h
int 10h         ;Call BIOS Video
mov ax,0A000h   ;VGA Segment
mov es,ax       ;Stored in ES
xor di,di       ;VGA Offset in DI
mov cx,0FA00h   ;Fill Entire Screen
mov al,09h      ;With Light Blue Color
rep stosb       ;Repeat Store AL at ES:DI
mov ah,25h      ;Set Interrupt Vector
mov al,28h      ;Of Interrupt 28h
mov ds,[oldseg] ;Restore Old Interrupt Vector Segment
mov dx,[oldoff] ;Restore Old Interrupt Vector Offset
int 21h         ;Call DOS Kernel
pop dx          ;Restore DX
pop ds          ;Restore DS
pop cx          ;Restore CX
pop di          ;Restore DI
pop es          ;Restore ES
pop ax          ;Restore AX
iret            ;Return and Restore Flags
resend:         ;Resident Code End

section .data
oldseg dw 0     ;Old Interrupt Vector Segment
oldoff dw 0     ;Old Interrupt Vector Offset
</code>```

After returning the original interrupt vector address, and setting the new interrupt vector address to "resstart", the program should terminate and stay resident. After this, Interrupt 28h would be triggered automatically since DOS has nothing else to do, which would in turn run my Interrupt handler.

The Interrupt handler sets the video mode to 13h, tries to fill the entire screen with a light blue color, restores the original Interrupt 28h handler, restores all registers and flags involved, and returns to DOS. Executing this program yields no results, the system doesn't even hang. While running the part of setting video mode 13h and filling the entire screen with blue on its own separately, it works perfectly fine.

答:
There are multiple problems in your program:

Problem 1

```<code>push cs ;Push Code Segment
pop ds ;Onto Data Segment
mov [oldseg],es ;Save Old Interrupt Vector Segment
mov [oldoff],bx ;Save Old Interrupt Vector Offset
...
mov ds,[oldseg] ;Restore Old Interrupt Vector Segment
mov dx,[oldoff] ;Restore Old Interrupt Vector Offset
</code>```

The four mov instructions assume that the ds register points to the .data section.

However, in the case of the first two mov instructions ds will point to the .text section, not to the .data section because of the push cs - pop ds sequence.

In the case of a .COM file .text and .data section are typically the same; however in .EXE files they are normally not the same.

In the case of the third mov instruction it is very improbable that ds points to any section that is related to your program. And in the case of the fourth one it is nearly impossible because the third mov instruction changed the ds register.

A solution would be to use the .text segment to store data. This is possible in "real-mode" operating systems (such as MS-DOS), but not in "protected-mode" operating systems (such as Windows):

Place the two dw 0 lines (eg. oldseg dw 0) before the section .data line. Now the four bytes of data storage are located in the same section as your code. Then you can access the data the following way:

```<code> push cs
 pop ds
 mov [oldseg],es ;We know that ds=cs, so no "cs:" is required here
 ...
 mov ds,cs:[oldseg] ;Restore Old Interrupt Vector Segment
 mov dx,cs:[oldoff] ;Restore Old Interrupt Vector Offset
</code>```

The "cs:" will tell the CPU that the data you access is located in the section cs points to; and cs always points to the section containing the code currently being executed. And this is the .text section.

Please note that the correct syntax (the location of the letters "cs:" in the line) differs from assembler to assembler:

```<code> mov dx,cs:[oldoff]
 cs:mov dx,[oldoff]
 mov dx,[cs:oldoff]
</code>```

Maybe your assembler uses another syntax.

Problem 2

```<code>mov ah,25h ;Set Interrupt Vector
mov al,28h ;Of Interrupt 28h
mov ds,[oldseg] ;Restore Old Interrupt Vector Segment
mov dx,[oldoff] ;Restore Old Interrupt Vector Offset
int 21h ;Call DOS Kernel
</code>```

Calling int 21h from inside int 21h (and int 28h is called from inside int 21h) is also not a good idea.

However, function 25h will do nothing but writing 4 bytes of data to the interrupt vector table (while the interrupts are disabled using cli):

You may do this directly by simply storing the offset to address 0:0A0h and the segment to address 0:0A2h:

```<code>mov ax,0      ;You might also use "xor ax,ax" or "sub ax,ax"
mov ds,ax     ;Now ds=0
mov ax,cs:[oldseg]
mov dx,cs:[oldoff]
cli           ;Disable the interrupts
mov [0A0h],dx ;Write dx to ds:0A0h which is 0:0A0h
mov [0A2h],ax ;Write ax to ds:0A2h which is 0:0A2h
</code>```

The cli is there to ensure that no hardware interrupt can happen between the two instructions mov [0A0h],dx and mov [0A2h],ax.

If you can ensure that int 28h is not called from a hardware interrupt, you do not need to do this.

The iret instruction will automatically restore the old state of the interrupts (enabled or disabled).

Problem 3

Calling complex functions (such as int 10h) from the int 28h interrupt seems also not to be the best idea.

Body:
I'm trying to set the handler of Interrupt 28h to my own routine, restore all the registers and flags involved, and restore the original Interrupt handler.
I'm using NASM Assembler, under DOSBox and MS-DOS 6.22 in VirtualBox.

I've thought about debugging, but doing so on a TSR program sounds impossible. I've tried pushing the Data Segment onto the Code Segment, and saving the original Data Segment for restoring later, but it seems to hang the machine even after restoring the Data Segment.

section .text   ;Code Section
org 100h        ;DOS Executable Start
mov ah,35h      ;Get Interrupt Vector
mov al,28h      ;Of Interrupt 28h
int 21h         ;Call DOS Kernel
push cs         ;Push Code Segment
pop ds          ;Onto Data Segment
mov [oldseg],es ;Save Old Interrupt Vector Segment
mov [oldoff],bx ;Save Old Interrupt Vector Offset
mov ah,25h      ;Set Interrupt Vector
mov dx,resstart ;To Resstart
int 21h         ;Call DOS Kernel
mov dx,resend   ;Set Data Offset to Resend
sub dx,resstart ;Subtract Resstart
shr dx,4h       ;Shift Right 4 Bits for Paragraph
inc dx          ;One Extra Paragraph for PSP
mov ah,31h      ;Terminate and Stay Resident
xor al,al       ;Return Code
int 21h         ;Call DOS Kernel

resstart:       ;Resident Code Start
push ax         ;Save AX
push es         ;Save ES
push di         ;Save DI
push cx         ;Save CX
push ds         ;Save DS
push dx         ;Save DX
mov ah,00h      ;Set Video Mode
mov al,13h      ;To Mode 13h
int 10h         ;Call BIOS Video
mov ax,0A000h   ;VGA Segment
mov es,ax       ;Stored in ES
xor di,di       ;VGA Offset in DI
mov cx,0FA00h   ;Fill Entire Screen
mov al,09h      ;With Light Blue Color
rep stosb       ;Repeat Store AL at ES:DI
mov ah,25h      ;Set Interrupt Vector
mov al,28h      ;Of Interrupt 28h
mov ds,[oldseg] ;Restore Old Interrupt Vector Segment
mov dx,[oldoff] ;Restore Old Interrupt Vector Offset
int 21h         ;Call DOS Kernel
pop dx          ;Restore DX
pop ds          ;Restore DS
pop cx          ;Restore CX
pop di          ;Restore DI
pop es          ;Restore ES
pop ax          ;Restore AX
iret            ;Return and Restore Flags
resend:         ;Resident Code End

section .data
oldseg dw 0     ;Old Interrupt Vector Segment
oldoff dw 0     ;Old Interrupt Vector Offset

After returning the original interrupt vector address, and setting the new interrupt vector address to "resstart", the program should terminate and stay resident. After this, Interrupt 28h would be triggered automatically since DOS has nothing else to do, which would in turn run my Interrupt handler.

The Interrupt handler sets the video mode to 13h, tries to fill the entire screen with a light blue color, restores the original Interrupt 28h handler, restores all registers and flags involved, and returns to DOS. Executing this program yields no results, the system doesn't even hang. While running the part of setting video mode 13h and filling the entire screen with blue on its own separately, it works perfectly fine.

Body:
There are multiple problems in your program:

Problem 1

push cs ;Push Code Segment
pop ds ;Onto Data Segment
mov [oldseg],es ;Save Old Interrupt Vector Segment
mov [oldoff],bx ;Save Old Interrupt Vector Offset
...
mov ds,[oldseg] ;Restore Old Interrupt Vector Segment
mov dx,[oldoff] ;Restore Old Interrupt Vector Offset

The four mov instructions assume that the ds register points to the .data section.

However, in the case of the first two mov instructions ds will point to the .text section, not to the .data section because of the push cs - pop ds sequence.

In the case of a .COM file .text and .data section are typically the same; however in .EXE files they are normally not the same.

In the case of the third mov instruction it is very improbable that ds points to any section that is related to your program. And in the case of the fourth one it is nearly impossible because the third mov instruction changed the ds register.

A solution would be to use the .text segment to store data. This is possible in "real-mode" operating systems (such as MS-DOS), but not in "protected-mode" operating systems (such as Windows):

Place the two dw 0 lines (eg. oldseg dw 0) before the section .data line. Now the four bytes of data storage are located in the same section as your code. Then you can access the data the following way:

 push cs
 pop ds
 mov [oldseg],es ;We know that ds=cs, so no "cs:" is required here
 ...
 mov ds,cs:[oldseg] ;Restore Old Interrupt Vector Segment
 mov dx,cs:[oldoff] ;Restore Old Interrupt Vector Offset

The "cs:" will tell the CPU that the data you access is located in the section cs points to; and cs always points to the section containing the code currently being executed. And this is the .text section.

Please note that the correct syntax (the location of the letters "cs:" in the line) differs from assembler to assembler:

 mov dx,cs:[oldoff]
 cs:mov dx,[oldoff]
 mov dx,[cs:oldoff]

Maybe your assembler uses another syntax.

Problem 2

mov ah,25h ;Set Interrupt Vector
mov al,28h ;Of Interrupt 28h
mov ds,[oldseg] ;Restore Old Interrupt Vector Segment
mov dx,[oldoff] ;Restore Old Interrupt Vector Offset
int 21h ;Call DOS Kernel

Calling int 21h from inside int 21h (and int 28h is called from inside int 21h) is also not a good idea.

However, function 25h will do nothing but writing 4 bytes of data to the interrupt vector table (while the interrupts are disabled using cli):

You may do this directly by simply storing the offset to address 0:0A0h and the segment to address 0:0A2h:

mov ax,0      ;You might also use "xor ax,ax" or "sub ax,ax"
mov ds,ax     ;Now ds=0
mov ax,cs:[oldseg]
mov dx,cs:[oldoff]
cli           ;Disable the interrupts
mov [0A0h],dx ;Write dx to ds:0A0h which is 0:0A0h
mov [0A2h],ax ;Write ax to ds:0A2h which is 0:0A2h

The cli is there to ensure that no hardware interrupt can happen between the two instructions mov [0A0h],dx and mov [0A2h],ax.

If you can ensure that int 28h is not called from a hardware interrupt, you do not need to do this.

The iret instruction will automatically restore the old state of the interrupts (enabled or disabled).

Problem 3

Calling complex functions (such as int 10h) from the int 28h interrupt seems also not to be the best idea.


问:
A PHP function that adds # hashtag to an array of words
I'm trying to write a function that adds the sign # to an array of words in a string

Given I can use the str_replace for each one of them but my array is getting bigger and it's not efficient.

$needles = array('a', 'c', 'd');
$haystack = 'a b c d e f g';
    foreach($needles as $what) {
        if(strpos($haystack, $what)!==false) {
     $haystack = str_replace($needles, '#'.$what.'-', $haystack);
    }
    }
echo $haystack;
```

The array here is needles a c d in a haystack of  a b c d e f g
I'm trying to make them #a #b #c so that the result would be  #a b #c #d e f g

答:
You are using wrong this str_replace() function
Read more about this function here str_replace function

```<code>$needles = array('a', 'c', 'd');
$haystack = 'a b c d e f g';

    foreach($needles as $key) {
        if(strpos($haystack, $key)!==false) {
     $haystack = str_replace($key, '#'.$key, $haystack);
    }
    }
echo $haystack;
</code>```

Output

```<code>#a b #c #d e f g
</code>```

Hope this will help you

Body:
I'm trying to write a function that adds the sign # to an array of words in a string

Given I can use the str_replace for each one of them but my array is getting bigger and it's not efficient.

$needles = array('a', 'c', 'd');
$haystack = 'a b c d e f g';
    foreach($needles as $what) {
        if(strpos($haystack, $what)!==false) {
     $haystack = str_replace($needles, '#'.$what.'-', $haystack);
    }
    }
echo $haystack;

The array here is needles a c d in a haystack of  a b c d e f g
I'm trying to make them #a #b #c so that the result would be  #a b #c #d e f g

Body:
You are using wrong this str_replace() function
Read more about this function here str_replace function

$needles = array('a', 'c', 'd');
$haystack = 'a b c d e f g';

    foreach($needles as $key) {
        if(strpos($haystack, $key)!==false) {
     $haystack = str_replace($key, '#'.$key, $haystack);
    }
    }
echo $haystack;

Output

#a b #c #d e f g

Hope this will help you


问:
symlink breaking after git pull
I keep my .vimrc file in a git repository since I use it on multiple computers. I don't believe there is a way to change the default location of .vimrc, so I keep it at ~/dotfile/.vimrc. I created a symbolic link between these with ln ~/dotfiles/.vimrc ~/.vimrc, which I then confirmed worked with ls -i ~/.vimrc which shows 12345 /Users/TheStrangeQuark/.vimrc and then ls -i ~/dotfiles/vimrc which shows 12345 /Users/TheStrangeQuark/dotfiles/.vimrc.

Now, I pull the latest version of my .vimrc while in ~/dotfiles. Now, the symbolic link is broken, which I can confirm by seeing different inode numbers from ls -i for the two files. I also can see that ~/.vimrc is not the updated version from my git pull.

Is there a way to make it so my git pull won't break this symbolic link?

I am running MacOS Majave if that helps.

答:
As mentioned in "Git and hard links", hard links cannot be represented in git, at least not without third party tools, or a post-merge hook.

This differs from soft link (ln -s), which are stored as a file pointing to the destination.

See also "What is the difference between a hard link and a symbolic link?".

Title: symlink breaking after git pull


问:
What is the issue with my code? How do I deal with this error?
I am unable to comprehend why I am getting this error from the code below. Thanks for your time!

```<code>import sys, os, argparse
from collections import defaultdict
from itertools import izip

parser = argparse.ArgumentParser()
parser.add_argument("--data_loc", type=str, help="folder of training data")
parser.add_argument("--out_loc", type=str, help="location to write files")
parser.add_argument("--n", type=int, default=10000, help="top n chunks get saved")
parser.add_argument("--char", action="store_true", help="char or nah")
args = parser.parse_args()

data_loc = sys.argv[1]
out_loc = sys.argv[2]
</code>```

Error message:

```<code>Traceback (most recent call last):
  File "make_chunk_vocab.py", line 12, in <module>
    data_loc = sys.argv[1]
</code>```

答: Do you have 2 arguments? Debug and see what sys.argv contains before accessing it. </p>

Body:
I am unable to comprehend why I am getting this error from the code below. Thanks for your time!

import sys, os, argparse
from collections import defaultdict
from itertools import izip

parser = argparse.ArgumentParser()
parser.add_argument("--data_loc", type=str, help="folder of training data")
parser.add_argument("--out_loc", type=str, help="location to write files")
parser.add_argument("--n", type=int, default=10000, help="top n chunks get saved")
parser.add_argument("--char", action="store_true", help="char or nah")
args = parser.parse_args()

data_loc = sys.argv[1]
out_loc = sys.argv[2]

Error message:

Traceback (most recent call last):
  File "make_chunk_vocab.py", line 12, in <module>
    data_loc = sys.argv[1]


问:
Fetch post api from React Client to express server causes error
I'm trying to send user id and password in React frontend (running on localhost:8080) to express backend server(running on localhost:5000) using post method, but when I click button for submit it says cannot Post /login

Below is my code

```<code>import React, { Component } from 'react';
//import'whatwg-fetch';

function postSend(url, data) {
  return fetch(url, {
    credentials: 'same-origin',
    mode: 'cors',
    method: 'POST', // 'GET', 'PUT', 'DELETE', etc.
    body: JSON.stringify(data), // Coordinate the body type with 'Content-Type'
    headers: new Headers({
      'Content-Type': 'application/json',
      'Accept': 'application/json'
    }),
  }).then((res) => res.json())
  .then((result) => console.log(result))
  .catch((error) =>{
    console.error(error, 'postRequest error');
  })
};

class Signup extends Component {
  constructor(props){
    super(props);
    this.state = { id: "", password: ""}
  }
  componentDidMount() {
    const API = 'http://localhost:8080/';
    const DEFAULT_QUERY = 'routes';
    fetch(API + DEFAULT_QUERY, {
  headers : {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
   },
   mode: 'cors'

  }).then(response => response.json())
    .then(data => this.setState({ data }))
    .catch(function(err) {console.log(err)});
}

  handleChange = event => {
    this.setState({ [event.target.name] : event.target.value });
  };
  handleSubmit(event) {
    event.preventDefault();
    postSend('http://localhost:5000/login', this.state);

  }
    render() {
        return ( <div>

            <h1>Welcome to Secret Admirer</h1>
            <form action = "/login" method = "POST"  > <hr/>
                <label>Enter Your Credentials to sign up</label>
                <div className ="form-group">
                <p>user id:
                <input  type="text" value = {this.state.id} onChange={this.handleChange} name="id" placeholder="Enter your ID..."  required />
                </p><br/></div>
                <div className = "form-group">
                <p>Password:
                <input type="text" value = {this.state.password} onChange={this.handleChange} name="password" placeholder="Enter your password" required />
                </p><br/></div>
             <button className = "btn btn-success" type="submit" value="Sign up" onSubmit={this.handleSubmit}> Sign Up</button>
            </form>

            </div>

        )}
}

export default Signup;
</code>```

```<code>const express = require('express');
const bodyParser = require('body-parser');
const user = require('../db/user');

const router = express.Router();
var urlencodedParser = bodyParser.urlencoded({extended: false});

//Sign Up
router.post('/login', function(req,res){
    console.log(req.body);
    var newUser = new user.User(req.body);
    newUser.save().then(item => {
        res.redirect('/signin.html');
    }).catch(err => {
        res.status(400).send(err,"Unable to save to database");
    });
});

//Sign in logic
router.post('/signin', urlencodedParser, async(req,res) => {
    // check is id exist
    let userid = await user.User.findOne({id: req.body.id});
    if (!userid) {
        res.status(400).send('Invalid id please sign up');
    } else {
        let userpass = await user.User.findOne({
            id: req.body.id,
            password: req.body.password
        });
        if (!userpass) {
            return res.status(400).send('Wrong password');
        }
        res.redirect('/login-success.html');
    }
});

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

I would like POST call to work instead of getting cannot POST /login

答: Update const API = 'http://localhost:8080/'; to const API = 'http://localhost:5000/'

Body:
I'm trying to send user id and password in React frontend (running on localhost:8080) to express backend server(running on localhost:5000) using post method, but when I click button for submit it says cannot Post /login

Below is my code

import React, { Component } from 'react';
//import'whatwg-fetch';

function postSend(url, data) {
  return fetch(url, {
    credentials: 'same-origin',
    mode: 'cors',
    method: 'POST', // 'GET', 'PUT', 'DELETE', etc.
    body: JSON.stringify(data), // Coordinate the body type with 'Content-Type'
    headers: new Headers({
      'Content-Type': 'application/json',
      'Accept': 'application/json'
    }),
  }).then((res) => res.json())
  .then((result) => console.log(result))
  .catch((error) =>{
    console.error(error, 'postRequest error');
  })
};

class Signup extends Component {
  constructor(props){
    super(props);
    this.state = { id: "", password: ""}
  }
  componentDidMount() {
    const API = 'http://localhost:8080/';
    const DEFAULT_QUERY = 'routes';
    fetch(API + DEFAULT_QUERY, {
  headers : {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
   },
   mode: 'cors'

  }).then(response => response.json())
    .then(data => this.setState({ data }))
    .catch(function(err) {console.log(err)});
}

  handleChange = event => {
    this.setState({ [event.target.name] : event.target.value });
  };
  handleSubmit(event) {
    event.preventDefault();
    postSend('http://localhost:5000/login', this.state);

  }
    render() {
        return (

Welcome to Secret Admirer

            <form action = "/login" method = "POST"  >

                Enter Your Credentials to sign up

user id:
                <input  type="text" value = {this.state.id} onChange={this.handleChange} name="id" placeholder="Enter your ID..."  required />

Password:
                <input type="text" value = {this.state.password} onChange={this.handleChange} name="password" placeholder="Enter your password" required />

             <button className = "btn btn-success" type="submit" value="Sign up" onSubmit={this.handleSubmit}> Sign Up</button>
            </form>

        )}
}

export default Signup;

const express = require('express');
const bodyParser = require('body-parser');
const user = require('../db/user');

const router = express.Router();
var urlencodedParser = bodyParser.urlencoded({extended: false});

//Sign Up
router.post('/login', function(req,res){
    console.log(req.body);
    var newUser = new user.User(req.body);
    newUser.save().then(item => {
        res.redirect('/signin.html');
    }).catch(err => {
        res.status(400).send(err,"Unable to save to database");
    });
});

//Sign in logic
router.post('/signin', urlencodedParser, async(req,res) => {
    // check is id exist
    let userid = await user.User.findOne({id: req.body.id});
    if (!userid) {
        res.status(400).send('Invalid id please sign up');
    } else {
        let userpass = await user.User.findOne({
            id: req.body.id,
            password: req.body.password
        });
        if (!userpass) {
            return res.status(400).send('Wrong password');
        }
        res.redirect('/login-success.html');
    }
});

module.exports = router;

I would like POST call to work instead of getting cannot POST /login