问:
Equation trouble in Rmarkdown
Keep getting a message:

! Missing { inserted.
<to be read again>
                   \left
l.70 \end{frame}

when running the R markdown file below (in RStudio). I have spent a few hours pulling my hair out trying to figure out why? The equation renders in the preview.

```<code>---
title: "Compile Please"
output: beamer_presentation
---

## This Equation is Poison for Rmd

$$ f(x) = \left( 1 + \frac{x}{m - \alpha} \right) ^ \left( x \right) $$
</code>```

答:
It may be picky about spaces there.  This "tighter" version with explicit parens to protect that exponentiated works here:</p>

```<code>$$ f(x) = \left( 1 + \frac{x}{m - \alpha} \right)^{\left( x \right)} $$
</code>```

Title: Equation trouble in Rmarkdown

Body:
Keep getting a message:

! Missing { inserted.
<to be read again>
                   \left
l.70 \end{frame}

when running the R markdown file below (in RStudio). I have spent a few hours pulling my hair out trying to figure out why? The equation renders in the preview.

---
title: "Compile Please"
output: beamer_presentation
---

## This Equation is Poison for Rmd

$$ f(x) = \left( 1 + \frac{x}{m - \alpha} \right) ^ \left( x \right) $$

Body:
It may be picky about spaces there.  This "tighter" version with explicit parens to protect that exponentiated works here:

$$ f(x) = \left( 1 + \frac{x}{m - \alpha} \right)^{\left( x \right)} $$


来源: stackexchange

问:
'adb' is not recognized as a command
In my new MacBook, I installed latest Android Studio. Then, in terminal, I created the .bash_profile, and added following lines to the file:

```<code>export ANDROID_HOME=~/Library/Android/sdk

export ANDROID_TOOLS=$ANDROID_HOME/tools

export PATH=$PATH:$ANDROID_HOME/platform_tools

export PATH=$PATH:$ANDROID_TOOLS
</code>```

After that, I run command source .bash_profile, then I type adb command, but get error that adb is not recognized as a command. Why? I also echo $PATH, I saw the platform_tools directory of Android sdk is there & there is adb file under that directory.

====== UPDATE =====

It is interesting, if I do following, it works:

```<code>export PATH=$PATH:/Users/myname/Library/Android/sdk/platform-tools
export PATH=$PATH:/Users/myname/Library/Android/sdk/tools
export ANDROID_HOME=/Users/myname/Library/Android/sdk
</code>```

WHY? Isn't ~ above identical to /Users/myname? Why my original script doesn't work but the above one works? I don't understand....Please someone explain to me.

答:
In your example all lines work OK (but pay particular attention to platform_tools folder's name):

```<code>export ANDROID_HOME=~/Library/Android/sdk
export ANDROID_TOOLS=$ANDROID_HOME/tools
export PATH=$PATH:$ANDROID_HOME/platform_tools:$ANDROID_TOOLS

source .bash_profile
adb
</code>```

so, you've got a mistake:

```<code>platform_tools
</code>```

instead of:

```<code>platform-tools
</code>```

Also, you could try this solution, it works fine:

```<code># print two export commands to your ~/.bash_profile
echo "export ANDROID_HOME=/Users/swift/Library/Android/sdk" >> ~/.bash_profile
echo "export PATH=${PATH}:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools" >> ~/.bash_profile

# Refresh bash profile (or restart Terminal.app)
source ~/.bash_profile

# Start using your adb command
adb --version
adb devices
</code>```

ContentLicense: CC BY-SA 3.0

Title: 'adb' is not recognized as a command

Body:
In my new MacBook, I installed latest Android Studio. Then, in terminal, I created the .bash_profile, and added following lines to the file:

export ANDROID_HOME=~/Library/Android/sdk

export ANDROID_TOOLS=$ANDROID_HOME/tools

export PATH=$PATH:$ANDROID_HOME/platform_tools

export PATH=$PATH:$ANDROID_TOOLS

After that, I run command source .bash_profile, then I type adb command, but get error that adb is not recognized as a command. Why? I also echo $PATH, I saw the platform_tools directory of Android sdk is there & there is adb file under that directory.

====== UPDATE =====

It is interesting, if I do following, it works:

export PATH=$PATH:/Users/myname/Library/Android/sdk/platform-tools
export PATH=$PATH:/Users/myname/Library/Android/sdk/tools
export ANDROID_HOME=/Users/myname/Library/Android/sdk

WHY? Isn't ~ above identical to /Users/myname? Why my original script doesn't work but the above one works? I don't understand....Please someone explain to me.

Body:
In your example all lines work OK (but pay particular attention to platform_tools folder's name):

export ANDROID_HOME=~/Library/Android/sdk
export ANDROID_TOOLS=$ANDROID_HOME/tools
export PATH=$PATH:$ANDROID_HOME/platform_tools:$ANDROID_TOOLS

source .bash_profile
adb

so, you've got a mistake:

platform_tools

instead of:

platform-tools

Also, you could try this solution, it works fine:

# print two export commands to your ~/.bash_profile
echo "export ANDROID_HOME=/Users/swift/Library/Android/sdk" >> ~/.bash_profile
echo "export PATH=${PATH}:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools" >> ~/.bash_profile

# Refresh bash profile (or restart Terminal.app)
source ~/.bash_profile

# Start using your adb command
adb --version
adb devices


问:
macOS, segue kind popover not allowed from toolbar
I would like to ask why is possible to create a segue of kind popover or sheet by dragging from a button to a NSWindow or NSView by you cannot from a toolbar item?

From a toolbar only allows kind: show, modal and custom

答:
While I'm not really sure why this isn't possible through dragging in Interface Builder, you can still present a popover manually by using the target/action mechanism. Your toolbar button will call an action like presentFooPopover(:), which in turn will call NSViewController's presentViewController(_ viewController: NSViewController, asPopoverRelativeTo positioningRect: NSRect, of positioningView: NSView, preferredEdge: NSRectEdge, behavior: NSPopover.Behavior) to present the popover's target view controller from some position in some view.

The presenting view controller (on which you call presentViewController...) doesn't have to own the view you use for positioning. Note also the positioningRect must be in the positioningView's coordinate system, so the view's bounds is usually used.

Putting all that together, you can pass the button (sender in your action) as the positioning view and use its bounds. The view controller responsible for presenting the popover could be your window controller or your window's content view controller (or really anything that won't go away while the popover is still presented, which would also dismiss the popover).


问:
Forcing sequential processing in Haskell's Data.Binary.Get
After trying to import the basic Java runtime library rt.jar with language-java-classfile, I've discovered that it uses huge amounts of memory.

I've reduced the program demonstrating the problem to 100 lines and uploaded it to hpaste. Without forcing the evaluation of stream in line #94, I have no chance of ever running it because it eats up all my memory. Forcing stream before passing it to getClass finishes, but still uses up huge amounts of memory:

```<code>  34,302,587,664 bytes allocated in the heap
  32,583,990,728 bytes copied during GC
     139,810,024 bytes maximum residency (398 sample(s))
      29,142,240 bytes maximum slop
             281 MB total memory in use (4 MB lost due to fragmentation)

  Generation 0: 64992 collections,     0 parallel, 38.07s, 37.94s elapsed
  Generation 1:   398 collections,     0 parallel, 25.87s, 27.78s elapsed

  INIT  time    0.01s  (  0.00s elapsed)
  MUT   time   37.22s  ( 36.85s elapsed)
  GC    time   63.94s  ( 65.72s elapsed)
  RP    time    0.00s  (  0.00s elapsed)
  PROF  time   13.00s  ( 13.18s elapsed)
  EXIT  time    0.00s  (  0.00s elapsed)
  Total time  114.17s  (115.76s elapsed)

  %GC time      56.0%  (56.8% elapsed)

  Alloc rate    921,369,531 bytes per MUT second

  Productivity  32.6% of total user, 32.2% of total elapsed
</code>```

I thought the problem was the ConstTables staying around, so I tried forcing cls in line #94 as well. But this only makes the memory consumption and the runtime worse:

```<code>  34,300,700,520 bytes allocated in the heap
  23,579,794,624 bytes copied during GC
     487,798,904 bytes maximum residency (423 sample(s))
      36,312,104 bytes maximum slop
             554 MB total memory in use (10 MB lost due to fragmentation)

  Generation 0: 64983 collections,     0 parallel, 71.19s, 71.48s elapsed
  Generation 1:   423 collections,     0 parallel, 344.74s, 353.01s elapsed

  INIT  time    0.01s  (  0.00s elapsed)
  MUT   time   40.60s  ( 42.38s elapsed)
  GC    time  415.93s  (424.49s elapsed)
  RP    time    0.00s  (  0.00s elapsed)
  PROF  time   56.53s  ( 57.71s elapsed)
  EXIT  time    0.00s  (  0.00s elapsed)
  Total time  513.07s  (524.58s elapsed)

  %GC time      81.1%  (80.9% elapsed)

  Alloc rate    844,636,801 bytes per MUT second

  Productivity   7.9% of total user, 7.7% of total elapsed
</code>```

So my question is basically, how do I force sequential processing of the files involved, so that after each one is processed, only the string result (cls) remains in memory?

答:
Your idea to force evaluation of cls in line 94 was right. But I guess you're approach to do so wasn't successfull. See this paste for my version, which runs in ca. 40MB instead of 220MB.

The key is to force reduction to normal form of cls, which is done by rnf cls. And this has to happen before the call to return. Therefore:

rnf cls `seq` return cls

Alternatively, you could use Control.Exception.evaluate:
  evaluate $ rnf cls
  return cls

ContentLicense: CC BY-SA 2.5

Body:
After trying to import the basic Java runtime library rt.jar with language-java-classfile, I've discovered that it uses huge amounts of memory.

I've reduced the program demonstrating the problem to 100 lines and uploaded it to hpaste. Without forcing the evaluation of stream in line #94, I have no chance of ever running it because it eats up all my memory. Forcing stream before passing it to getClass finishes, but still uses up huge amounts of memory:

  34,302,587,664 bytes allocated in the heap
  32,583,990,728 bytes copied during GC
     139,810,024 bytes maximum residency (398 sample(s))
      29,142,240 bytes maximum slop
             281 MB total memory in use (4 MB lost due to fragmentation)

  Generation 0: 64992 collections,     0 parallel, 38.07s, 37.94s elapsed
  Generation 1:   398 collections,     0 parallel, 25.87s, 27.78s elapsed

  INIT  time    0.01s  (  0.00s elapsed)
  MUT   time   37.22s  ( 36.85s elapsed)
  GC    time   63.94s  ( 65.72s elapsed)
  RP    time    0.00s  (  0.00s elapsed)
  PROF  time   13.00s  ( 13.18s elapsed)
  EXIT  time    0.00s  (  0.00s elapsed)
  Total time  114.17s  (115.76s elapsed)

  %GC time      56.0%  (56.8% elapsed)

  Alloc rate    921,369,531 bytes per MUT second

  Productivity  32.6% of total user, 32.2% of total elapsed

I thought the problem was the ConstTables staying around, so I tried forcing cls in line #94 as well. But this only makes the memory consumption and the runtime worse:

  34,300,700,520 bytes allocated in the heap
  23,579,794,624 bytes copied during GC
     487,798,904 bytes maximum residency (423 sample(s))
      36,312,104 bytes maximum slop
             554 MB total memory in use (10 MB lost due to fragmentation)

  Generation 0: 64983 collections,     0 parallel, 71.19s, 71.48s elapsed
  Generation 1:   423 collections,     0 parallel, 344.74s, 353.01s elapsed

  INIT  time    0.01s  (  0.00s elapsed)
  MUT   time   40.60s  ( 42.38s elapsed)
  GC    time  415.93s  (424.49s elapsed)
  RP    time    0.00s  (  0.00s elapsed)
  PROF  time   56.53s  ( 57.71s elapsed)
  EXIT  time    0.00s  (  0.00s elapsed)
  Total time  513.07s  (524.58s elapsed)

  %GC time      81.1%  (80.9% elapsed)

  Alloc rate    844,636,801 bytes per MUT second

  Productivity   7.9% of total user, 7.7% of total elapsed

So my question is basically, how do I force sequential processing of the files involved, so that after each one is processed, only the string result (cls) remains in memory?


问:
c# regex to match only hyphen words
Basically if I have aaa-aaa it should be match.
If it's aaaa-bbbb--- it should match aaaa-bbbb
If its only aaaa it should NOT match.

I want to do it with regex, Any ideas ?

Currently I have

```<code>(?=\\S*[-])([a-zA-Z-]+)
</code>```

答:
Here's how you write a regex.

Describe what the pattern of the string you want to match is, in words.

Find a character class, quantifier or operator that fits each feature in the pattern you described.

Let's try to describe what you want in words first.

The string starts with a bunch of letters

The start of the string must have one or more letters

Then comes a hyphen

Then there is another bunch of characters at the end

The end of the string must have one or more letters

Now, we convert each rule into regex

[a-zA-Z]

+

-

[a-zA-Z]

+

Then we join all these together to get:

```<code>[a-zA-Z]+-[a-zA-Z]+
</code>```

Title: c# regex to match only hyphen words

Body:
Basically if I have aaa-aaa it should be match.
If it's aaaa-bbbb--- it should match aaaa-bbbb
If its only aaaa it should NOT match.

I want to do it with regex, Any ideas ?

Currently I have

(?=\\S*[-])([a-zA-Z-]+)

Body:
Here's how you write a regex.

Describe what the pattern of the string you want to match is, in words.

Find a character class, quantifier or operator that fits each feature in the pattern you described.

Let's try to describe what you want in words first.

The string starts with a bunch of letters

The start of the string must have one or more letters

Then comes a hyphen

Then there is another bunch of characters at the end

The end of the string must have one or more letters

Now, we convert each rule into regex

[a-zA-Z]

+

-

[a-zA-Z]

+

Then we join all these together to get:

[a-zA-Z]+-[a-zA-Z]+


问:
executing observable request on keychange
Im trying to implement from where Im checking if given email exists in database, my goal is to detect key change in input field and after fixed delay execute request to db, struggling with executing the request, because im pretty new to angular and reactive.

code:

```<code>checkIfExists(email: string){
    this.emailToSearch.next(email);
  }

emailExists: Observable<boolean>;
  private emailToSearch = new Subject<string>();
  private user = new RegistrationUser(null, null, null, null, null);

  ngOnInit(): void {
    this.emailExists = this.emailToSearch
      .debounceTime(500)
      .distinctUntilChanged()
      .switchMap(
        email => this.registrationService.exists(email));

  }

  <input type="text" class="form-control" name="email" (keyup)="checkIfExists(email.value)" #email="ngModel" required [(ngModel)]="user.email">
</code>```

答:
Your code seems to be okay so far. The only thing you're missing is to actually invoke the subscription by calling the subscribe method:

```<code>  ngOnInit(): void {
    this.emailExists = this.emailToSearch
      .debounceTime(500)
      .distinctUntilChanged()
      .switchMap(
        email => this.registrationService.exists(email))
      .subscribe((result) => doSomething(result));
  }
</code>```

There is one thing you have to be careful with. In your case, if for some reason the Observable that you receive from this.registrationService.exists errors out, your search will break. Make sure you catch this by doing the following:

```<code>  ngOnInit(): void {
    this.emailExists = this.emailToSearch
      .debounceTime(500)
      .distinctUntilChanged()
      .switchMap(
        email => this.registrationService.exists(email).catch(() => Observable.empty()))
      .subscribe((result) => doSomething(result));
  }
</code>```

The empty observable will allow your subscription to remain active.

Body:
Im trying to implement from where Im checking if given email exists in database, my goal is to detect key change in input field and after fixed delay execute request to db, struggling with executing the request, because im pretty new to angular and reactive.

code:

checkIfExists(email: string){
    this.emailToSearch.next(email);
  }

emailExists: Observable<boolean>;
  private emailToSearch = new Subject<string>();
  private user = new RegistrationUser(null, null, null, null, null);

  ngOnInit(): void {
    this.emailExists = this.emailToSearch
      .debounceTime(500)
      .distinctUntilChanged()
      .switchMap(
        email => this.registrationService.exists(email));

  }

  <input type="text" class="form-control" name="email" (keyup)="checkIfExists(email.value)" #email="ngModel" required [(ngModel)]="user.email">

Body:
Your code seems to be okay so far. The only thing you're missing is to actually invoke the subscription by calling the subscribe method:

  ngOnInit(): void {
    this.emailExists = this.emailToSearch
      .debounceTime(500)
      .distinctUntilChanged()
      .switchMap(
        email => this.registrationService.exists(email))
      .subscribe((result) => doSomething(result));
  }

There is one thing you have to be careful with. In your case, if for some reason the Observable that you receive from this.registrationService.exists errors out, your search will break. Make sure you catch this by doing the following:

  ngOnInit(): void {
    this.emailExists = this.emailToSearch
      .debounceTime(500)
      .distinctUntilChanged()
      .switchMap(
        email => this.registrationService.exists(email).catch(() => Observable.empty()))
      .subscribe((result) => doSomething(result));
  }

The empty observable will allow your subscription to remain active.


问:
Best ways of centralising a div inside another div
I'm just curious as to what the best way is of aligning a div centrally (vertically and horizontally) inside another div. This example features a red div which I want to vertically & horizontally centre inside the div with the background picture.

What is the best way of doing this so it automatically adapts when resizing the browser window & displaying on mobiles?

The following methods fail:

position:relative; & top: 50%; - only the very top of the div is centralised but not the rest. Adding a negative margin-top fails because it applies it to the parent element

margin: 25% auto;

vertical-align: middle;

justify-content: center; - presumably only applies to flexboxes

Here is the code:

body{
    background: yellow;
    margin: 0 auto;
}

#first{
    width:100%;
    height:550px;
    background: url('https://static.pexels.com/photos/30627/pexels-photo-30627.jpg');
    background-size: cover;
}

#central{
    width:200px;
    height:100px;
    background: red;
    margin: 0 auto;

    /*

    Why DO THESE FAIL:

    position:relative; & top: 50%;

    margin: 25% auto;

    vertical-align: middle;

    justify-content: center; - presumably only applies to flexboxes

    */
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <link rel="stylesheet" type="text/css" href="css.css">
    <title>title</title>
  </head>
  <body>

      <div id="first">
        <div id="central"></div>
      </div>

  </body>
</html></code>```

Thanks for any help.

答:
I think the best way to do that is using flexbox. Check this amazing post about flexbox.

The css of the parent div has to be sth like that:

```<code>.first {
  display: flex;
  align-items: center;
}
</code>```

Body:
I'm just curious as to what the best way is of aligning a div centrally (vertically and horizontally) inside another div. This example features a red div which I want to vertically & horizontally centre inside the div with the background picture.

What is the best way of doing this so it automatically adapts when resizing the browser window & displaying on mobiles?

The following methods fail:

position:relative; & top: 50%; - only the very top of the div is centralised but not the rest. Adding a negative margin-top fails because it applies it to the parent element

margin: 25% auto;

vertical-align: middle;

justify-content: center; - presumably only applies to flexboxes

Here is the code:

body{
    background: yellow;
    margin: 0 auto;
}

#first{
    width:100%;
    height:550px;
    background: url('https://static.pexels.com/photos/30627/pexels-photo-30627.jpg');
    background-size: cover;
}

#central{
    width:200px;
    height:100px;
    background: red;
    margin: 0 auto;

    /*

    Why DO THESE FAIL:

    position:relative; & top: 50%;

    margin: 25% auto;

    vertical-align: middle;

    justify-content: center; - presumably only applies to flexboxes

    */
}

<!DOCTYPE html>

    <meta charset="UTF-8">
    <link rel="stylesheet" type="text/css" href="css.css">
    <title>title</title>

Thanks for any help.

Body:
I think the best way to do that is using flexbox. Check this amazing post about flexbox.

The css of the parent div has to be sth like that:

.first {
  display: flex;
  align-items: center;
}


问:
how often optimize table query called
Actually i queried optimize table query for one table. then i didn't do any operation on that table. then again i'm querying optimize table query at the end of every month. but the data in the table may be changed once in four or 8 months. is it create any problem in performance of the mysql query?</p>

答:
If the data doesn't quite change over a period of 4-8 months it should not create any issue with performance for the end of month report.
However if the count of rows that are changed in the 4-8 months period is huge then you would want to rebuild indexes/analyze the tables so that the queries run fine after the load.</p>

Title: how often optimize table query called


问:
Find pair of matches between an numpy array Python
I have a numpy array in Python which contains labels for a classification problem. The array derived after the concatentation of two initial identical arrays.

```<code>labels = np.concatenate((labels1, labels2)) #labels1 and labels2 are identical
</code>```

I want to generate positive/negative pairs which will contain all the indexes from labels (from which labels1 and labels2 are equal) and also the pairs with the negative ones. For example if my input is the following:

```<code>labels = {1, 1, 2, 2, 3, 1, 1, 2, 2, 3} # labels1 = labels2 = {1, 1, 2, 2, 3}
</code>```

Then I want to return as positive pairs:

```<code>positive_pairs = {{1, 6}, {1, 7}, {2, 6}, {2, 7}, {3, 8}, {3, 9}, {4, 8}, {4, 9}, {5, 10}} # i dont want to have {1,2} or {3, 4} in within the positives
negative_pairs = {{1, 8}, {1, 9}, ...}
</code>```

How can I do so in python?

EDIT: What in the case that labels1 and labels2 are not equal?

答:
```<code>outp = []
len1 = len(labels) // 2 # assume initially labels was [label1, label1]
label1 = labels[:len1]
label2 = labels[len1:]
set1 = set(label1)
for v in set1:
    eq1 = np.where(label1 == v)[0] + 1
    eq2 = np.where(label2 == v)[0] + len1 + 1
    outp.append(np.transpose([np.tile(eq1, len(eq2)), np.repeat(eq2, len(eq1))]))
outp = np.concatenate(outp).tolist()

# Edit: Find "negative pairs"
eq3 = np.indices((len1, ))[0][np.in1d(label2, list(set1), invert=True)] + len1 + 1
outn = np.transpose([np.tile(np.arange(len1), len(eq3)), np.repeat(eq3, len1)]).tolist()
</code>```

Body:
I have a numpy array in Python which contains labels for a classification problem. The array derived after the concatentation of two initial identical arrays.

labels = np.concatenate((labels1, labels2)) #labels1 and labels2 are identical

I want to generate positive/negative pairs which will contain all the indexes from labels (from which labels1 and labels2 are equal) and also the pairs with the negative ones. For example if my input is the following:

labels = {1, 1, 2, 2, 3, 1, 1, 2, 2, 3} # labels1 = labels2 = {1, 1, 2, 2, 3}

Then I want to return as positive pairs:

positive_pairs = {{1, 6}, {1, 7}, {2, 6}, {2, 7}, {3, 8}, {3, 9}, {4, 8}, {4, 9}, {5, 10}} # i dont want to have {1,2} or {3, 4} in within the positives
negative_pairs = {{1, 8}, {1, 9}, ...}

How can I do so in python?

EDIT: What in the case that labels1 and labels2 are not equal?


问:
spirit x3 how to add a vector to an AST
I'm trying to parse a file and have the data copied into a vector within a class object. I've taken the employee example and modified it to what I'm trying to do. The file being parsed looks like this (but more lines) ...

```<code>1 0.2 0.3 0.4
</code>```

I've added a vector to struct employee and am getting assertion failures on the phrase_parse line.

```<code>static assertion failed: Attribute does not have the expected size.
static_assert(
^
</code>```

I'm kind of thinking the expected size has something to do with the vector. Thoughts on where I'm going wrong?

```<code>namespace client {
    namespace ast {

    struct employee
    {
        int id;
        std::vector<double> coords;
    };

    using boost::fusion::operator<<;
}}

BOOST_FUSION_ADAPT_STRUCT(
    client::ast::employee,
    (int, id)
    (std::vector<double>, coords)
)

namespace client
{
    namespace parser
    {
        namespace x3 = boost::spirit::x3;
        namespace ascii = boost::spirit::x3::ascii;

        using x3::int_;
        using x3::double_;

        x3::rule<class employee, ast::employee> const employee = "employee";
        auto const employee_def =
             int_ >> double_ >> double_ >> double_;
        BOOST_SPIRIT_DEFINE(employee)
    }
}

int main()
{
    using boost::spirit::x3::ascii::space;
    using client::parser::employee;

    string fil("test-file.in");

    mapped_file_source map(fil);
    istringstream iss(map.data());
    map.close();

    client::ast::employee emp;

    boost::spirit::istream_iterator iter(iss >> noskipws), eof;

    phrase_parse(iter, eof, employee, space, emp);
    // failure on above line
}
</code>```

答:
According to the documentation, double_ >> double_ >> double_ synthesizes a Fusion sequence of double, double, double (so fusion::tuple<double, double, double> or fusion::list<double, double, double> etc).

You want a vector, so you need a repeating parser (operator)

the repeat directive will do repeat(3) [double_]

the Kleene star (operator *) or plus (operator +) are interesting (but unbounded)

the list operator (operator %) is also unbounded but accepts delimiters (e.g. double_ % ','

In this case I'd go the other way: use a proper AST for the grammar:

Live On Coliru

```<code>struct coord {
    double x,y,z;
};

struct employee
{
    int id;
    coord coords;
};
</code>```

Adapting them is simpler than the old fashioned method you used:

```<code>BOOST_FUSION_ADAPT_STRUCT(client::ast::coord, x, y, z)
BOOST_FUSION_ADAPT_STRUCT(client::ast::employee, id, coords)
</code>```

The parser is a clean

```<code>auto const coord_def = double_ >> double_ >> double_;
auto const employee_def = int_ >> coord;
</code>```

Full demo:

Live On Coliru

```<code>#include <boost/spirit/home/x3.hpp>
#include <boost/spirit/include/support_istream_iterator.hpp>
#include <boost/fusion/adapted/struct.hpp>
#include <iostream>

namespace client {
    namespace ast {

    struct coord {
        double x,y,z;
    };

    struct employee
    {
        int id;
        coord coords;
    };

    using boost::fusion::operator<<;
}}

BOOST_FUSION_ADAPT_STRUCT(client::ast::coord, x, y, z)
BOOST_FUSION_ADAPT_STRUCT(client::ast::employee, id, coords)

namespace client
{
    namespace parser
    {
        namespace x3 = boost::spirit::x3;
        namespace ascii = boost::spirit::x3::ascii;

        using x3::int_;
        using x3::double_;

        x3::rule<class employee, ast::coord>    const coord    = "coord";
        x3::rule<class employee, ast::employee> const employee = "employee";

        auto const coord_def = double_ >> double_ >> double_;
        auto const employee_def = int_ >> coord;

        BOOST_SPIRIT_DEFINE(employee, coord);
    }
}

int main()
{
    using boost::spirit::x3::ascii::space;
    using client::parser::employee;

    std::istringstream iss("1 0.2 0.3 0.4");

    client::ast::employee emp;

    boost::spirit::istream_iterator iter(iss >> std::noskipws), eof;

    bool ok = phrase_parse(iter, eof, employee, space, emp);
    if (ok)
        std::cout << "parsed: "
             << emp.id       << " "
             << emp.coords.x << " "
             << emp.coords.y << " "
             << emp.coords.z << "\n";
}
</code>```

Title: spirit x3 how to add a vector to an AST

Body:
I'm trying to parse a file and have the data copied into a vector within a class object. I've taken the employee example and modified it to what I'm trying to do. The file being parsed looks like this (but more lines) ...

1 0.2 0.3 0.4

I've added a vector to struct employee and am getting assertion failures on the phrase_parse line.

static assertion failed: Attribute does not have the expected size.
static_assert(
^

I'm kind of thinking the expected size has something to do with the vector. Thoughts on where I'm going wrong?

namespace client {
    namespace ast {

    struct employee
    {
        int id;
        std::vector<double> coords;
    };

    using boost::fusion::operator<<;
}}

BOOST_FUSION_ADAPT_STRUCT(
    client::ast::employee,
    (int, id)
    (std::vector<double>, coords)
)

namespace client
{
    namespace parser
    {
        namespace x3 = boost::spirit::x3;
        namespace ascii = boost::spirit::x3::ascii;

        using x3::int_;
        using x3::double_;

        x3::rule<class employee, ast::employee> const employee = "employee";
        auto const employee_def =
             int_ >> double_ >> double_ >> double_;
        BOOST_SPIRIT_DEFINE(employee)
    }
}

int main()
{
    using boost::spirit::x3::ascii::space;
    using client::parser::employee;

    string fil("test-file.in");

    mapped_file_source map(fil);
    istringstream iss(map.data());
    map.close();

    client::ast::employee emp;

    boost::spirit::istream_iterator iter(iss >> noskipws), eof;

    phrase_parse(iter, eof, employee, space, emp);
    // failure on above line
}

Body:
According to the documentation, double_ >> double_ >> double_ synthesizes a Fusion sequence of double, double, double (so fusion::tuple<double, double, double> or fusion::list<double, double, double> etc).

You want a vector, so you need a repeating parser (operator)

the repeat directive will do repeat(3) [double_]

the Kleene star (operator *) or plus (operator +) are interesting (but unbounded)

the list operator (operator %) is also unbounded but accepts delimiters (e.g. double_ % ','

In this case I'd go the other way: use a proper AST for the grammar:

Live On Coliru

struct coord {
    double x,y,z;
};

struct employee
{
    int id;
    coord coords;
};

Adapting them is simpler than the old fashioned method you used:

BOOST_FUSION_ADAPT_STRUCT(client::ast::coord, x, y, z)
BOOST_FUSION_ADAPT_STRUCT(client::ast::employee, id, coords)

The parser is a clean

auto const coord_def = double_ >> double_ >> double_;
auto const employee_def = int_ >> coord;

Full demo:

Live On Coliru

#include <boost/spirit/home/x3.hpp>
#include <boost/spirit/include/support_istream_iterator.hpp>
#include <boost/fusion/adapted/struct.hpp>
#include <iostream>

namespace client {
    namespace ast {

    struct coord {
        double x,y,z;
    };

    struct employee
    {
        int id;
        coord coords;
    };

    using boost::fusion::operator<<;
}}

BOOST_FUSION_ADAPT_STRUCT(client::ast::coord, x, y, z)
BOOST_FUSION_ADAPT_STRUCT(client::ast::employee, id, coords)

namespace client
{
    namespace parser
    {
        namespace x3 = boost::spirit::x3;
        namespace ascii = boost::spirit::x3::ascii;

        using x3::int_;
        using x3::double_;

        x3::rule<class employee, ast::coord>    const coord    = "coord";
        x3::rule<class employee, ast::employee> const employee = "employee";

        auto const coord_def = double_ >> double_ >> double_;
        auto const employee_def = int_ >> coord;

        BOOST_SPIRIT_DEFINE(employee, coord);
    }
}

int main()
{
    using boost::spirit::x3::ascii::space;
    using client::parser::employee;

    std::istringstream iss("1 0.2 0.3 0.4");

    client::ast::employee emp;

    boost::spirit::istream_iterator iter(iss >> std::noskipws), eof;

    bool ok = phrase_parse(iter, eof, employee, space, emp);
    if (ok)
        std::cout << "parsed: "
             << emp.id       << " "
             << emp.coords.x << " "
             << emp.coords.y << " "
             << emp.coords.z << "\n";
}


问:
Run command line in python and save the details
i am trying to run some command line in python script, like:

```<code>ping 8.8.8.8
</code>```

and when i write this code:

```<code>import os
os.system('ping 8.8.8.8')
</code>```

it printing me the details of the command.
but i want it for be background command,
what mean i dont want to user will see all the details.
i want to save it to varilble, and after that edit and print as my wish.
how can i do that?
i try to store what the function return, as:

```<code>answer = os.system('ping 8.8.8.8')
</code>```

but the function return 0. help someone?

答:
import os
res = os.popen('ping 8.8.8.')
print(res.read())
res.close()

But I think it's safer to use subprocess.Popen() instead of os.popen().

Here show how to switch over

Body:
i am trying to run some command line in python script, like:

ping 8.8.8.8

and when i write this code:

import os
os.system('ping 8.8.8.8')

it printing me the details of the command.
but i want it for be background command,
what mean i dont want to user will see all the details.
i want to save it to varilble, and after that edit and print as my wish.
how can i do that?
i try to store what the function return, as:

answer = os.system('ping 8.8.8.8')

but the function return 0. help someone?


问:
How to roll back delete operation sql server?
I have an input page in my C# application whereby my boss can enter sales info.

This page also has a clear button, which clears the contents of the table in the database. This clear button was convenient for testing, however now in hindsight a mistake.

All the records in the table have been deleted. There are no backups either.

Long shot, but is there any way of recovering this data using only SQL Server 2008?

答:
If you still have the transaction logs, there are some tools, but these will cost some ...

See
How to undo a delete operation in SQL Server 2005?

and
https://web.archive.org/web/20080215075500/http://sqlserver2000.databases.aspfaq.com/how-do-i-recover-data-from-sql-server-s-log-files.html

Edit : Looks like Redgate is SQL 2000 only. Which leaves Apex. And if your clear function uses TRUNCATE, you are up the creek.


问:
Laravel Cashier: should I add a trial period in Stripe too?
Quoting Laravel Cashier documentation:

If you would like to offer trial periods to your customers while still collecting payment method information up front, You should use the trialDays method when creating your subscriptions.

Assuming I want to add a 30 days trial period to my subscriptions, I can create a subscription with this code:

```<code>$user->newSubscription('main', 'monthly')
        ->trialDays(30)
        ->create($stripeToken);
</code>```

As a Stripe user, should I add a trial period in Stripe plan too?

I'm not sure to understand the logic of Laravel Cashier here. It seems redundant to declare something at two different places.

答: I would say its not necessary. If you're adding trial days at the time of subscription creation (trial_end parameter when using the API directly), that will take precedence over the trial days defined on a plan anyway!</p>

Body:
Quoting Laravel Cashier documentation:

If you would like to offer trial periods to your customers while still collecting payment method information up front, You should use the trialDays method when creating your subscriptions.

Assuming I want to add a 30 days trial period to my subscriptions, I can create a subscription with this code:

$user->newSubscription('main', 'monthly')
        ->trialDays(30)
        ->create($stripeToken);

As a Stripe user, should I add a trial period in Stripe plan too?

I'm not sure to understand the logic of Laravel Cashier here. It seems redundant to declare something at two different places.


问:
How can I make a windows app in C# that for example automatically follows someone on Twitter when I open it up?
If I were to follow USA Today on Twitter with a JavaScript code I could go to their page and paste this simple code in the console:

```<code>follow();
function follow(){
var button = document.getElementsByClassName("EdgeButton EdgeButton--secondary EdgeButton--medium button-text follow-text")[0];
button.click();
}
</code>```

How can I trigger this code on a specific URL in C# (only after the page loaded)?

So what I'm trying to ask is how can I trigger a button in C# remotely, without actually visiting the page?

So it could be a simple console application too where I simply

```<code>string jsCode = "follow();
function follow(){
var button = document.getElementsByClassName("EdgeButton EdgeButton--secondary EdgeButton--medium button-text follow-text")[0];
button.click();
}";
string url = "https://twitter.com/";
List<string> pagesToFollow = new List<string>();
pagesToFollow.Add("USATODAY");
pagesToFollow.Add("RT_America");
pagesToFollow.Add("Reuters");
foreach (var s in pagesToFollow) whateverMethodGoesHere(url + s, jsCode);
</code>```

This is pretty much what the app would look like but I have no idea how to execute a JavaScript code remotely and I yet to find a solution to the problem that the code should wait until the page is loaded.

答:
Considering it a general question as you request, a general answer would be something like this:

Use a proxy, like Fiddler, and study the HTTP requests done while performing the task you want to emulate. Then, replay the requests from your program.

Embed a headless browser like Chromium and control it from your code.

Use Selenium. There is a binding package in NuGet.

... and many more, I suppose. This question is really open to speculation.

Body:
If I were to follow USA Today on Twitter with a JavaScript code I could go to their page and paste this simple code in the console:

follow();
function follow(){
var button = document.getElementsByClassName("EdgeButton EdgeButton--secondary EdgeButton--medium button-text follow-text")[0];
button.click();
}

How can I trigger this code on a specific URL in C# (only after the page loaded)?

So what I'm trying to ask is how can I trigger a button in C# remotely, without actually visiting the page?

So it could be a simple console application too where I simply

string jsCode = "follow();
function follow(){
var button = document.getElementsByClassName("EdgeButton EdgeButton--secondary EdgeButton--medium button-text follow-text")[0];
button.click();
}";
string url = "https://twitter.com/";
List<string> pagesToFollow = new List<string>();
pagesToFollow.Add("USATODAY");
pagesToFollow.Add("RT_America");
pagesToFollow.Add("Reuters");
foreach (var s in pagesToFollow) whateverMethodGoesHere(url + s, jsCode);

This is pretty much what the app would look like but I have no idea how to execute a JavaScript code remotely and I yet to find a solution to the problem that the code should wait until the page is loaded.


问:
Are there any configuration options for RoR asset packager?
Regarding the Asset packager plugin for RoR.

Is there a way to configure it, so that it packages JS/CSS files in development environment, but without minifying the JS files?

答:
Doesn't seem like it, but it's easy to add:

Add "development" env at this line or setup another ENV variable and if it exists it can be included automatically so you don't mess around with code more than once.

For the compressed_file method (which compresses the js and css) you could add an option (or have it read from the ENV) and compress or not depending on it


问:
How to calculate the outgoing call ( which I dialed from my app) duration in android programmatically
I have given the permission in manifest.xml file

```<code><uses-permission android:name="android.permission.CALL_PHONE"/>
<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
</code>```

And define a receiver:

```<code><receiver android:name=".OutgoingCallReceiver">
        <intent-filter>
            <action android:name="android.intent.action.PHONE_STATE" />
        </intent-filter>
    </receiver>
</code>```

The receiver file is:

```<code>public class OutgoingCallReceiver extends BroadcastReceiver {

public static String TAG = "AUTODIAL";
static long start_time, end_time, call_duration;
String number;

@Override
public void onReceive(Context context, Intent intent) {

    Toast.makeText(context, "intent get data : "+intent.getData(), Toast.LENGTH_LONG).show();
    String action = intent.getAction();
    String state=intent.getStringExtra(TelephonyManager.EXTRA_STATE);
    Toast.makeText(context, "Phone State : "+state, Toast.LENGTH_LONG).show();

    if(state==null) {
        number=intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
        Toast.makeText(context, "Out going Phone number : "+number, Toast.LENGTH_LONG).show();
    }

    if (action.equalsIgnoreCase("android.intent.action.PHONE_STATE")) {
        if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
            start_time = System.currentTimeMillis();
        }
        if (state.equals(TelephonyManager.EXTRA_STATE_IDLE)) {
            end_time = System.currentTimeMillis();
        }
        call_duration = end_time - start_time;
}
}
</code>```

Here, it is giving all out going call duration and not only the ones I dialed from my app .

And is it possible to go back to my app after dialing from it?

答:
below is a code of detecting outgoing call by accessibility events -

Add a class which extends AccessibilityService in your projects -

```<code>public class CallDetection extends AccessibilityService {
@Override
public void onAccessibilityEvent(AccessibilityEvent event) {
     acquireLock(this);
    Log.d("myaccess","after lock");
    if (event.getEventType() == AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED) {
        Log.d("myaccess","in window changed");
        AccessibilityNodeInfo info = event.getSource();
        if (info != null && info.getText() != null) {
            String duration = info.getText().toString();
            String zeroSeconds = String.format("%02d:%02d", new Object[]{Integer.valueOf(0), Integer.valueOf(0)});
            String firstSecond = String.format("%02d:%02d", new Object[]{Integer.valueOf(0), Integer.valueOf(1)});
            Log.d("myaccess","after calculation - "+ zeroSeconds + " --- "+ firstSecond + " --- " + duration);
            if (zeroSeconds.equals(duration) || firstSecond.equals(duration)) {
                Toast.makeText(getApplicationContext(),"Call answered",Toast.LENGTH_SHORT).show();
               // Your Code goes here
            }
            info.recycle();
        }
    }
}

@Override
protected void onServiceConnected() {
    super.onServiceConnected();
    Toast.makeText(this,"Service connected",Toast.LENGTH_SHORT).show();
    AccessibilityServiceInfo info = new AccessibilityServiceInfo();
    info.eventTypes = AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED;
    info.feedbackType = AccessibilityServiceInfo.FEEDBACK_GENERIC;
    info.notificationTimeout = 0;
    info.packageNames = null;
    setServiceInfo(info);
}

@Override
public void onInterrupt() {

}
}
</code>```

But to get the function event.getSource() working you have to specify some of your service configuration through xml, so create a xml folder in your project and add a xml file called  serviceconfig.xml (you can give any name you want.

The content of serviceconfig is below -

```<code><accessibility-service xmlns:android="http://schemas.android.com/apk/res/android"
android:description="@string/callDetection"
android:accessibilityEventTypes="typeWindowContentChanged"
android:notificationTimeout="100"
android:canRetrieveWindowContent="true"
/>
</code>```

You can find more about serviceconfig in Here

Now add your service in you Manifest file like this -

```<code><service android:name=".CallDetection"
        android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE"
        android:label="@string/callDetection">
        <intent-filter>
            <action android:name="android.accessibilityservice.AccessibilityService" />
        </intent-filter>
        <meta-data
            android:name="android.accessibilityservice"
            android:resource="@xml/serviceconfig" />
</service>
</code>```

And youre done, just run the app and go to Accessibility settings in your phone, you will find an option named as detection (or whatever name you have given as your service description), switch that on to give accesibility permissions for you app.

Now you will see a toast when call is answered.

you can Code any code you want in there, also you can call a callback function in your activity

Most important - Dont call your call window(android dialer window) untill the call is answered, otherwise this will not work.

Note - As android doesn't provide any solution to detect if the call is answered or not, this is the best alternative i have made, hope it works for you.

Body:
I have given the permission in manifest.xml file

<uses-permission android:name="android.permission.CALL_PHONE"/>
<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>

And define a receiver:

<receiver android:name=".OutgoingCallReceiver">
        <intent-filter>
            <action android:name="android.intent.action.PHONE_STATE" />
        </intent-filter>
    </receiver>

The receiver file is:

public class OutgoingCallReceiver extends BroadcastReceiver {

public static String TAG = "AUTODIAL";
static long start_time, end_time, call_duration;
String number;

@Override
public void onReceive(Context context, Intent intent) {

    Toast.makeText(context, "intent get data : "+intent.getData(), Toast.LENGTH_LONG).show();
    String action = intent.getAction();
    String state=intent.getStringExtra(TelephonyManager.EXTRA_STATE);
    Toast.makeText(context, "Phone State : "+state, Toast.LENGTH_LONG).show();

    if(state==null) {
        number=intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
        Toast.makeText(context, "Out going Phone number : "+number, Toast.LENGTH_LONG).show();
    }

    if (action.equalsIgnoreCase("android.intent.action.PHONE_STATE")) {
        if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
            start_time = System.currentTimeMillis();
        }
        if (state.equals(TelephonyManager.EXTRA_STATE_IDLE)) {
            end_time = System.currentTimeMillis();
        }
        call_duration = end_time - start_time;
}
}

Here, it is giving all out going call duration and not only the ones I dialed from my app .

And is it possible to go back to my app after dialing from it?

Body:
below is a code of detecting outgoing call by accessibility events -

Add a class which extends AccessibilityService in your projects -

public class CallDetection extends AccessibilityService {
@Override
public void onAccessibilityEvent(AccessibilityEvent event) {
     acquireLock(this);
    Log.d("myaccess","after lock");
    if (event.getEventType() == AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED) {
        Log.d("myaccess","in window changed");
        AccessibilityNodeInfo info = event.getSource();
        if (info != null && info.getText() != null) {
            String duration = info.getText().toString();
            String zeroSeconds = String.format("%02d:%02d", new Object[]{Integer.valueOf(0), Integer.valueOf(0)});
            String firstSecond = String.format("%02d:%02d", new Object[]{Integer.valueOf(0), Integer.valueOf(1)});
            Log.d("myaccess","after calculation - "+ zeroSeconds + " --- "+ firstSecond + " --- " + duration);
            if (zeroSeconds.equals(duration) || firstSecond.equals(duration)) {
                Toast.makeText(getApplicationContext(),"Call answered",Toast.LENGTH_SHORT).show();
               // Your Code goes here
            }
            info.recycle();
        }
    }
}

@Override
protected void onServiceConnected() {
    super.onServiceConnected();
    Toast.makeText(this,"Service connected",Toast.LENGTH_SHORT).show();
    AccessibilityServiceInfo info = new AccessibilityServiceInfo();
    info.eventTypes = AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED;
    info.feedbackType = AccessibilityServiceInfo.FEEDBACK_GENERIC;
    info.notificationTimeout = 0;
    info.packageNames = null;
    setServiceInfo(info);
}

@Override
public void onInterrupt() {

}
}

But to get the function event.getSource() working you have to specify some of your service configuration through xml, so create a xml folder in your project and add a xml file called  serviceconfig.xml (you can give any name you want.

The content of serviceconfig is below -

<accessibility-service xmlns:android="http://schemas.android.com/apk/res/android"
android:description="@string/callDetection"
android:accessibilityEventTypes="typeWindowContentChanged"
android:notificationTimeout="100"
android:canRetrieveWindowContent="true"
/>

You can find more about serviceconfig in Here

Now add your service in you Manifest file like this -

<service android:name=".CallDetection"
        android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE"
        android:label="@string/callDetection">
        <intent-filter>
            <action android:name="android.accessibilityservice.AccessibilityService" />
        </intent-filter>
        <meta-data
            android:name="android.accessibilityservice"
            android:resource="@xml/serviceconfig" />
</service>

And youre done, just run the app and go to Accessibility settings in your phone, you will find an option named as detection (or whatever name you have given as your service description), switch that on to give accesibility permissions for you app.

Now you will see a toast when call is answered.

you can Code any code you want in there, also you can call a callback function in your activity

Most important - Dont call your call window(android dialer window) untill the call is answered, otherwise this will not work.

Note - As android doesn't provide any solution to detect if the call is answered or not, this is the best alternative i have made, hope it works for you.


问:
blank space after "%c" in scanf format string ignores last character
```<code>#include <stdio.h>

int main(void)
{
    char c;
    while (scanf(" %c ", &c) != EOF)
        printf("you typed: %c \n", c);

    return 0;
}
</code>```

I can just put blank space before %c like " %c" to let scanf read  a single character and skip any white spaces, but if I put another blank space after %c there comes problems:

```<code>a s d f
you typed: a
you typed: s
you typed: d
1 2 3
you typed: f
you typed: 1
you typed: 2
</code>```

so why does it leave last character in input stream? Even though I actually typed "a s d f " with tailing space.

In fact scanf leaves "f \n" unread, right?

btw in the case of " %c" there's no problem as expected.

答:
From the draft of the C11 standard:

7.21.6.2 The fscanf function

[...]

5.  A directive composed of white-space character(s) is executed by reading input up to the first non-white-space character (which remains unread), or until no more characters can be read. The directive never fails.

This means that a whitespace character in the format string of *scanf will read and discard all whitespace characters until a non-whitespace character is encountered.

So, even if you input "a s d f ", your scanf, after consuming the f, would read and discard the final space and would wait for further input as it hasn't encountered a non-whitespace character yet.

You can close the stream by sending in an EOF signal so that the scanf will stop scanning and return EOF. Or you could remove that space and revert it to " %c" which you originally had.

Body:
#include <stdio.h>

int main(void)
{
    char c;
    while (scanf(" %c ", &c) != EOF)
        printf("you typed: %c \n", c);

    return 0;
}

I can just put blank space before %c like " %c" to let scanf read  a single character and skip any white spaces, but if I put another blank space after %c there comes problems:

a s d f
you typed: a
you typed: s
you typed: d
1 2 3
you typed: f
you typed: 1
you typed: 2

so why does it leave last character in input stream? Even though I actually typed "a s d f " with tailing space.

In fact scanf leaves "f \n" unread, right?

btw in the case of " %c" there's no problem as expected.


问:
How to properly use the HTML semantic elements in a blog?
I read a lot of information on w3schools. It defines
 as:

The
 element defines a section in a document. [...] A home page could normally be split into sections for introduction, content, and contact information.

So, basically, a
 can be a  (introduction) and  (contact information)?

The  element specifies a header for a document or section.

So I could put a  inside a
? But a
 can be used "for introduction", so it basically is a header? Same story with the  element.

Questions

How am I actually supposed to use the elements?

Should I use  for the title of an
 or for the part of my website containing the logo and navigation?

Should I use  for the data of an
 or for the part of my website containing the copyright and footer navigation?

Should I put a
 tag around my
 tags?

Let's say I have a simple website, containing a logo, navigation, several articles and some footer text. What would be the best way to do the markup?

<!DOCTYPE html>

    <title>My site</title>

Item 1

Item 2

Item 3

Article 1 title

            Posted on Foo.Bar.2017

Article 2 title

            Posted on Foo.Bar.2017

Article 3 title

            Posted on Foo.Bar.2017

Copyright

```

If I do that, the Nu HTML Checker says:

Warning: Section lacks heading. Consider using h2-h6 elements to add identifying headings to all sections.

I don't want an
 stating the
 contains
 tags. Should I just remove the
? It appears to be a flexible tag, yet I can't find a valid place to put it.

What would be the correct markup?

答:
header / footer

There are sectioning content and sectioning root elements. header/footer elements always "belong" to one of these sectioning (content/root) elements.

  belongs to the 'body'

    belongs to the 'article'
    belongs to the 'article'

    belongs to the 'body'
    belongs to the 'body'

  belongs to the 'body'

```

Note that the div element is not a sectioning element, which is why its header/footer children belong to the body (which is a sectioning root element), not to the div.

So you can use header/footer elements for site-wide content by placing them so that their nearest sectioning parent element is the body element.

section

A header/footer could consist of one or multiple section elements, but this typically only makes sense if the header/footer is (unusually) complex.

In general, when does it make sense to use section? If you have an implicit section, or if you need an entry in the document outline. Please see my related answers:

how to decide which sectioning content element to use (with three blog markup examples)

section in article vs. article in section (in a blog context)

a rule of thumb when to use section

Note that the validator reports a warning, not an error, when a sectioning content element doesn’t have a heading element. They are not required to have headings, but it can be sign that the sectioning content elements gets misused: it typically only makes sense to use one if it could have a heading, even if you don’t actually provide one.

Body:
I read a lot of information on w3schools. It defines
 as:

The
 element defines a section in a document. [...] A home page could normally be split into sections for introduction, content, and contact information.

So, basically, a
 can be a  (introduction) and  (contact information)?

The  element specifies a header for a document or section.

So I could put a  inside a
? But a
 can be used "for introduction", so it basically is a header? Same story with the  element.

Questions

How am I actually supposed to use the elements?

Should I use  for the title of an
 or for the part of my website containing the logo and navigation?

Should I use  for the data of an
 or for the part of my website containing the copyright and footer navigation?

Should I put a
 tag around my
 tags?

Let's say I have a simple website, containing a logo, navigation, several articles and some footer text. What would be the best way to do the markup?

<!DOCTYPE html>

    <title>My site</title>

Item 1

Item 2

Item 3

Article 1 title

            Posted on Foo.Bar.2017

Article 2 title

            Posted on Foo.Bar.2017

Article 3 title

            Posted on Foo.Bar.2017

Copyright

If I do that, the Nu HTML Checker says:

Warning: Section lacks heading. Consider using h2-h6 elements to add identifying headings to all sections.

I don't want an
 stating the
 contains
 tags. Should I just remove the
? It appears to be a flexible tag, yet I can't find a valid place to put it.

What would be the correct markup?

Body:
header / footer

There are sectioning content and sectioning root elements. header/footer elements always "belong" to one of these sectioning (content/root) elements.

<body>

  <header>belongs to the 'body'</header>

  <article>
    <header>belongs to the 'article'</header>
    <footer>belongs to the 'article'</footer>
  </article>

  <div>
    <header>belongs to the 'body'</header>
    <footer>belongs to the 'body'</footer>
  </div>

  <footer>belongs to the 'body'</footer>

</body>

Note that the div element is not a sectioning element, which is why its header/footer children belong to the body (which is a sectioning root element), not to the div.

So you can use header/footer elements for site-wide content by placing them so that their nearest sectioning parent element is the body element.

section

A header/footer could consist of one or multiple section elements, but this typically only makes sense if the header/footer is (unusually) complex.

In general, when does it make sense to use section? If you have an implicit section, or if you need an entry in the document outline. Please see my related answers:

how to decide which sectioning content element to use (with three blog markup examples)

section in article vs. article in section (in a blog context)

a rule of thumb when to use section

Note that the validator reports a warning, not an error, when a sectioning content element doesn’t have a heading element. They are not required to have headings, but it can be sign that the sectioning content elements gets misused: it typically only makes sense to use one if it could have a heading, even if you don’t actually provide one.


问:
Delete and insert statement
I am new to SQL, so I face a problem when am using delete statement then insert statement the row that I deleted is replaced by the row that I will insert, for example:

Before deleting a row

Table:

```<code>Count | Username | Time
------+----------+------
  10  | MMMMM    | 20:00
  11  | UUUUU    | 23:00
  12  | NNNNN    | 23:30
</code>```

Code:

```<code>SqlCommand cmd = new SqlCommand("delete from table where [Count] = 11", con);
cmd.ExecuteNonQuery();
</code>```

After deleting a row:

```<code>Count | Username | Time
------+----------+------
  10  | MMMMM    | 20:00
  12  | NNNNN    | 23:30
</code>```

Code:

```<code>SqlCommand cmd = new SqlCommand("insert into table values (13,'SSSSS', '01:00')", con);
cmd.ExecuteNonQuery();
</code>```

After inserting a row:

```<code>Count | Username | Time
------+----------+------
  10  | MMMMM    | 20:00
  13  | SSSSS    | 01:00
  12  | NNNNN    | 23:30
</code>```

This the problem in the previous table after using insert statement, if there is a way to make it look like this table after using insert statement :

```<code>Count | Username | Time
------+----------+------
  10  | MMMMM    | 20:00
  12  | NNNNN    | 23:30
  13  | SSSSS    | 01:00
</code>```

Update

I forget to use primary key and it worked for me, i tried to use order by and it didn't help me

答:
```<code>SELECT [Count], Username, Time
FROM Table
ORDER BY [Count]
</code>```

ORDER BY is what you're looking for here. There is no order that can safely be assumed without specifying it directly.

Title: Delete and insert statement

Body:
I am new to SQL, so I face a problem when am using delete statement then insert statement the row that I deleted is replaced by the row that I will insert, for example:

Before deleting a row

Table:

Count | Username | Time
------+----------+------
  10  | MMMMM    | 20:00
  11  | UUUUU    | 23:00
  12  | NNNNN    | 23:30

Code:

SqlCommand cmd = new SqlCommand("delete from table where [Count] = 11", con);
cmd.ExecuteNonQuery();

After deleting a row:

Count | Username | Time
------+----------+------
  10  | MMMMM    | 20:00
  12  | NNNNN    | 23:30

Code:

SqlCommand cmd = new SqlCommand("insert into table values (13,'SSSSS', '01:00')", con);
cmd.ExecuteNonQuery();

After inserting a row:

Count | Username | Time
------+----------+------
  10  | MMMMM    | 20:00
  13  | SSSSS    | 01:00
  12  | NNNNN    | 23:30

This the problem in the previous table after using insert statement, if there is a way to make it look like this table after using insert statement :

Count | Username | Time
------+----------+------
  10  | MMMMM    | 20:00
  12  | NNNNN    | 23:30
  13  | SSSSS    | 01:00

Update

I forget to use primary key and it worked for me, i tried to use order by and it didn't help me

Body:
SELECT [Count], Username, Time
FROM Table
ORDER BY [Count]

ORDER BY is what you're looking for here. There is no order that can safely be assumed without specifying it directly.


问:
How does std :: current_exception work?
Consider the following example:

```<code>class myclass
{
public:

    void f() const
    {
        std :: cout << "Hello from myclass!" << std :: endl;
    }
};

int main()
{
    std :: exception_ptr x;

    try
    {
        throw myclass();
    }
    catch(...)
    {
        x = std :: current_exception();
    }

    try
    {
        std :: rethrow_exception(x);
    }
    catch(const myclass & n)
    {
        n.f();
    }
}
</code>```

Here I throw an object of class myclass and use std :: current_exception() in the catch(...) block to get a std :: exception_ptr. Later I use std :: rethrow_exception to get the exception thrown again and I catch it, this time with catch(const myclass &), that allows me to, e.g., call f() and get Hello from myclass! printed out.

Now. I kind of imagine how I could implement something similar to std :: exception_ptr: a pointer to a base class, from which a template wrapper for each possible type inherits, and some rethrow virtual method that allows to throw again the exception. So far so good.

Now, how does std :: current_exception() work? How is it implemented? I tried to inspect it using my Xcode but I got a nice flashing question mark: ?. Is this some kind of primitive in C++11? Like, e.g., decltype or sizeof? Or is there another way to access the exception hidden in that catch(...)?

For example, is there a way to just print out an exception, whatever it is? Something like:

```<code>template <typename type> void printme(const type & exception)
{
    try
    {
        throw exception;
    }
    catch(...)
    {
        std :: cout << /* SOME MAGIC HERE */ << std :: endl;
    }
}
</code>```

I guess that std :: current_exception() would be using some similar way to access the exception, make a copy of it, and instantiate an appropriate std :: exception_ptr that can be later rethrown.

So am I missing something? I tried something trivial like catch(auto x) but it doesn't seem to do the job.

答:
Before std::exception_ptr there was boost::exception_ptr that attempts to implement this functionality without direct language support and consequently requires more boilerplate code to work. With Boost, you have to wrap the exception at the point of throw  with boost::enable_current_exception and throw the wrapper instead. I have not actually studied the implementation, but I imagine that the wrapper's copy constructor sets a thread-local pointer to point to itself (throw must copy its argument) which boost::current_exception then retrieves (possibly copying the exception to free store first, so that it can outlive the catch block). For catch (T x) to still work the wrapper has to wrap the original exception by inheriting from it, which makes it impossible to use with primitive types.

Another way is to copy the original, set the thread-local pointer to point to the copy and throw the original. This way works for any throwable type but current_exception would refer to a different instance than the one used o initialize the catch parameter.

Now std::exception_ptr has direct language support and does not have to jump through hoops or do excessive copying to archive this but the basic idea is that same: store the exception in a type-erased container that can rethrow it at the point of throw and point to that.

Title: How does std :: current_exception work?

Body:
Consider the following example:

class myclass
{
public:

    void f() const
    {
        std :: cout << "Hello from myclass!" << std :: endl;
    }
};

int main()
{
    std :: exception_ptr x;

    try
    {
        throw myclass();
    }
    catch(...)
    {
        x = std :: current_exception();
    }

    try
    {
        std :: rethrow_exception(x);
    }
    catch(const myclass & n)
    {
        n.f();
    }
}

Here I throw an object of class myclass and use std :: current_exception() in the catch(...) block to get a std :: exception_ptr. Later I use std :: rethrow_exception to get the exception thrown again and I catch it, this time with catch(const myclass &), that allows me to, e.g., call f() and get Hello from myclass! printed out.

Now. I kind of imagine how I could implement something similar to std :: exception_ptr: a pointer to a base class, from which a template wrapper for each possible type inherits, and some rethrow virtual method that allows to throw again the exception. So far so good.

Now, how does std :: current_exception() work? How is it implemented? I tried to inspect it using my Xcode but I got a nice flashing question mark: ?. Is this some kind of primitive in C++11? Like, e.g., decltype or sizeof? Or is there another way to access the exception hidden in that catch(...)?

For example, is there a way to just print out an exception, whatever it is? Something like:

template <typename type> void printme(const type & exception)
{
    try
    {
        throw exception;
    }
    catch(...)
    {
        std :: cout << /* SOME MAGIC HERE */ << std :: endl;
    }
}

I guess that std :: current_exception() would be using some similar way to access the exception, make a copy of it, and instantiate an appropriate std :: exception_ptr that can be later rethrown.

So am I missing something? I tried something trivial like catch(auto x) but it doesn't seem to do the job.


问:
How to sum values from a json field in Mariadb using JSON functions
Giving the following json field in a table column:

```<code>[
  {
    "payment_date":"2016-04-26",
    "amount":590,
    "payment_method":"2"
  },
  {
    "payment_date":"2017-05-01",
    "amount":208,
    "payment_method":"4"
  }
]
</code>```

How could I sum all the amounts?

The farthest I could get is

```<code>SELECT JSON_EXTRACT(`payment_lines`, '$[*].amount') FROM tbl
</code>```

which returns:

```<code>[590, 208]
</code>```

What I would need to get is this sum of 590 and 208. So to say that in this case there are two rows but there might be many more.

```<code>SELECT VERSION();
10.2.6-MariaDB-10.2.6+maria~jessie-log
</code>```

答:
Try:

MariaDB [(none)]> SELECT VERSION();
+-----------------------+
| VERSION()             |
+-----------------------+
| 10.2.6-MariaDB-10.2.6 |
+-----------------------+
1 row in set (0.00 sec)

MariaDB [(none)]> SET @`JSON` := '
    '> [
    '>   {
    '>     "payment_date":"2016-04-26",
    '>     "amount":590,
    '>     "payment_method":"2"
    '>   },
    '>   {
    '>     "payment_date":"2017-05-01",
    '>     "amount":208,
    '>     "payment_method":"4"
    '>   }
    '> ]';
Query OK, 0 rows affected (0.00 sec)

MariaDB [(none)]> SELECT
    ->   JsonGet_Int(
    ->     JSON_EXTRACT(@`JSON`, '$[*].amount'),
    ->     '[+]'
    ->   ) `SUM`;
+------+
| SUM  |
+------+
|  798 |
+------+
1 row in set (0.00 sec)
```

<p>See CONNECT JSON Table Type.</p>

<p><strong>UPDATE</strong></p>

<p>Check:</p>

<pre class="lang-sql prettyprint-override"><code>MariaDB [(none)]> SHOW VARIABLES WHERE `Variable_name` = 'plugin_dir';
+---------------+------------------------+
| Variable_name | Value                  |
+---------------+------------------------+
| plugin_dir    | /usr/lib/mysql/plugin/ |
+---------------+------------------------+
1 row in set (0.00 sec)

MariaDB [(none)]> \! ls -1 /usr/lib/mysql/plugin/ | grep 'ha_connect'
ha_connect.so

MariaDB [(none)]> CREATE FUNCTION IF NOT EXISTS jsonget_int RETURNS integer
    -> SONAME 'ha_connect.so';
Query OK, 0 rows affected (0.00 sec)
</code>```

Body:
Giving the following json field in a table column:

[
  {
    "payment_date":"2016-04-26",
    "amount":590,
    "payment_method":"2"
  },
  {
    "payment_date":"2017-05-01",
    "amount":208,
    "payment_method":"4"
  }
]

How could I sum all the amounts?

The farthest I could get is

SELECT JSON_EXTRACT(`payment_lines`, '$[*].amount') FROM tbl

which returns:

[590, 208]

What I would need to get is this sum of 590 and 208. So to say that in this case there are two rows but there might be many more.

SELECT VERSION();
10.2.6-MariaDB-10.2.6+maria~jessie-log

Body:
Try:

MariaDB [(none)]> SELECT VERSION();
+-----------------------+
| VERSION()             |
+-----------------------+
| 10.2.6-MariaDB-10.2.6 |
+-----------------------+
1 row in set (0.00 sec)

MariaDB [(none)]> SET @`JSON` := '
    '> [
    '>   {
    '>     "payment_date":"2016-04-26",
    '>     "amount":590,
    '>     "payment_method":"2"
    '>   },
    '>   {
    '>     "payment_date":"2017-05-01",
    '>     "amount":208,
    '>     "payment_method":"4"
    '>   }
    '> ]';
Query OK, 0 rows affected (0.00 sec)

MariaDB [(none)]> SELECT
    ->   JsonGet_Int(
    ->     JSON_EXTRACT(@`JSON`, '$[*].amount'),
    ->     '[+]'
    ->   ) `SUM`;
+------+
| SUM  |
+------+
|  798 |
+------+
1 row in set (0.00 sec)

See CONNECT JSON Table Type.

UPDATE

Check:

MariaDB [(none)]> SHOW VARIABLES WHERE `Variable_name` = 'plugin_dir';
+---------------+------------------------+
| Variable_name | Value                  |
+---------------+------------------------+
| plugin_dir    | /usr/lib/mysql/plugin/ |
+---------------+------------------------+
1 row in set (0.00 sec)

MariaDB [(none)]> \! ls -1 /usr/lib/mysql/plugin/ | grep 'ha_connect'
ha_connect.so

MariaDB [(none)]> CREATE FUNCTION IF NOT EXISTS jsonget_int RETURNS integer
    -> SONAME 'ha_connect.so';
Query OK, 0 rows affected (0.00 sec)


问:
PHP 7.1: no cURL with HTTP/2
My question is not about finding out if a server supports HTTP/2 (they both do) but how to make sure PHP is utilizing HTTP/2 with the correct cURL settings for the most current PHP version in CentOS (built from Remi's repository). My own answer addresses some oddities concerning this.

I've setup my CentOS 7 server to support HTTP/2 with the help of this fine guide: Setting up HTTP/2 on your web server

So I've got the latest releases, compiled and installed them and all is working fine. Pages are served with HTTP/2 headers, exactly as they should.

Now I'd like to utilize HTTP/2 functionality in my PHP scripts. Mainly by doing cURL calls in HTTP/2 fashion. I found out I needed to upgrade libcurl and build and compile it with specific HTTP/2 support. With some setbacks, I got it to work.

So curl -V tells me:

```<code>curl 7.55.0-DEV (x86_64-unknown-linux-gnu) libcurl/7.55.0-DEV OpenSSL/1.1.0f zlib/1.2.7 nghttp2/1.23.1
Release-Date: [unreleased]
Protocols: dict file ftp ftps gopher http https imap imaps pop3 pop3s rtsp smb smbs smtp smtps telnet tftp
Features: IPv6 Largefile NTLM NTLM_WB SSL libz TLS-SRP HTTP2 UnixSockets HTTPS-proxy
</code>```

Great!

And phpinfo() gives me the same version (7.55.0-DEV) in conjunction with the newly installed OpenSSL, which is:

OpenSSL 1.1.0f  25 May 2017

And Apache, BTW:

```<code>Server version: Apache/2.4.26 (Unix)
Server built:   Jul  7 2017 09:47:22
</code>```

However, when I write a simple PHP script with a cURL call and the CURLOPT_HTTP_VERSION option set to CURL_HTTP_VERSION_2_0, as outlined in this example: https://stackoverflow.com/a/37146586/1005334, it tells me the server does not have HTTP/2 support...

How can this be?

One thing I noticed, is the bit about the OpenSSL module in phpinfo() still mentions my old OpenSSL version (OpenSSL 1.0.1e-fips), although the OpenSSL-version mentioned with the cURL module states OpenSSL 1.1.0f.

I've installed PHP 7.1 (it currently stands at version 7.1.7) from Remi's repository, could it be it is built against an older OpenSSL version so it will not work with my newer one? I also read support in PHP 7 for HTTP/2 is not quite apparent, but I imagine it shouldn't be a problem, right?

Or is OpenSSL not the problem and should I look elsewhere, perhaps compiling PHP from source with some intended flags?

答:
Packages in my repository are built against standard base repository, so OpenSSL 1.0.1e and Curl 7.29.0 (using NSS).

So you have to rebuild EVERYTHING which use theses library to take benefit of new features (including PHP)

Title: PHP 7.1: no cURL with HTTP/2

Body:
My question is not about finding out if a server supports HTTP/2 (they both do) but how to make sure PHP is utilizing HTTP/2 with the correct cURL settings for the most current PHP version in CentOS (built from Remi's repository). My own answer addresses some oddities concerning this.

I've setup my CentOS 7 server to support HTTP/2 with the help of this fine guide: Setting up HTTP/2 on your web server

So I've got the latest releases, compiled and installed them and all is working fine. Pages are served with HTTP/2 headers, exactly as they should.

Now I'd like to utilize HTTP/2 functionality in my PHP scripts. Mainly by doing cURL calls in HTTP/2 fashion. I found out I needed to upgrade libcurl and build and compile it with specific HTTP/2 support. With some setbacks, I got it to work.

So curl -V tells me:

curl 7.55.0-DEV (x86_64-unknown-linux-gnu) libcurl/7.55.0-DEV OpenSSL/1.1.0f zlib/1.2.7 nghttp2/1.23.1
Release-Date: [unreleased]
Protocols: dict file ftp ftps gopher http https imap imaps pop3 pop3s rtsp smb smbs smtp smtps telnet tftp
Features: IPv6 Largefile NTLM NTLM_WB SSL libz TLS-SRP HTTP2 UnixSockets HTTPS-proxy

Great!

And phpinfo() gives me the same version (7.55.0-DEV) in conjunction with the newly installed OpenSSL, which is:

OpenSSL 1.1.0f  25 May 2017

And Apache, BTW:

Server version: Apache/2.4.26 (Unix)
Server built:   Jul  7 2017 09:47:22

However, when I write a simple PHP script with a cURL call and the CURLOPT_HTTP_VERSION option set to CURL_HTTP_VERSION_2_0, as outlined in this example: https://stackoverflow.com/a/37146586/1005334, it tells me the server does not have HTTP/2 support...

How can this be?

One thing I noticed, is the bit about the OpenSSL module in phpinfo() still mentions my old OpenSSL version (OpenSSL 1.0.1e-fips), although the OpenSSL-version mentioned with the cURL module states OpenSSL 1.1.0f.

I've installed PHP 7.1 (it currently stands at version 7.1.7) from Remi's repository, could it be it is built against an older OpenSSL version so it will not work with my newer one? I also read support in PHP 7 for HTTP/2 is not quite apparent, but I imagine it shouldn't be a problem, right?

Or is OpenSSL not the problem and should I look elsewhere, perhaps compiling PHP from source with some intended flags?


问:
R: How to make a data.table read-only without copying it (e. g. for data validation)
I do data wrangling (ETL) to load new data into a data base and want to let users implement their own data validation functions based on my existing data.table object that contains the prepared data.

How can I avoid that the user can change (modify) the data of my data.table within the validation function (intentionally or unintentionally) without making a copy (since it slows down the validation processing and therefore the whole ETL process)?

Locking/write-protecting the data is only required temporarily within the validation function...

Simplified example:

```<code>library(data.table)

DT <- as.data.table(mtcars)
DT[, row.number := 1:(.N)]  # add a row number column to allow identification of invalid rows
DT[c(3,6,7), cyl := 100]    # create some data errors (100 cylinders in the car)

# correctly implemented validate function (does not change the data)
validate <- function(data) {
  data[cyl > 10, .(row.number = row.number, col.name = "cyl", col.value = cyl,
                   severity = "ERROR", msg = "More than 10 cylinders")]
}

validate(DT)
</code>```

The output is OK and the data.table passed to the validate() function is not changed:

```<code>   row.number col.name col.value severity                    msg
1:          3      cyl       100    ERROR More than 10 cylinders
2:          6      cyl       100    ERROR More than 10 cylinders
3:          7      cyl       100    ERROR More than 10 cylinders
</code>```

What I want to avoid is that a user implements validate() like this and modifies the original data:

```<code>validate.with.side.effects <- function(data) {
  data[, max.cyl := 10]  # this adds a new column into the original data.table!
  data[cyl > max.cyl, .(row.number = row.number, col.name = "cyl", col.value = cyl, severity = "ERROR", msg = "More than 10 cylinders")]
}
</code>```

This implementation would modify the original data.table in DT!

Update:

There is an open feature request for that:
https://github.com/Rdatatable/data.table/issues/1086

The feature request is based on a similar requirement in a different context (immutable data in package): Lock or protect a data.table in R

Update 2

There is another similar feature request for that:
https://github.com/Rdatatable/data.table/issues/778

And another similar SO question:
How does one return a 'const' data.table from an R function?

Update 3: Could an immutable data.frame be used?

Generally yes (to make a data.frame read-only) but this solution does not meet the requirements of the question:

```<code>library(plyr)
idf <- idata.frame(DT)
idf[, max.cly := 10]
# Error in `:=`(max.cly, 10) :
#  Check that is.data.table(DT) == TRUE. Otherwise, := and `:=`(...) are defined for use in j, once only and in particular ways. See help(":=").

validate(idf)
# Error in `[.idf`(data, cyl > 10, .(row.number = row.number, col.name = "cyl",  :
#                                     object 'cyl' not found

# it is no longer a data.table...
class(idata.frame(DT))
# [1] "idf"         "environment"

# so that the data.table syntax does NOT work anymore...
idf[cyl > 10, .(row.number = row.number, col.name = "cyl", col.value = cyl,
                severity = "ERROR", msg = "More than 10 cylinders")]
# Error in `[.idf`(idf, cyl > 10, .(row.number = row.number, col.name = "cyl",  :
#                                    object 'cyl' not found
</code>```

答:
Would an immutable data frame allow you to accomplish what you need?

R's objects are usually immutable and employ copy-on-use semantics to apply functions (see this link for more details). data.table is a bit of an odd duck since it allows direct interaction with the object, bypassing copy-on-use which makes it more like a mutable object. The scenario you have described requires an object with both mutable and immutable properties. You may have to copy dt in order to apply validation without modifying the original object.

Body:
I do data wrangling (ETL) to load new data into a data base and want to let users implement their own data validation functions based on my existing data.table object that contains the prepared data.

How can I avoid that the user can change (modify) the data of my data.table within the validation function (intentionally or unintentionally) without making a copy (since it slows down the validation processing and therefore the whole ETL process)?

Locking/write-protecting the data is only required temporarily within the validation function...

Simplified example:

library(data.table)

DT <- as.data.table(mtcars)
DT[, row.number := 1:(.N)]  # add a row number column to allow identification of invalid rows
DT[c(3,6,7), cyl := 100]    # create some data errors (100 cylinders in the car)

# correctly implemented validate function (does not change the data)
validate <- function(data) {
  data[cyl > 10, .(row.number = row.number, col.name = "cyl", col.value = cyl,
                   severity = "ERROR", msg = "More than 10 cylinders")]
}

validate(DT)

The output is OK and the data.table passed to the validate() function is not changed:

   row.number col.name col.value severity                    msg
1:          3      cyl       100    ERROR More than 10 cylinders
2:          6      cyl       100    ERROR More than 10 cylinders
3:          7      cyl       100    ERROR More than 10 cylinders

What I want to avoid is that a user implements validate() like this and modifies the original data:

validate.with.side.effects <- function(data) {
  data[, max.cyl := 10]  # this adds a new column into the original data.table!
  data[cyl > max.cyl, .(row.number = row.number, col.name = "cyl", col.value = cyl, severity = "ERROR", msg = "More than 10 cylinders")]
}

This implementation would modify the original data.table in DT!

Update:

There is an open feature request for that:
https://github.com/Rdatatable/data.table/issues/1086

The feature request is based on a similar requirement in a different context (immutable data in package): Lock or protect a data.table in R

Update 2

There is another similar feature request for that:
https://github.com/Rdatatable/data.table/issues/778

And another similar SO question:
How does one return a 'const' data.table from an R function?

Update 3: Could an immutable data.frame be used?

Generally yes (to make a data.frame read-only) but this solution does not meet the requirements of the question:

library(plyr)
idf <- idata.frame(DT)
idf[, max.cly := 10]
# Error in `:=`(max.cly, 10) :
#  Check that is.data.table(DT) == TRUE. Otherwise, := and `:=`(...) are defined for use in j, once only and in particular ways. See help(":=").

validate(idf)
# Error in `[.idf`(data, cyl > 10, .(row.number = row.number, col.name = "cyl",  :
#                                     object 'cyl' not found

# it is no longer a data.table...
class(idata.frame(DT))
# [1] "idf"         "environment"

# so that the data.table syntax does NOT work anymore...
idf[cyl > 10, .(row.number = row.number, col.name = "cyl", col.value = cyl,
                severity = "ERROR", msg = "More than 10 cylinders")]
# Error in `[.idf`(idf, cyl > 10, .(row.number = row.number, col.name = "cyl",  :
#                                    object 'cyl' not found


问:
Python pandas read_csv - Loading tgz-zipped dataset in dataframe
I am trying to load the "California Housing" dataset into a pandas dataframe directly from the source URL. The URL points to a tgz-file that contains two files, cal_housing.data and cal_housing.domain.

Loading the file with pandas read_csv is working fine but it makes one error that I don't understand and want to get rid off: The first value of the dataframe (first row, first column) is replaced by the filename.

This is what cal_housing.data looks like:

```<code>0 -122.230000,37.880000,41.000000,880.000000,129.000000,322.000000,126.000000,8.325200,452600.000000
1 -122.220000,37.860000,21.000000,7099.000000,1106.000000,2401.000000,1138.000000,8.301400,358500.000000
2 -122.240000,37.850000,52.000000,1467.000000,190.000000,496.000000,177.000000,7.257400,352100.000000
3 ...
</code>```

This is what cal_housing.domain looks like:

```<code>0 longitude: continuous.
1 latitude: continuous.
2 housingMedianAge: continuous.
3 totalRooms: continuous.
4 totalBedrooms: continuous.
5 population: continuous.
6 households: continuous.
7 medianIncome: continuous.
8 medianHouseValue: continuous.
</code>```

This is what I do:

import pandas as pd
source = 'http://www.dcc.fc.up.pt/~ltorgo/Regression/cal_housing.tgz'
col_names = ['longitude', 'latitude', 'housingMedianAge', 'totalRooms', 'totalBedrooms', 'population', 'households', 'medianIncome', 'medianHouseValue']
data = pd.read_csv(source, compression='gzip', header=None, names=col_names).dropna()
print(type(data))
```

<p>This is what I get:</p>

```0      CaliforniaHousing/cal_housing.data     37.88              41.0   ...
1                             -122.220000     37.86              21.0   ...
2                             -122.240000     37.85              52.0   ...
...
```

<p>And finally, this is what I want to get:</p>

```0      -122.230000     37.88              41.0   ...
1      -122.220000     37.86              21.0   ...
2      -122.240000     37.85              52.0   ...
...
```

答:
From https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html

compression : {‘infer’, ‘gzip’, ‘bz2’, ‘zip’, ‘xz’, None}, default
  ‘infer’ For on-the-fly decompression of on-disk data. If ‘infer’, then
  use gzip, bz2, zip or xz if filepath_or_buffer is a string ending in
  ‘.gz’, ‘.bz2’, ‘.zip’, or ‘xz’, respectively, and no decompression
  otherwise. If using ‘zip’, the ZIP file must contain only one data
  file to be read in. Set to None for no decompression. New in version
  0.18.1: support for ‘zip’ and ‘xz’ compression.

I don't see tarballs in the list. It seems that you're trying to use 'gzip' on a gzipped tarball. I recommend extracting the files locally and reading the dataframes from the separate csv files.

Body:
I am trying to load the "California Housing" dataset into a pandas dataframe directly from the source URL. The URL points to a tgz-file that contains two files, cal_housing.data and cal_housing.domain.

Loading the file with pandas read_csv is working fine but it makes one error that I don't understand and want to get rid off: The first value of the dataframe (first row, first column) is replaced by the filename.

This is what cal_housing.data looks like:

0 -122.230000,37.880000,41.000000,880.000000,129.000000,322.000000,126.000000,8.325200,452600.000000
1 -122.220000,37.860000,21.000000,7099.000000,1106.000000,2401.000000,1138.000000,8.301400,358500.000000
2 -122.240000,37.850000,52.000000,1467.000000,190.000000,496.000000,177.000000,7.257400,352100.000000
3 ...

This is what cal_housing.domain looks like:

0 longitude: continuous.
1 latitude: continuous.
2 housingMedianAge: continuous.
3 totalRooms: continuous.
4 totalBedrooms: continuous.
5 population: continuous.
6 households: continuous.
7 medianIncome: continuous.
8 medianHouseValue: continuous.

This is what I do:

import pandas as pd
source = 'http://www.dcc.fc.up.pt/~ltorgo/Regression/cal_housing.tgz'
col_names = ['longitude', 'latitude', 'housingMedianAge', 'totalRooms', 'totalBedrooms', 'population', 'households', 'medianIncome', 'medianHouseValue']
data = pd.read_csv(source, compression='gzip', header=None, names=col_names).dropna()
print(type(data))

This is what I get:

0      CaliforniaHousing/cal_housing.data     37.88              41.0   ...
1                             -122.220000     37.86              21.0   ...
2                             -122.240000     37.85              52.0   ...
...

And finally, this is what I want to get:

0      -122.230000     37.88              41.0   ...
1      -122.220000     37.86              21.0   ...
2      -122.240000     37.85              52.0   ...
...


问:
PyCharm Jupyter notebook : Add Jupyter to the interpreter of the current project
I have a new project in PyCharm under it the project, I create a jupyter notebook
but when I run it I keep getting this error

```<code>Add Jupyter to the interpreter of the current project.
</code>```

I cant figure out what to do, I have reset the

Project Interpretor
  But no use

答:
You need to install jupyter for the project interpreter or the virtualenv that you use:

pip install jupyter

PyCharm support for the Jupyter Notebook is shaky IMO. You will probably need to restart it, and respond to dialog windows trying to connect to the default Notebook server location, localhost:8888. On my machine, canceling that request to connect strangely helps to finally see the output of the cells within PyCharm.

Body:
I have a new project in PyCharm under it the project, I create a jupyter notebook
but when I run it I keep getting this error

Add Jupyter to the interpreter of the current project.

I cant figure out what to do, I have reset the

Project Interpretor
  But no use


问:
pods file with multiple platforms for iOS
I want to combine 2 pods in my project. One is :

```<code>source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '8.0'
use_frameworks!

pod 'DJKFlipper'
</code>```

and the other is:

```<code>platform :ios, '9.0'
pod 'HQPagerViewController', :git=> 'https://github.com/quangpc/HQPagerViewController.git', :branch=> 'master'
</code>```

The issue is that one is asking for platform 8.0 and other is 9.0

I tried changing the whole file platform to 8.0, but get the following error: Specs satisfying the HQPagerViewController (from https://github.com/quangpc/HQPagerViewController.git, branch master), HQPagerViewController (= 1.0) dependency were found, but they required a higher minimum deployment target.

And if keep the target to 9.0, I get above 100 issues in the app after installing pod, as the target platform is incorrect.

I also tried this:

```<code>target 'Bhaskar' do
  # Comment the next line if you're not using Swift and don't want to use dynamic frameworks

 platform :ios, ‘9.0’
  use_frameworks!

  pod 'HQPagerViewController', :git=> 'https://github.com/quangpc/HQPagerViewController.git', :branch=> 'master'

end

target 'Bhaskar - FlipView’ do
  source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '8.0'
use_frameworks!

pod 'DJKFlipper'
end
</code>```

but getting an error here too. I have used pods maybe for the second time ever, and always worked with same platform. How can I combine these both?

Any help will be appreciated!
Thanks!

答: Since you have a minimum requirement of ios 9 for one pod your target platform should be 9. You could change the deployment target as mentioned by RJiryes above.  Since one of your pods is base 8, in most cases it should support ios 9 to. But in case your ios 8 pod has deprecated code from ios 9, in that case you will have to pork your pod and change it to support ios9. And It is important that you use up to date pods as using older version of pods are not good practice and may end up having issues.</p>

Body:
I want to combine 2 pods in my project. One is :

source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '8.0'
use_frameworks!

pod 'DJKFlipper'

and the other is:

platform :ios, '9.0'
pod 'HQPagerViewController', :git=> 'https://github.com/quangpc/HQPagerViewController.git', :branch=> 'master'

The issue is that one is asking for platform 8.0 and other is 9.0

I tried changing the whole file platform to 8.0, but get the following error: Specs satisfying the HQPagerViewController (from https://github.com/quangpc/HQPagerViewController.git, branch master), HQPagerViewController (= 1.0) dependency were found, but they required a higher minimum deployment target.

And if keep the target to 9.0, I get above 100 issues in the app after installing pod, as the target platform is incorrect.

I also tried this:

target 'Bhaskar' do
  # Comment the next line if you're not using Swift and don't want to use dynamic frameworks

 platform :ios, ‘9.0’
  use_frameworks!

  pod 'HQPagerViewController', :git=> 'https://github.com/quangpc/HQPagerViewController.git', :branch=> 'master'

end

target 'Bhaskar - FlipView’ do
  source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '8.0'
use_frameworks!

pod 'DJKFlipper'
end

but getting an error here too. I have used pods maybe for the second time ever, and always worked with same platform. How can I combine these both?

Any help will be appreciated!
Thanks!


问:
libssh2 - read file with SFTP
I'm using libssh2 lib to make SFTP session with the device.

But when I try to read a file and return the output, never return the complete file.

I think is because control chars (like \0) in the middle of the file.

Code:

```<code>sftp_handle = libssh2_sftp_open(sftp_session, filename, LIBSSH2_FXF_READ, 0);
if (!sftp_handle) return "-1";
char buf[99999];
int x = libssh2_sftp_read(sftp_handle, buf, sizeof(buf));
char * output = (char *)malloc(sizeof(char)*x);
memcpy(output, buf, x);
output[x] = '\0';
libssh2_sftp_close(sftp_handle);
</code>```

************Update 1************

The file I'm trying to read is a text file with almost all the ascii chars.

************Update 2************

x is the number of bytes writen into the buffer and the file have ~98kb (99999 bytes) but the libssh2_sftp_read function return 30000 to x.

答:
I assume that the code is just snippet and so the below comment may not be appropriate if there is a loop revolving around the base snippet.

The libssh2_sftp_read() may not read the full bytes of the file, but the maximum it can read in a single invocation. So this call may need to be repeated until either it returns zero or the scan the read buffer to check for EOF character. [EOF checking could make platform-dependent of your code]. Just highlighting the man page below.

Reads a block of data from an LIBSSH2_SFTP_HANDLE. This method is
  modelled after the POSIX read(2) function and uses the same calling
  semantics. libssh2_sftp_read, will attempt to read as much as possible
  however it may not fill all of buffer if the file pointer reaches the
  end or if further reads would cause the socket to block.

Title: libssh2 - read file with SFTP

Body:
I'm using libssh2 lib to make SFTP session with the device.

But when I try to read a file and return the output, never return the complete file.

I think is because control chars (like \0) in the middle of the file.

Code:

sftp_handle = libssh2_sftp_open(sftp_session, filename, LIBSSH2_FXF_READ, 0);
if (!sftp_handle) return "-1";
char buf[99999];
int x = libssh2_sftp_read(sftp_handle, buf, sizeof(buf));
char * output = (char *)malloc(sizeof(char)*x);
memcpy(output, buf, x);
output[x] = '\0';
libssh2_sftp_close(sftp_handle);

************Update 1************

The file I'm trying to read is a text file with almost all the ascii chars.

************Update 2************

x is the number of bytes writen into the buffer and the file have ~98kb (99999 bytes) but the libssh2_sftp_read function return 30000 to x.


问:
Division without using '/'
Can anyone tell me an efficient approach to perform the division operation without using '/'. I can calculate the integer value in log(n) steps using a method similar to binary search.

```<code>115/3
57 * 3 > 115
28 * 3 < 115
47 * 3 > 115
.
.
.
38 * 3 is quotient value .....
</code>```

But is there any other more efficient method?

答:
Division of two numbers without using / </p>

```<code>int div(int a,int b){

    if(b == 0)
         return -1;   //undefined
    else if (b == 1)
         return a;
    else if(b > 1){

       int count = 0;
       for(int i=b;i<=a;i+=b){
           count++;
       }
    }

    return count;

}
</code>```

Title: Division without using '/'

Body:
Can anyone tell me an efficient approach to perform the division operation without using '/'. I can calculate the integer value in log(n) steps using a method similar to binary search.

115/3
57 * 3 > 115
28 * 3 < 115
47 * 3 > 115
.
.
.
38 * 3 is quotient value .....

But is there any other more efficient method?

Body:
Division of two numbers without using /

int div(int a,int b){

    if(b == 0)
         return -1;   //undefined
    else if (b == 1)
         return a;
    else if(b > 1){

       int count = 0;
       for(int i=b;i<=a;i+=b){
           count++;
       }
    }

    return count;

}

ContentLicense: CC BY-SA 4.0


问:
How to roll back delete operation sql server?
I have an input page in my C# application whereby my boss can enter sales info.

This page also has a clear button, which clears the contents of the table in the database. This clear button was convenient for testing, however now in hindsight a mistake.

All the records in the table have been deleted. There are no backups either.

Long shot, but is there any way of recovering this data using only SQL Server 2008?

答:
Edit:( 2008 support)

SQL Data Compare Professional

This version of SQL Data Compare, you can compare a live database with or against backup files and synchronize data and deleted tables with their data contents from the backup file or backup file set to the live database.

Redgate even say this should do the same job, and that is why they have not come with any new version.

Will probably need a backup or transaction log ....

See this subject.


问:
How to invert drag rotation in A-Frame?
A simple question. I used 4-6 hours to finding this but not found.

Example, Im building a panorama viewer :

```

How to invert roation by drag mouse ? (Left to right , right to left - something like this)

答:
The ability to reverse the drag rotation direction is built in since v0.6.0 using this attribute on the camera

```<code>look-controls="reverseMouseDrag: true"
</code>```

Here's an example:

```

Note - according to this issue this still only works with mouse dragging on desktop machines, and does not work with touch dragging on mobile.

Title: How to invert drag rotation in A-Frame?

Body:
A simple question. I used 4-6 hours to finding this but not found.

Example, Im building a panorama viewer :

How to invert roation by drag mouse ? (Left to right , right to left - something like this)

Body:
The ability to reverse the drag rotation direction is built in since v0.6.0 using this attribute on the camera

look-controls="reverseMouseDrag: true"

Here's an example:

<script src="https://aframe.io/releases/0.6.0/aframe.min.js"></script>

<a-scene>
  <a-entity camera look-controls="reverseMouseDrag: true"></a-entity>
  <a-sky src="https://aframe.io/aframe/examples/boilerplate/panorama/puydesancy.jpg" rotation="0 -130 0"></a-sky>
</a-scene>

Note - according to this issue this still only works with mouse dragging on desktop machines, and does not work with touch dragging on mobile.