问:
MVP, set the view of the presenter to null on destroy?
I am currently trying to implement the MVP pattern on Android. However, I came to think about memory leaks (since the presenter holds a reference to the activity - the view). My question is, should I set the view of the presenter to null say onDestroy of the activity?

This is my main activity:

```<code>public class MainActivity extends AppCompatActivity implements MainView {
private Button loadUser;
private TextView mTextView;
@Inject
IMainPresenter mPresenter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    setUpViews();

    ((MyApp) getApplication()).getAppComponent().inject(this);
    mPresenter.setView(this);
}

private void setUpViews() {
    loadUser = (Button) findViewById(R.id.getUserBtn);
    loadUser.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            mPresenter.loadUserName(2);
        }
    });
    mTextView = (TextView) findViewById(R.id.userNameTextView);
}

@Override
public void setUserName(String userName) {
    mTextView.setText(userName);
}

@Override
protected void onDestroy() {
    super.onDestroy();
    mPresenter.setView(null);
}
}
</code>```

答: Could you not make the presenter lifecycle aware using https://developer.android.com/topic/libraries/architecture/lifecycle.html ? The presenter could then itself be responsible for setting the view to null when onDestroy() is called on the view.</p>

Body:
I am currently trying to implement the MVP pattern on Android. However, I came to think about memory leaks (since the presenter holds a reference to the activity - the view). My question is, should I set the view of the presenter to null say onDestroy of the activity?

This is my main activity:

public class MainActivity extends AppCompatActivity implements MainView {
private Button loadUser;
private TextView mTextView;
@Inject
IMainPresenter mPresenter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    setUpViews();

    ((MyApp) getApplication()).getAppComponent().inject(this);
    mPresenter.setView(this);
}

private void setUpViews() {
    loadUser = (Button) findViewById(R.id.getUserBtn);
    loadUser.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            mPresenter.loadUserName(2);
        }
    });
    mTextView = (TextView) findViewById(R.id.userNameTextView);
}

@Override
public void setUserName(String userName) {
    mTextView.setText(userName);
}

@Override
protected void onDestroy() {
    super.onDestroy();
    mPresenter.setView(null);
}
}


来源: stackexchange

问:
How to redirect to another page in a Facebook application?
How do I redirect to another page in a Facebook application?</p>

ContentLicense: CC BY-SA 3.0

Body: document.setLocation('url');

ContentLicense: CC BY-SA 2.5


问:
First event per patients
The attached code is supposed to return the first ORDER_PROC.ORDER_INST for each patient. I'm getting multiple records in some cases.
Any suggestions on a better approach?
Thanks
Steve</p>

```<code>SELECT DISTINCT
  ORDER_PROC.PAT_ENC_CSN_ID as ordercsn, Min(ORDER_PROC.ORDER_INST) as
  CodeStatus_Datetime, CLARITY_SER.PROV_NAME as CodeStatus_OrderProvider
FROM
  ORDER_PROC  with(nolock) , ORDER_METRICS with(nolock) , CLARITY_SER
  with(nolock)

WHERE
  ORDER_PROC.ORDER_PROC_ID = ORDER_METRICS.ORDER_ID AND
  ORDER_METRICS.ORDERING_PROV_ID = CLARITY_SER.PROV_ID AND
  --ORDER_PROC.REASON_FOR_CANC_C IS  NULL AND
  (ORDER_PROC.PROC_CODE = 'COD1' OR
  ORDER_PROC.PROC_CODE = 'COD2' OR
  ORDER_PROC.PROC_CODE = 'COD3'
  )
GROUP by
ORDER_PROC.PAT_ENC_CSN_ID, ORDER_PROC.ORDER_INST,CLARITY_SER.PROV_NAME
</code>```

答:
Use ROW_NUMBER() to create partition for each patient

```<code>SELECT *
FROM (
    SELECT OP.PAT_ENC_CSN_ID as ordercsn,
           OP.ORDER_INST,
           CodeStatus_Datetime,
           CS.PROV_NAME as CodeStatus_OrderProvider,
           ROW_NUMBER() OVER (PARTITION BY OP.PAT_ENC_CSN_ID
                               ORDER BY OP.ORDER_INST) as rn
    FROM  ORDER_PROC  OP
    JOIN  ORDER_METRICS OM
      OP.ORDER_PROC_ID = OM.ORDER_ID
    JOIN CLARITY_SER  CS
      OM.ORDERING_PROV_ID = CS.PROV_ID

    WHERE
      OP.PROC_CODE IN ('COD1','COD2','COD3')
   ) as T
 WHERE rn = 1
</code>```

Title: First event per patients

Body:
The attached code is supposed to return the first ORDER_PROC.ORDER_INST for each patient. I'm getting multiple records in some cases.
Any suggestions on a better approach?
Thanks
Steve

SELECT DISTINCT
  ORDER_PROC.PAT_ENC_CSN_ID as ordercsn, Min(ORDER_PROC.ORDER_INST) as
  CodeStatus_Datetime, CLARITY_SER.PROV_NAME as CodeStatus_OrderProvider
FROM
  ORDER_PROC  with(nolock) , ORDER_METRICS with(nolock) , CLARITY_SER
  with(nolock)

WHERE
  ORDER_PROC.ORDER_PROC_ID = ORDER_METRICS.ORDER_ID AND
  ORDER_METRICS.ORDERING_PROV_ID = CLARITY_SER.PROV_ID AND
  --ORDER_PROC.REASON_FOR_CANC_C IS  NULL AND
  (ORDER_PROC.PROC_CODE = 'COD1' OR
  ORDER_PROC.PROC_CODE = 'COD2' OR
  ORDER_PROC.PROC_CODE = 'COD3'
  )
GROUP by
ORDER_PROC.PAT_ENC_CSN_ID, ORDER_PROC.ORDER_INST,CLARITY_SER.PROV_NAME

Body:
Use ROW_NUMBER() to create partition for each patient

SELECT *
FROM (
    SELECT OP.PAT_ENC_CSN_ID as ordercsn,
           OP.ORDER_INST,
           CodeStatus_Datetime,
           CS.PROV_NAME as CodeStatus_OrderProvider,
           ROW_NUMBER() OVER (PARTITION BY OP.PAT_ENC_CSN_ID
                               ORDER BY OP.ORDER_INST) as rn
    FROM  ORDER_PROC  OP
    JOIN  ORDER_METRICS OM
      OP.ORDER_PROC_ID = OM.ORDER_ID
    JOIN CLARITY_SER  CS
      OM.ORDERING_PROV_ID = CS.PROV_ID

    WHERE
      OP.PROC_CODE IN ('COD1','COD2','COD3')
   ) as T
 WHERE rn = 1


问:
User session expires after every deploy. Using asp.net core, identity and azure
I have an asp.net core web application deployed on Azure App Service, the problem is that every time I publish changes to the server, (no matter if it's via vs publish or via vs team services ci) the users sessions expires and every user has to login again.

How can I avoid this?
Thanks for your help.

答:
Everytime you publish build your AppDomain recycled, so session state will be changed and expired.
You can read in details in this question
Losing Session State

If you want to keep your user logged-in after build, maybe use another technique. Like Access Tokens for example.

Read more from here

https://samueleresca.net/2016/12/developing-token-authentication-using-asp-net-core/
https://dotnetthoughts.net/token-based-authentication-in-aspnet-core/


问:
sql server 2012 service pack 1 or later is required upgrade
I am using sql 2012 but I dont know which service pack.
I want to Upgrade 2014 but when ı update gives
"sql server 2012 or later is required upgrade" error.now I am downloading sql server 2012 service pack 3.but I dont know solutions.</p>

答: Running SELECT @@VERSION in SSMS should tell you the version of sql server you are using


问:
Page title not showing up, why not?
I'm trying to set the page title by doing something this in my code:  this.Title = "string"; but it won't show up at all. Image is here for clarity, I guess. The red part is where the text should be.

Edit: Alright first off sorry for the lack of information but wasn't sure what to show and what not. I'm trying to change the title based on what the name of an item is that I am getting from the message (I don't think the message is being received, I thought it was since this isn't the only one I'm using. looking into it now, thank you guys for that).

message:
MessagingCenter.Subscribe<ZonePage, string>(this, "loginname", (s, arg) => { name = arg; this.Title = name; });

xaml markup:

```<code><ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         x:Class="MobileApp.LoginPage">
<StackLayout BackgroundColor="#15a4fa">
    <StackLayout VerticalOptions="CenterAndExpand" Padding="50, 0, 50, 50">
        <Image Source="logotext.png" />
    </StackLayout>

    <StackLayout BackgroundColor="White" VerticalOptions="StartAndExpand" Padding="25, 20, 25, 20">
        <Entry x:Name="userNameEntry" TextColor="Black" Placeholder="Username" HorizontalOptions="Fill"/>
        <Entry x:Name="passwordEntry" IsEnabled="True" TextColor="Black" IsPassword="True" Placeholder="Password" HorizontalOptions="Fill"/>
        <StackLayout Orientation="Horizontal">
            <Switch x:Name="Remember" IsToggled="False" HorizontalOptions="Center"/>
            <Label Text="Remember me" TextColor="Black" Font="18" HorizontalOptions="Start"/>
        </StackLayout>
    </StackLayout>

    <StackLayout Padding="75, 0, 75, 50" VerticalOptions="Center">
        <Picker x:Name="picker"  TextColor="White" Title="Select an Identity Source">
            <Picker.Items>
                <!-- Items added dynamically from xaml.cs -->
            </Picker.Items>
        </Picker>
    </StackLayout>

    <StackLayout Padding="0, 0, 0, 0" VerticalOptions="StartAndExpand" HorizontalOptions="Center" Orientation="Horizontal">
        <Button Text="Login" BackgroundColor="White" TextColor="Black" VerticalOptions="Start" HorizontalOptions="Center" Clicked="OnLogin"/>
    </StackLayout>
</StackLayout>
</code>```

答:
You are probably setting the title to the wrong page.
From what I understand from your image you are using a MasterDetail page.
If I'm correct this MasterDetailPage holds your LoginPage in where you try to change the title.
But instead of trying to change the title of the LoginPage try to change the title of the MasterDetailPage which holds the LoginPage as Detail. </p>

Title: Page title not showing up, why not?

Body:
I'm trying to set the page title by doing something this in my code:  this.Title = "string"; but it won't show up at all. Image is here for clarity, I guess. The red part is where the text should be.

Edit: Alright first off sorry for the lack of information but wasn't sure what to show and what not. I'm trying to change the title based on what the name of an item is that I am getting from the message (I don't think the message is being received, I thought it was since this isn't the only one I'm using. looking into it now, thank you guys for that).

message:
MessagingCenter.Subscribe<ZonePage, string>(this, "loginname", (s, arg) => { name = arg; this.Title = name; });

xaml markup:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         x:Class="MobileApp.LoginPage">
<StackLayout BackgroundColor="#15a4fa">
    <StackLayout VerticalOptions="CenterAndExpand" Padding="50, 0, 50, 50">
        <Image Source="logotext.png" />
    </StackLayout>

    <StackLayout BackgroundColor="White" VerticalOptions="StartAndExpand" Padding="25, 20, 25, 20">
        <Entry x:Name="userNameEntry" TextColor="Black" Placeholder="Username" HorizontalOptions="Fill"/>
        <Entry x:Name="passwordEntry" IsEnabled="True" TextColor="Black" IsPassword="True" Placeholder="Password" HorizontalOptions="Fill"/>
        <StackLayout Orientation="Horizontal">
            <Switch x:Name="Remember" IsToggled="False" HorizontalOptions="Center"/>

        </StackLayout>
    </StackLayout>

    <StackLayout Padding="75, 0, 75, 50" VerticalOptions="Center">
        <Picker x:Name="picker"  TextColor="White" Title="Select an Identity Source">
            <Picker.Items>

            </Picker.Items>
        </Picker>
    </StackLayout>

    <StackLayout Padding="0, 0, 0, 0" VerticalOptions="StartAndExpand" HorizontalOptions="Center" Orientation="Horizontal">
        <Button Text="Login" BackgroundColor="White" TextColor="Black" VerticalOptions="Start" HorizontalOptions="Center" Clicked="OnLogin"/>
    </StackLayout>
</StackLayout>


问:
Does .Any with a predicate have to generate the resulting list before it looks for .Any
I've got a List with 1,000,000 complex objects.  I need to create another list with a subset of those objects, keeping the original list unchanged.  At this point in the code, I know for certain that bigList is not null, and that it has at least 1 item.

My original code:

```<code>var smallList = bigList.Where(csvrec => csvrec.PreApprovalAmount <= 0 || csvrec.PreApprovalAmount > csvrec.ReplacementAmount).ToList();
</code>```

My team lead said that there were several problems with my code.  He said that .Where could result in null, and that calling .ToList() would cause a null exception.  So, in order to avoid that, he said I needed to change my code to:

```<code>var smallList = new List<CSVLines>();
if(bigList.Any(csvrec => csvrec.PreApprovalAmount <= 0 || csvrec.PreApprovalAmount > csvrec.ReplacementAmount))
{
    smallList = bigList.Where(csvrec => csvrec.PreApprovalAmount <= 0 || csvrec.PreApprovalAmount > csvrec.ReplacementAmount).ToList();
}
</code>```

I don't think that .Where can ever result in a null exception.

I don't think that smallList will not ever be null.  It could be a
list with 0 elements, but not null.

Doing .Any with a predicate means it has to generate the list, then
determine if it has at least 1 element, and then my code will have
to generate the same list again to assign it to smallList.

Am I correct?  Are the proposed changes from my team lead basically doubling the amount of work to create this list with no real benefit?

答:
Does .Any with a predicate have to generate the resulting list before
  it looks for .Any

No, Enumerable.Any does not need to do that. MSDN:

The enumeration of source is stopped as soon as the result can be
  determined.

The method takes a sequence and a predicate, then enumerates the sequence until the predicate matches once and returns true. If no item matches false is returned. So if the first item already matches the result does not need to be enumerated. In Source-code:

```<code>foreach (TSource element in source) {
    if (predicate(element)) return true;
}
return false;
</code>```

Are the proposed changes from my team lead basically doubling the
  amount of work to create this list with no real benefit?

Yes, first checking if any item matches and then using Where to filter is unnecessary overhead in this case. It is not doubling the overhead because Any stops at the first matching but it is overhead (it's doubled if there is no matching item, because the sequence has to be enumerated twice).

.Where could result in null, and that calling .ToList() would cause
  a null exception.

No, that's impossible. Enumerable.Where never returns null, it's a filter on the input sequence and if no item matches the predicate Enumerable.Empty<T> is returned.

Maybe he was confused because a query gets executed at the ToList, so if there was a NullReferenceException somewhere in the query, then you see this exception at the ToList(or any other method that executes it). Look at following query that throws an exception:

```<code>var query = "foo".Select(c => { throw new NullReferenceException(); return 1; });
List<int> list = query.ToList(); // exception here not in first line
</code>```

Body:
I've got a List with 1,000,000 complex objects.  I need to create another list with a subset of those objects, keeping the original list unchanged.  At this point in the code, I know for certain that bigList is not null, and that it has at least 1 item.

My original code:

var smallList = bigList.Where(csvrec => csvrec.PreApprovalAmount <= 0 || csvrec.PreApprovalAmount > csvrec.ReplacementAmount).ToList();

My team lead said that there were several problems with my code.  He said that .Where could result in null, and that calling .ToList() would cause a null exception.  So, in order to avoid that, he said I needed to change my code to:

var smallList = new List<CSVLines>();
if(bigList.Any(csvrec => csvrec.PreApprovalAmount <= 0 || csvrec.PreApprovalAmount > csvrec.ReplacementAmount))
{
    smallList = bigList.Where(csvrec => csvrec.PreApprovalAmount <= 0 || csvrec.PreApprovalAmount > csvrec.ReplacementAmount).ToList();
}

I don't think that .Where can ever result in a null exception.

I don't think that smallList will not ever be null.  It could be a
list with 0 elements, but not null.

Doing .Any with a predicate means it has to generate the list, then
determine if it has at least 1 element, and then my code will have
to generate the same list again to assign it to smallList.

Am I correct?  Are the proposed changes from my team lead basically doubling the amount of work to create this list with no real benefit?

Body:
Does .Any with a predicate have to generate the resulting list before
  it looks for .Any

No, Enumerable.Any does not need to do that. MSDN:

The enumeration of source is stopped as soon as the result can be
  determined.

The method takes a sequence and a predicate, then enumerates the sequence until the predicate matches once and returns true. If no item matches false is returned. So if the first item already matches the result does not need to be enumerated. In Source-code:

foreach (TSource element in source) {
    if (predicate(element)) return true;
}
return false;

Are the proposed changes from my team lead basically doubling the
  amount of work to create this list with no real benefit?

Yes, first checking if any item matches and then using Where to filter is unnecessary overhead in this case. It is not doubling the overhead because Any stops at the first matching but it is overhead (it's doubled if there is no matching item, because the sequence has to be enumerated twice).

.Where could result in null, and that calling .ToList() would cause
  a null exception.

No, that's impossible. Enumerable.Where never returns null, it's a filter on the input sequence and if no item matches the predicate Enumerable.Empty<T> is returned.

Maybe he was confused because a query gets executed at the ToList, so if there was a NullReferenceException somewhere in the query, then you see this exception at the ToList(or any other method that executes it). Look at following query that throws an exception:

var query = "foo".Select(c => { throw new NullReferenceException(); return 1; });
List<int> list = query.ToList(); // exception here not in first line


问:
Racket pattern matching of lists
I am trying to do pattern matching with lists, but for some reason I get an unexpected match when I do the following:

```<code>> (define code '(h1 ((id an-id-here)) Some text here))
> (define code-match-expr '(pre ([class brush: python]) ...))
> (match code
    [code-match-expr #t]
    [_ #f])
#t
</code>```

Question: Why does code match code-match-expr?

Practical use-case

I tried this in the Racket REPL, because I actually want to solve another practical problem: using Pollen's pygments wrapping functions to highlight code, which will be output as HTML later on. For this purpose I wrote the following code, where the problem occurs:

```<code>(define (read-post-from-file path)
  (Post-from-content (replace-code-xexprs (parse-markdown path))))

(define (replace-code-xexprs list-of-xexprs)
  ;; define known languages
  (define KNOWN-LANGUAGE-SYMBOLS
    (list 'python
          'racket
          'html
          'css
          'javascript
          'erlang
          'rust))
  ;; check if it matches for a single language's match expression
  ;; if it mathces any language, return that language's name as a symbol
  (define (get-matching-language an-xexpr)
    (define (matches-lang-match-expr? an-xexpr lang-symbol)
      (display "XEXPR:") (displayln an-xexpr)
      (match an-xexpr
        [`(pre ([class brush: ,lang-symbol]) (code () ,more ...)) lang-symbol]
        [`(pre ([class brush: ,lang-symbol]) ,more ...) lang-symbol]
        [_ #f]))

    (ormap (lambda (lang-symbol)
             ;; (display "trying to match ")
             ;; (display an-xexpr)
             ;; (display " against ")
             ;; (displayln lang-symbol)
             (matches-lang-match-expr? an-xexpr lang-symbol))
           KNOWN-LANGUAGE-SYMBOLS))

  ;; replace code in an xexpr with highlightable code
  ;; TODO: What happens if the code is in a lower level of the xexpr?
  (define (replace-code-in-single-xexpr an-xexpr)
    (let ([matching-language (get-matching-language an-xexpr)])
      (cond [matching-language (code-highlight an-xexpr matching-language)]
            [else an-xexpr])))

  ;; apply the check to all xexpr
  (map replace-code-in-single-xexpr list-of-xexprs))

(define (code-highlight language code)
  (highlight language code))
</code>```

In this example I am parsing a markdown file which has the following content:

```<code># Code Demo

```python
def hello():
    print("Hello World!")
```
</code>```

And I get the following xexprs:

1.

```<code>(h1 ((id code-demo)) Code Demo)
</code>```

2.

```<code>(pre ((class brush: python)) (code () def hello():
    print("Hello World!")))
</code>```

However, none of those match for some reason.

答:
Make sure you're clear what it is you are matching. In Racket x-expressions, attribute names are symbols but the values are strings. So the expression you're matching would be something like (pre ([class "brush: js"])) ___) -- not (pre ([class brush: js]) ___).

To match that string and extract the part after "brush: ", you could use a pregexp match pattern. Here is a snippet that Frog uses to extract the language to give to Pygments:

```<code>(for/list ([x xs])
  (match x
    [(or `(pre ([class ,brush]) (code () ,(? string? texts) ...))
         `(pre ([class ,brush]) ,(? string? texts) ...))
     (match brush
       [(pregexp "\\s*brush:\\s*(.+?)\\s*$" (list _ lang))
        `(div ([class ,(str "brush: " lang)])
              ,@(pygmentize (apply string-append texts) lang
                            #:python-executable python-executable
                            #:line-numbers? line-numbers?
                            #:css-class css-class))]
       [_ `(pre ,@texts)])]
    [x x])))
</code>```

(Here pygmentize is a function defined in other Frog source code; it's a wrapper around running Pygments as a separate process and piping text between it. But you could substitute another way of using Pygments or any other syntax highlighter. That's N/A for your question about match. I mention it just so that doesn't become a distraction and another embedded question. :))

Title: Racket pattern matching of lists

Body:
I am trying to do pattern matching with lists, but for some reason I get an unexpected match when I do the following:

> (define code '(h1 ((id an-id-here)) Some text here))
> (define code-match-expr '(pre ([class brush: python]) ...))
> (match code
    [code-match-expr #t]
    [_ #f])
#t

Question: Why does code match code-match-expr?

Practical use-case

I tried this in the Racket REPL, because I actually want to solve another practical problem: using Pollen's pygments wrapping functions to highlight code, which will be output as HTML later on. For this purpose I wrote the following code, where the problem occurs:

(define (read-post-from-file path)
  (Post-from-content (replace-code-xexprs (parse-markdown path))))

(define (replace-code-xexprs list-of-xexprs)
  ;; define known languages
  (define KNOWN-LANGUAGE-SYMBOLS
    (list 'python
          'racket
          'html
          'css
          'javascript
          'erlang
          'rust))
  ;; check if it matches for a single language's match expression
  ;; if it mathces any language, return that language's name as a symbol
  (define (get-matching-language an-xexpr)
    (define (matches-lang-match-expr? an-xexpr lang-symbol)
      (display "XEXPR:") (displayln an-xexpr)
      (match an-xexpr
        [`(pre ([class brush: ,lang-symbol]) (code () ,more ...)) lang-symbol]
        [`(pre ([class brush: ,lang-symbol]) ,more ...) lang-symbol]
        [_ #f]))

    (ormap (lambda (lang-symbol)
             ;; (display "trying to match ")
             ;; (display an-xexpr)
             ;; (display " against ")
             ;; (displayln lang-symbol)
             (matches-lang-match-expr? an-xexpr lang-symbol))
           KNOWN-LANGUAGE-SYMBOLS))

  ;; replace code in an xexpr with highlightable code
  ;; TODO: What happens if the code is in a lower level of the xexpr?
  (define (replace-code-in-single-xexpr an-xexpr)
    (let ([matching-language (get-matching-language an-xexpr)])
      (cond [matching-language (code-highlight an-xexpr matching-language)]
            [else an-xexpr])))

  ;; apply the check to all xexpr
  (map replace-code-in-single-xexpr list-of-xexprs))

(define (code-highlight language code)
  (highlight language code))

In this example I am parsing a markdown file which has the following content:

# Code Demo

```python
def hello():
    print("Hello World!")
```

And I get the following xexprs:

1.

(h1 ((id code-demo)) Code Demo)

2.

(pre ((class brush: python)) (code () def hello():
    print("Hello World!")))

However, none of those match for some reason.

Body:
Make sure you're clear what it is you are matching. In Racket x-expressions, attribute names are symbols but the values are strings. So the expression you're matching would be something like (pre ([class "brush: js"])) ___) -- not (pre ([class brush: js]) ___).

To match that string and extract the part after "brush: ", you could use a pregexp match pattern. Here is a snippet that Frog uses to extract the language to give to Pygments:

(for/list ([x xs])
  (match x
    [(or `(pre ([class ,brush]) (code () ,(? string? texts) ...))
         `(pre ([class ,brush]) ,(? string? texts) ...))
     (match brush
       [(pregexp "\\s*brush:\\s*(.+?)\\s*$" (list _ lang))
        `(div ([class ,(str "brush: " lang)])
              ,@(pygmentize (apply string-append texts) lang
                            #:python-executable python-executable
                            #:line-numbers? line-numbers?
                            #:css-class css-class))]
       [_ `(pre ,@texts)])]
    [x x])))

(Here pygmentize is a function defined in other Frog source code; it's a wrapper around running Pygments as a separate process and piping text between it. But you could substitute another way of using Pygments or any other syntax highlighter. That's N/A for your question about match. I mention it just so that doesn't become a distraction and another embedded question. :))


问:
net service in android app
I have a net service in my app, for now it doesn't matter if it's a thread in the Application context or a service, what does matter is i have some trouble getting response properly.

The service is working, and i do get responses, right now i work with the observer design patter which is a bitch in android :-( i have to remove the listener in on destroy and then check the network if it is all ready finished and handle different scenarios.

I want to change my approach, but i'm not sure what's the right android way, it seems like activities are made for polling which is bad for my architecture and error prone :-(.

I thought of the folowing two methods but non seem to give me a real solution:

create a braodcast receiver that
    will send a broadcase with a flag if
    response or error arrived from the
    net, it's apt to the activity to
    poll the right data and handle. i do
    wonder about this since if i
    register for broacast i basically
    have to remove the listener in on
    pause, so i CAN miss a broadcast,
    then it's back to check the net
    state in onCreate, same like what
    i'm doing now - sucks...

register the activity that whats an event and sent it an intent using startActivity but here if the activity is in on pause or stop i'll bring it to the front, i don't want this kind of behavior, i only want that the activity will get the event no matter what, and starting to wonder if there's a way to do that.

The landscape\portrait event are killing me, any way out of it ?

答:
i discovered the following:

i can decide to handle the
landscape\portrait events myself and
then i eliminate 90% of the problem

i can use Broadcast Receivers but with sticky flag on that will cause the intent to wait for me, i just have to check first if i got the intent once i'll gt it once more if it's sticky (meaning in landscape \ portrait i may get it twice on screen rotation)

if i get new intent that doesn't kill my app (depends on the intent) i get it in onNewIntent() method. i can put some init functions that are dependant on those values in a seperate init function that gathers them all to share them between onCreate and onNewIntnet.

Title: net service in android app


答:
He said that .Where could result in null, and that calling .ToList() would cause a null exception.

The only reason a Where could cause a null reference exception is if its target is null or its predicate runs into a null reference exception. If nothing matches, .Where returns an empty IEnumerable<T>, not a null.

Adding a call to Any is completely superfluous. Although it does not recreate the entire list, it still uses some CPU cycles in evaluating the predicate before returning true or false. It is still O(n), though, so when no match is found, the condition is evaluated for the entire sequence.

Adding a call to Any also decreases readability of your code, which is arguably worse than wasting CPU cycles.

Title: Does .Any with a predicate have to generate the resulting list before it looks for .Any


问:
BeyondCompare4 update session defaults doesn't work
I changed the encoding of my project from gbk to UTF-8,
then I use beyondcompare4(Version 4.2.3) to make sure they(two folders) are only encoding differences.

however,every time I open the old file in the compare left side, new in right.
file in left side shows [western european] encoding,
I have to select ANSI repeatedly, or some chinese words will be messy.
file in right will auto-detect UTF-8,which very nice.

I want to set just one time, then enabled to remaining file.

so I use the session settings below, not work,
I tried [update for all the files within parent session], not work too.

it will change back,,

Are there any good ideas can compare file ignore encoding,
or just show the file in right encoding ?

答:
Only session settings in the Importance, Alignment, and Replacements tabs can be set as session defaults.

To see what session settings can be set as defaults, open Beyond Compare to the Home view. In the Sessions list on the left side, expand New. Select Text Compare. Then click the Edit Defaults button.

A character encoding override that affects all comparisons can be set in a file format. To set the encoding, open Tools | File Formats. Select the format with a mask that matches your files. Go to the Conversion tab. Change the Encoding dropdown from Detect to your preferred encoding.

Encoding overrides in file formats affect both sides, it isn't possible to assign a global encoding override that is side specific.


问:
Dapper: Converting a string to an enum
I'm new to Dapper and I'm trying to figure out if it can handle mapping database strings to enums; it doesn't happen for me by default.

For example, say I use this SQL

```<code>select customer_type from customers
</code>```

and this class

```<code>public class Customer
{
    ...
    public CustomerType CustomerType { get; set; }
    ...
}
</code>```

with this enum

```<code>public enum CustomerType
{
     Unknown,
     SomeCustomerType,
     ...
}
</code>```

In this case I always end up with the default enum value (Unknown) rather than a mapping of the string value from the database.

Anyone know how I can achieve this?

Edit:
I know that this is possible with an number field because an number will convert to an enum, but that has the drawback of having to ensure that the database id and enum are kept in sync. I'm looking for something similar but with string.

答:
If you alias the column name to have the same name as your property that should work too:

SELECT
   REPLACE(customer_type, ' ','') As CustomerType
FROM customers

You can also use the replace function to remove white spaces in case the values for the customer_type field in the database has any.

Title: Dapper: Converting a string to an enum

Body:
I'm new to Dapper and I'm trying to figure out if it can handle mapping database strings to enums; it doesn't happen for me by default.

For example, say I use this SQL

select customer_type from customers

and this class

public class Customer
{
    ...
    public CustomerType CustomerType { get; set; }
    ...
}

with this enum

public enum CustomerType
{
     Unknown,
     SomeCustomerType,
     ...
}

In this case I always end up with the default enum value (Unknown) rather than a mapping of the string value from the database.

Anyone know how I can achieve this?

Edit:
I know that this is possible with an number field because an number will convert to an enum, but that has the drawback of having to ensure that the database id and enum are kept in sync. I'm looking for something similar but with string.


问:
Cannot search mongo db by timestamp
Hey I am having an issue with this line of code

```<code> db.eventrecords.find({ timestamp: { $gte:ISODate("2013-11-19T14:00:00Z"),
 $lt: ISODate("2018-11-19T20:00:00Z") } })
</code>```

This query and any similiar query using timestamp returns nothing even though I know there is data there.

Here is an example of that data returned with d.eventrecords.find()

```<code> { "_id" : ObjectId("5a0c9e22da6e704174881b6c"), "userId" :
  "59e0265c387d7d22a4f81533", "timestamp" : "Wed Nov 15 2017 15:05:54 GMT-
   0500 (Eastern Standard Time)", "name" : "LOGIN" }
</code>```

Can anyone shed light on why this query won't return data?

答: You can't do that because you store dates as string (not timestamp).</p>

Title: Cannot search mongo db by timestamp

Body:
Hey I am having an issue with this line of code

 db.eventrecords.find({ timestamp: { $gte:ISODate("2013-11-19T14:00:00Z"),
 $lt: ISODate("2018-11-19T20:00:00Z") } })

This query and any similiar query using timestamp returns nothing even though I know there is data there.

Here is an example of that data returned with d.eventrecords.find()

 { "_id" : ObjectId("5a0c9e22da6e704174881b6c"), "userId" :
  "59e0265c387d7d22a4f81533", "timestamp" : "Wed Nov 15 2017 15:05:54 GMT-
   0500 (Eastern Standard Time)", "name" : "LOGIN" }

Can anyone shed light on why this query won't return data?


问:
Cross compiling problems
I have installed the cross compile tools in the ubuntu 16.04.And when I type arm-linux-gnueabihf-gcc -vin the command line.The command line shows that the cross compiler can work as follows:

```<code>Using built-in specs.
COLLECT_GCC=arm-linux-gnueabihf-gcc
COLLECT_LTO_WRAPPER=/home/nju/ti-processor-linux-sdk/linux-devkit/sysroots/x86_64-arago-linux/usr/bin/../libexec/gcc/arm-linux-gnueabihf/6.2.1/lto-wrapper
Target: arm-linux-gnueabihf
Configured with: /home/tcwg-buildslave/workspace/tcwg-make-release/label/docker-trusty-amd64-tcwg-build/target/arm-linux-gnueabihf/snapshots/gcc-linaro-6.2-2016.11/configure SHELL=/bin/bash --with-mpc=/home/tcwg-buildslave/workspace/tcwg-make-release/label/docker-trusty-amd64-tcwg-build/target/arm-linux-gnueabihf/_build/builds/destdir/x86_64-unknown-linux-gnu --with-mpfr=/home/tcwg-buildslave/workspace/tcwg-make-release/label/docker-trusty-amd64-tcwg-build/target/arm-linux-gnueabihf/_build/builds/destdir/x86_64-unknown-linux-gnu --with-gmp=/home/tcwg-buildslave/workspace/tcwg-make-release/label/docker-trusty-amd64-tcwg-build/target/arm-linux-gnueabihf/_build/builds/destdir/x86_64-unknown-linux-gnu --with-gnu-as --with-gnu-ld --disable-libstdcxx-pch --disable-libmudflap --with-cloog=no --with-ppl=no --with-isl=no --disable-nls --enable-c99 --enable-gnu-indirect-function --disable-multilib --with-tune=cortex-a9 --with-arch=armv7-a --with-fpu=vfpv3-d16 --with-float=hard --with-mode=thumb --enable-multiarch --with-build-sysroot=/home/tcwg-buildslave/workspace/tcwg-make-release/label/docker-trusty-amd64-tcwg-build/target/arm-linux-gnueabihf/_build/sysroots/arm-linux-gnueabihf --enable-lto --enable-linker-build-id --enable-long-long --enable-shared --with-sysroot=/home/tcwg-buildslave/workspace/tcwg-make-release/label/docker-trusty-amd64-tcwg-build/target/arm-linux-gnueabihf/_build/builds/destdir/x86_64-unknown-linux-gnu/arm-linux-gnueabihf/libc --enable-languages=c,c++,fortran,lto --enable-checking=release --disable-bootstrap --build=x86_64-unknown-linux-gnu --host=x86_64-unknown-linux-gnu --target=arm-linux-gnueabihf --prefix=/home/tcwg-buildslave/workspace/tcwg-make-release/label/docker-trusty-amd64-tcwg-build/target/arm-linux-gnueabihf/_build/builds/destdir/x86_64-unknown-linux-gnu
Thread model: posix
gcc version 6.2.1 20161016 (Linaro GCC 6.2-2016.11)
</code>```

But when I execute ./configure --host=arm-linux-gnueabihf,the system cannot detect the arm-linux-gnueabihf tools.

```<code>configure: WARNING: If you wanted to set the --build type, don't use --host.
If a cross compiler is detected then cross compile mode will be used.
checking for a BSD-compatible install... /usr/bin/install -c
checking whether build environment is sane... yes
checking for arm-linux-gnueabihf-strip... no
checking for strip... strip
checking for a thread-safe mkdir -p... /bin/mkdir -p
checking for gawk... no
checking for mawk... mawk
checking whether make sets $(MAKE)... yes
checking for arm-linux-gnueabihf-g++... no
checking for arm-linux-gnueabihf-c++... no
checking for arm-linux-gnueabihf-gpp... no
checking for arm-linux-gnueabihf-aCC... no
checking for arm-linux-gnueabihf-CC... no
checking for arm-linux-gnueabihf-cxx... no
checking for arm-linux-gnueabihf-cc++... no
checking for arm-linux-gnueabihf-cl.exe... no
checking for arm-linux-gnueabihf-FCC... no
checking for arm-linux-gnueabihf-KCC... no
checking for arm-linux-gnueabihf-RCC... no
checking for arm-linux-gnueabihf-xlC_r... no
checking for arm-linux-gnueabihf-xlC... no
checking for g++... g++
checking whether the C++ compiler works... yes
checking for C++ compiler default output file name... a.out
checking for suffix of executables...
checking whether we are cross compiling... no
checking for suffix of object files... o
checking whether we are using the GNU C++ compiler... yes
checking whether g++ accepts -g... yes
checking for style of include used by make... GNU
checking dependency style of g++... gcc3
checking for arm-linux-gnueabihf-gcc... no
checking for gcc... gcc
checking whether we are using the GNU C compiler... yes
checking whether gcc accepts -g... yes
checking for gcc option to accept ISO C89... none needed
checking dependency style of gcc... gcc3
checking for pthread_rwlock_init in -lpthread... yes
checking how to run the C preprocessor... gcc -E
checking for grep that handles long lines and -e... /bin/grep
checking for egrep... /bin/grep -E
checking for ANSI C header files... yes
checking for sys/types.h... yes
checking for sys/stat.h... yes
checking for stdlib.h... yes
checking for string.h... yes
checking for memory.h... yes
checking for strings.h... yes
checking for inttypes.h... yes
checking for stdint.h... yes
checking for unistd.h... yes
checking fcntl.h usability... yes
checking fcntl.h presence... yes
checking for fcntl.h... yes
checking for stdlib.h... (cached) yes
checking for string.h... (cached) yes
checking sys/ioctl.h usability... yes
checking sys/ioctl.h presence... yes
checking for sys/ioctl.h... yes
checking for unistd.h... (cached) yes
checking gtk/gtk.h usability... no
checking gtk/gtk.h presence... no
checking for gtk/gtk.h... no
checking pthread.h usability... yes
checking pthread.h presence... yes
checking for pthread.h... yes
checking for stdlib.h... (cached) yes
checking for GNU libc compatible malloc... yes
configure: creating ./config.status
config.status: creating Makefile
config.status: creating config.h
config.status: config.h is unchanged
config.status: executing depfiles commands
</code>```

WHich reason could cause this problem? How can I solve it?
Thanks

答: Well, arm-linux-gnueabihf-gcc seems to be not part of the list printed by the configure script, does it? But I see a check for arm-linux-gnueabihf-g++. Is that one installed too?

Title: Cross compiling problems

Body:
I have installed the cross compile tools in the ubuntu 16.04.And when I type arm-linux-gnueabihf-gcc -vin the command line.The command line shows that the cross compiler can work as follows:

Using built-in specs.
COLLECT_GCC=arm-linux-gnueabihf-gcc
COLLECT_LTO_WRAPPER=/home/nju/ti-processor-linux-sdk/linux-devkit/sysroots/x86_64-arago-linux/usr/bin/../libexec/gcc/arm-linux-gnueabihf/6.2.1/lto-wrapper
Target: arm-linux-gnueabihf
Configured with: /home/tcwg-buildslave/workspace/tcwg-make-release/label/docker-trusty-amd64-tcwg-build/target/arm-linux-gnueabihf/snapshots/gcc-linaro-6.2-2016.11/configure SHELL=/bin/bash --with-mpc=/home/tcwg-buildslave/workspace/tcwg-make-release/label/docker-trusty-amd64-tcwg-build/target/arm-linux-gnueabihf/_build/builds/destdir/x86_64-unknown-linux-gnu --with-mpfr=/home/tcwg-buildslave/workspace/tcwg-make-release/label/docker-trusty-amd64-tcwg-build/target/arm-linux-gnueabihf/_build/builds/destdir/x86_64-unknown-linux-gnu --with-gmp=/home/tcwg-buildslave/workspace/tcwg-make-release/label/docker-trusty-amd64-tcwg-build/target/arm-linux-gnueabihf/_build/builds/destdir/x86_64-unknown-linux-gnu --with-gnu-as --with-gnu-ld --disable-libstdcxx-pch --disable-libmudflap --with-cloog=no --with-ppl=no --with-isl=no --disable-nls --enable-c99 --enable-gnu-indirect-function --disable-multilib --with-tune=cortex-a9 --with-arch=armv7-a --with-fpu=vfpv3-d16 --with-float=hard --with-mode=thumb --enable-multiarch --with-build-sysroot=/home/tcwg-buildslave/workspace/tcwg-make-release/label/docker-trusty-amd64-tcwg-build/target/arm-linux-gnueabihf/_build/sysroots/arm-linux-gnueabihf --enable-lto --enable-linker-build-id --enable-long-long --enable-shared --with-sysroot=/home/tcwg-buildslave/workspace/tcwg-make-release/label/docker-trusty-amd64-tcwg-build/target/arm-linux-gnueabihf/_build/builds/destdir/x86_64-unknown-linux-gnu/arm-linux-gnueabihf/libc --enable-languages=c,c++,fortran,lto --enable-checking=release --disable-bootstrap --build=x86_64-unknown-linux-gnu --host=x86_64-unknown-linux-gnu --target=arm-linux-gnueabihf --prefix=/home/tcwg-buildslave/workspace/tcwg-make-release/label/docker-trusty-amd64-tcwg-build/target/arm-linux-gnueabihf/_build/builds/destdir/x86_64-unknown-linux-gnu
Thread model: posix
gcc version 6.2.1 20161016 (Linaro GCC 6.2-2016.11)

But when I execute ./configure --host=arm-linux-gnueabihf,the system cannot detect the arm-linux-gnueabihf tools.

configure: WARNING: If you wanted to set the --build type, don't use --host.
If a cross compiler is detected then cross compile mode will be used.
checking for a BSD-compatible install... /usr/bin/install -c
checking whether build environment is sane... yes
checking for arm-linux-gnueabihf-strip... no
checking for strip... strip
checking for a thread-safe mkdir -p... /bin/mkdir -p
checking for gawk... no
checking for mawk... mawk
checking whether make sets $(MAKE)... yes
checking for arm-linux-gnueabihf-g++... no
checking for arm-linux-gnueabihf-c++... no
checking for arm-linux-gnueabihf-gpp... no
checking for arm-linux-gnueabihf-aCC... no
checking for arm-linux-gnueabihf-CC... no
checking for arm-linux-gnueabihf-cxx... no
checking for arm-linux-gnueabihf-cc++... no
checking for arm-linux-gnueabihf-cl.exe... no
checking for arm-linux-gnueabihf-FCC... no
checking for arm-linux-gnueabihf-KCC... no
checking for arm-linux-gnueabihf-RCC... no
checking for arm-linux-gnueabihf-xlC_r... no
checking for arm-linux-gnueabihf-xlC... no
checking for g++... g++
checking whether the C++ compiler works... yes
checking for C++ compiler default output file name... a.out
checking for suffix of executables...
checking whether we are cross compiling... no
checking for suffix of object files... o
checking whether we are using the GNU C++ compiler... yes
checking whether g++ accepts -g... yes
checking for style of include used by make... GNU
checking dependency style of g++... gcc3
checking for arm-linux-gnueabihf-gcc... no
checking for gcc... gcc
checking whether we are using the GNU C compiler... yes
checking whether gcc accepts -g... yes
checking for gcc option to accept ISO C89... none needed
checking dependency style of gcc... gcc3
checking for pthread_rwlock_init in -lpthread... yes
checking how to run the C preprocessor... gcc -E
checking for grep that handles long lines and -e... /bin/grep
checking for egrep... /bin/grep -E
checking for ANSI C header files... yes
checking for sys/types.h... yes
checking for sys/stat.h... yes
checking for stdlib.h... yes
checking for string.h... yes
checking for memory.h... yes
checking for strings.h... yes
checking for inttypes.h... yes
checking for stdint.h... yes
checking for unistd.h... yes
checking fcntl.h usability... yes
checking fcntl.h presence... yes
checking for fcntl.h... yes
checking for stdlib.h... (cached) yes
checking for string.h... (cached) yes
checking sys/ioctl.h usability... yes
checking sys/ioctl.h presence... yes
checking for sys/ioctl.h... yes
checking for unistd.h... (cached) yes
checking gtk/gtk.h usability... no
checking gtk/gtk.h presence... no
checking for gtk/gtk.h... no
checking pthread.h usability... yes
checking pthread.h presence... yes
checking for pthread.h... yes
checking for stdlib.h... (cached) yes
checking for GNU libc compatible malloc... yes
configure: creating ./config.status
config.status: creating Makefile
config.status: creating config.h
config.status: config.h is unchanged
config.status: executing depfiles commands

WHich reason could cause this problem? How can I solve it?
Thanks


问:
Receiving the key value pair as input parameter
I am trying to receive the below key value pair as the input parameter to my Web API

```<code>json=%7B%0A%22MouseSampleBarcode%22%20%3A%20%22MOS81%22%0A%7D%0A
</code>```

where the right of the string is the URL encoded JSON which looks like

```<code>{
"MouseSampleBarcode" : "MOS81"
}
</code>```

How can I parse this and store them in to the Model class

```<code> [HttpPost]
 public async Task<IHttpActionResult> Get([FromBody] CoreBarCodeDTO.RootObject coreBarCode)
 {
  string Bar_Code = coreBarCode.MouseSampleBarcode.ToString();
</code>```

where the CoreBarCodeDTO looks like below

```<code>public class CoreBarCodeDTO
{
    public class RootObject
    {
        public string MouseSampleBarcode { get; set; }
    }
 }
</code>```

答:
You could do it this way. Change your class to this definition. In your controller coreBarCode.json will have the the json which you can then work with as needed:

```<code>public class CoreBarCodeDTO
{
    private string _json;
    public string json { get { return _json; }
        set {
            string decoded = HttpUtility.UrlDecode(value);
            _json = decoded;
        }
    }
}
</code>```

Update

```<code> [HttpPost]
 public async Task<IHttpActionResult> Get([FromBody] CoreBarCodeDTOcoreBarCode coreBarCode)
 {
    string Bar_Code = coreBarCode.json;
    //work with the JSON here, with Newtonsoft for example
    var obj = JObject.Parse(Bar_Code);
    // obj["MouseSampleBarcode"] now = "MOS81"

 }
</code>```

Body:
I am trying to receive the below key value pair as the input parameter to my Web API

json=%7B%0A%22MouseSampleBarcode%22%20%3A%20%22MOS81%22%0A%7D%0A

where the right of the string is the URL encoded JSON which looks like

{
"MouseSampleBarcode" : "MOS81"
}

How can I parse this and store them in to the Model class

 [HttpPost]
 public async Task<IHttpActionResult> Get([FromBody] CoreBarCodeDTO.RootObject coreBarCode)
 {
  string Bar_Code = coreBarCode.MouseSampleBarcode.ToString();

where the CoreBarCodeDTO looks like below

public class CoreBarCodeDTO
{
    public class RootObject
    {
        public string MouseSampleBarcode { get; set; }
    }
 }

Body:
You could do it this way. Change your class to this definition. In your controller coreBarCode.json will have the the json which you can then work with as needed:

public class CoreBarCodeDTO
{
    private string _json;
    public string json { get { return _json; }
        set {
            string decoded = HttpUtility.UrlDecode(value);
            _json = decoded;
        }
    }
}

Update

 [HttpPost]
 public async Task<IHttpActionResult> Get([FromBody] CoreBarCodeDTOcoreBarCode coreBarCode)
 {
    string Bar_Code = coreBarCode.json;
    //work with the JSON here, with Newtonsoft for example
    var obj = JObject.Parse(Bar_Code);
    // obj["MouseSampleBarcode"] now = "MOS81"

 }


问:
How to extract the month, day of month and IP address from the line using sed or awk?
I have extracted the day/month and IP that are continuously bruteforcing my IMAP server:

```<code>Nov1 unknown[186.216.99.239]:
Nov1 unknown[62.249.196.214]:
Nov1 unknown[110.145.123.120]:
Nov1 fixed-187-190-251-149.totalplay.net[187.190.251.149]:
Nov1 pd9568164.dip0.t-ipconnect.de[217.86.129.100]:
Nov1 unknown[103.227.88.130]:
</code>```

I want the output to be like below:

```<code>Nov1 186.216.99.239
Nov1 62.249.196.214
Nov1 110.145.123.120
Nov1 187.190.251.149
Nov1 217.86.129.100
Nov1 103.227.88.130
</code>```

I achieved this result using combination of sed, awk and cut with below code, but I would like to learn if there are better ways?

```<code>while read -r line
    do
        monthday=$(echo $line | awk '{ print $1 }')
        # ip=$(echo $line | awk -F'[\\\[\\\]]' { print $2 } )
        ip=$(echo $line| cut -d[ -f2| cut -d] -f1 )
        echo "${monthday} ${ip}"
    done < badIpList.txt
</code>```

答:
With awk: set the field separator to the any of space, [ or ], then print the first and third field:

```<code>$ awk -F "[][ ]" '{ print $1, $3 }' infile
Nov1 186.216.99.239
Nov1 62.249.196.214
Nov1 110.145.123.120
Nov1 187.190.251.149
Nov1 217.86.129.100
Nov1 103.227.88.130
</code>```

Notice that the field separator is a regular expression, namely the bracket expression [][ ]. From the gawk manual:

To include one of the characters \, ], -, or ^ in a bracket expression, put a \ in front of it.

So the expression would have to be

```<code>[\[\] ]
</code>```

but because regular expressions stored in strings ("dynamic/computed regexps") are scanned twice, we have to escape the backslash:

```<code>-F '[\\[\\] ]'
</code>```

or to use double quotes, as I did, I'd have to escape both the backslash and the backslash escaping it:

```<code>-F "[\\\[\\\] ]"
</code>```

which clearly isn't all too readable. Thankfully, there is a loophole:

Additionally, if you place ] right after the opening [, the closing bracket is treated as one of the characters to be matched.

so we get away with

```<code>-F "[][ ]"
</code>```

even within double quotes. There is no real reason to use double quotes here, by the way.

Body:
I have extracted the day/month and IP that are continuously bruteforcing my IMAP server:

Nov1 unknown[186.216.99.239]:
Nov1 unknown[62.249.196.214]:
Nov1 unknown[110.145.123.120]:
Nov1 fixed-187-190-251-149.totalplay.net[187.190.251.149]:
Nov1 pd9568164.dip0.t-ipconnect.de[217.86.129.100]:
Nov1 unknown[103.227.88.130]:

I want the output to be like below:

Nov1 186.216.99.239
Nov1 62.249.196.214
Nov1 110.145.123.120
Nov1 187.190.251.149
Nov1 217.86.129.100
Nov1 103.227.88.130

I achieved this result using combination of sed, awk and cut with below code, but I would like to learn if there are better ways?

while read -r line
    do
        monthday=$(echo $line | awk '{ print $1 }')
        # ip=$(echo $line | awk -F'[\\\[\\\]]' { print $2 } )
        ip=$(echo $line| cut -d[ -f2| cut -d] -f1 )
        echo "${monthday} ${ip}"
    done < badIpList.txt

Body:
With awk: set the field separator to the any of space, [ or ], then print the first and third field:

$ awk -F "[][ ]" '{ print $1, $3 }' infile
Nov1 186.216.99.239
Nov1 62.249.196.214
Nov1 110.145.123.120
Nov1 187.190.251.149
Nov1 217.86.129.100
Nov1 103.227.88.130

Notice that the field separator is a regular expression, namely the bracket expression [][ ]. From the gawk manual:

To include one of the characters \, ], -, or ^ in a bracket expression, put a \ in front of it.

So the expression would have to be

[\[\] ]

but because regular expressions stored in strings ("dynamic/computed regexps") are scanned twice, we have to escape the backslash:

-F '[\\[\\] ]'

or to use double quotes, as I did, I'd have to escape both the backslash and the backslash escaping it:

-F "[\\\[\\\] ]"

which clearly isn't all too readable. Thankfully, there is a loophole:

Additionally, if you place ] right after the opening [, the closing bracket is treated as one of the characters to be matched.

so we get away with

-F "[][ ]"

even within double quotes. There is no real reason to use double quotes here, by the way.


问:
Stop Script Outputting as plain text so that it runs as a Script in a set Div parent Class
I'm trying to output a script via a CMS (Webflow) but the system is outputting it as plain text, which stops it from correctly embedding & running.

So for example rather than getting:-

```<code><div clss="embed"><script type="text/javascript">whatever</script></div>
</code>```

The output comes out as the same in the inspector, but just plain text (not running script):-

```<code><div clss="embed">"<script type="text/javascript">whatever</script>"</div>
</code>```

So my question is whether there is a way to target a specific container div with class '.embed' (in Javascript or jQuery) to always ensure that any code in that class is always correctly outputted as a functioning script, rather than just printed on the screen as text?

Thanks

Glennyboy

Example Script

```<code><script type="text/javascript">
var uri = 'https://impgb.tradedoubler.com/imp?type(js)g(228862)a(28418)' + new String (Math.random()).substring (2, 11);
document.write('<sc'+'ript type="text/javascript" src="'+uri+'" charset=""></sc'+'ript>');
</script>
</code>```

Outputs on the page the same except in speech marks in the code " "

答:
What you are trying to do, and the way you want to do it, is NOT possible. You cannot have a div or container to ALWAYS have FUNCTIONING javascript. The key here is FUNCTIONING. Based on what you are describing, the script you are trying to execute is probably escaped, and so it is not valid javascript.

To really achieve what you are trying to do (which, I assume, is to execute your script dynamically), you need to look at where you are getting that script from. It seems like the source you are using is escaping the javsacript. You will need to un-escape it, and then put it in a script tag dynamically.

Perhaps you could show a little more of your code, so we can see where you are getting the script from. We can probably make a suggestion as to how to properly un-escape it.

Body:
I'm trying to output a script via a CMS (Webflow) but the system is outputting it as plain text, which stops it from correctly embedding & running.

So for example rather than getting:-

The output comes out as the same in the inspector, but just plain text (not running script):-

""

So my question is whether there is a way to target a specific container div with class '.embed' (in Javascript or jQuery) to always ensure that any code in that class is always correctly outputted as a functioning script, rather than just printed on the screen as text?

Thanks

Glennyboy

Example Script

Outputs on the page the same except in speech marks in the code " "


问:
Averaging of two images with mask
I have two image like this:

I create two mask, which show me position of each image on scene.

I create mask which show me intersection of two images.

I create intersection mask with
cv::bitwise_and(mask_left, mask_right, mask_intersection);

I want adding two images together. Where pixels of mask_intersection is white, I want use average value of pixels on both images. Here is result, where I just add one image on another. The problem is sharp border, which I want to solve with averaging of both images only on mask_intersection.

I don't know how to solve this problem the easiest way.

答:
For averaging the two images  where the mask intersect, you could use copyTo.

Supposing you have maskIntersection, image1, image2 and finalImage, the code would look something like:

```<code>((image1 + image2) * 0.5).copyTo(finalImage, maskIntersection)
</code>```

Even though this answers your question of averaging the two images, I don't think it will provide very good results. Blending two images together is usually a more involved process. Take a look at this class to have a quick overview of what is required.

Title: Averaging of two images with mask

Body:
For averaging the two images  where the mask intersect, you could use copyTo.

Supposing you have maskIntersection, image1, image2 and finalImage, the code would look something like:

((image1 + image2) * 0.5).copyTo(finalImage, maskIntersection)

Even though this answers your question of averaging the two images, I don't think it will provide very good results. Blending two images together is usually a more involved process. Take a look at this class to have a quick overview of what is required.


问:
Powershell output - Row to column conversion
I found the following PowerShell VMware script that exports several pieces of information from the environment.

```<code>&{foreach($vm in (Get-VM)) {
$vm.ExtensionData.Guest.Net | select -Property @{N='VM';E={$vm.Name}},
@{N='Host';E={$vm.VMHost.Name}},
@{N='OS';E={$vm.Guest.OSFullName}},
@{N='Tools';E={$vm.ExtensionData.Guest.ToolsRunningStatus}},
@{N='NicType';E={[string]::Join(',',(Get-NetworkAdapter -Vm $vm | Select-Object -ExpandProperty Type))}},
@{N='VLAN';E={[string]::Join(',',(Get-NetworkAdapter -Vm $vm | Select-Object -ExpandProperty NetworkName))}},
@{N='IP';E={[string]::Join(',',($vm.Guest.IPAddress | Where {($_.Split(".")).length -eq 4}))}},
@{N='Gateway';E={[string]::Join(',',($vm.ExtensionData.Guest.IpStack.IpRouteConfig.IpRoute | %{if($_.Gateway.IpAddress){$_.Gateway.IpAddress}}))}},
@{N='Subnet Mask';E={
            $dec = [Convert]::ToUInt32($(('1' * $_.IpConfig.IpAddress[0].PrefixLength).PadRight(32, '0')), 2)
            $DottedIP = $( For ($i = 3; $i -gt -1; $i--) {
                    $Remainder = $dec % [Math]::Pow(256, $i)
                    (                        $dec - $Remainder) / [Math]::Pow(256, $i)
                    $dec = $Remainder
                } )
            [String]::Join('.', $DottedIP)
        }},
@{N="DNS";E={[string]::Join(',',($vm.ExtensionData.Guest.IpStack.DnsConfig.IpAddress))}},
@{N='MAC';E={[string]::Join(',',$_.MacAddress)}}}}
</code>```

The output of it, is in a following style: (several hundred of those "blocks", one per VM, showing two of them)

```<code>VM          : VMname1
Host        : ESXi1.domain.com
OS          : Red Hat Enterprise Linux 6 (64-bit)
Tools       : guestToolsRunning
NicType     : Vmxnet3
VLAN        : 123-DMZ-VMnet
IP          : 10.10.10.40
Gateway     : 10.10.10.1
Subnet Mask : 255.255.255.0
DNS         : 10.10.10.11,10.10.10.13
MAC         : 01:50:56:9a:98:62

VM          : VMname2
Host        : ESXi2.domain.com
OS          : Microsoft Windows Server 2012 (64-bit)
Tools       : guestToolsRunning
NicType     : Vmxnet3
VLAN        : 20-VMnet
IP          : 10.55.10.14
Gateway     : 10.55.10.1
Subnet Mask : 255.255.255.0
DNS         : 10.10.10.11,10.10.10.13,10.20.10.11,10.10.231.13
MAC         : 12:50:32:22:68:9c
</code>```

I have tried to find a correct approach to convert the output to the CSV format:
VM,HOST,OS,Tools,NicType,VLAN,IP,Gateway, Subnet Mask, DNS, MAC
VMname1,ESXi1.domain.com, etc
VMname1,ESXi2.domain.com, etc

With the "conversion script", also found on the internet, which I tried to adjust to meet my needs, I tried to convert the information however it doesn't seems to work.

```<code>$list = Get-Content C:\temp\IPs\results.txt
$i = 0
Do
{
$VM1 = $list[$i].value
$Host1 =$list[$i+1].value
$OS1 =$list[$i+2].value
$Tools1 =$list[$i+3].value
$NicType1 =$list[$i+4].value
$VLAN1 =$list[$i+5].value
$IP1 =$list[$i+6].value
$Gateway1 =$list[$i+7].value
$SubnetMask1 =$list[$i+8].value
$DNS1 =$list[$i+9].value
$MAC1 =$list[$i+10].value
[array]$converter += $VM1 + "," + $Host1 + "," + $OS1 + "," + $Tools1 + ","
+ $NicType1 + "," + $VLAN1 + "," + $IP1 + "," + $Gateway1 + "," +
$SubnetMask1 + "," + $DNS1 + "," + $MAC1
$i = $i + 11
} while ($i -le $list.count)
$converter = $converter|convertfrom-csv -header VM1, Host1, OS1, Tools1,
NicType1, VLAN1, IP1, Gateway1, SubnetMask1, DNS1, MAC1
$converter|export-csv C:\temp\IPs\results.csv -notypeinformation
</code>```

Please note, for some entries such as DNS or IP address, there might be multiple values.

How would I go and convert the rows to columns to capture all the available info?

Thank you.

答:
The final working code:</p>

```<code>&{foreach($vm in (get-VM)) {
$vm.ExtensionData.Guest.Net | select -Property @{N='VM';E={$vm.Name}},
@{N='Host';E={$vm.VMHost.Name}},
@{N='OS';E={$vm.Guest.OSFullName}},
@{N='Tools';E={$vm.ExtensionData.Guest.ToolsRunningStatus}},
@{N='NicType';E={[string]::Join(',',(Get-NetworkAdapter -Vm $vm | Select-Object -ExpandProperty Type))}},
@{N='VLAN';E={[string]::Join(',',(Get-NetworkAdapter -Vm $vm | Select-Object -ExpandProperty NetworkName))}},
@{N='IP';E={[string]::Join(',',($vm.Guest.IPAddress | Where {($_.Split(".")).length -eq 4}))}},
@{N='Gateway';E={[string]::Join(',',($vm.ExtensionData.Guest.IpStack.IpRouteConfig.IpRoute | %{if($_.Gateway.IpAddress){$_.Gateway.IpAddress}}))}},
@{N='Subnet Mask';E={
            $dec = [Convert]::ToUInt32($(('1' * $_.IpConfig.IpAddress[0].PrefixLength).PadRight(32, '0')), 2)
            $DottedIP = $( For ($i = 3; $i -gt -1; $i--) {
                    $Remainder = $dec % [Math]::Pow(256, $i)
                    (                        $dec - $Remainder) / [Math]::Pow(256, $i)
                    $dec = $Remainder
                } )
            [String]::Join('.', $DottedIP)
        }},
@{N="DNS";E={[string]::Join(',',($vm.ExtensionData.Guest.IpStack.DnsConfig.IpAddress))}},
@{N='MAC';E={[string]::Join(',',$_.MacAddress)}}
  }
} | ft -AutoSize | Out-String -Width 4096 | Out-File C:\temp\VM-GetSomeInfo.txt
</code>```

Body:
I found the following PowerShell VMware script that exports several pieces of information from the environment.

&{foreach($vm in (Get-VM)) {
$vm.ExtensionData.Guest.Net | select -Property @{N='VM';E={$vm.Name}},
@{N='Host';E={$vm.VMHost.Name}},
@{N='OS';E={$vm.Guest.OSFullName}},
@{N='Tools';E={$vm.ExtensionData.Guest.ToolsRunningStatus}},
@{N='NicType';E={[string]::Join(',',(Get-NetworkAdapter -Vm $vm | Select-Object -ExpandProperty Type))}},
@{N='VLAN';E={[string]::Join(',',(Get-NetworkAdapter -Vm $vm | Select-Object -ExpandProperty NetworkName))}},
@{N='IP';E={[string]::Join(',',($vm.Guest.IPAddress | Where {($_.Split(".")).length -eq 4}))}},
@{N='Gateway';E={[string]::Join(',',($vm.ExtensionData.Guest.IpStack.IpRouteConfig.IpRoute | %{if($_.Gateway.IpAddress){$_.Gateway.IpAddress}}))}},
@{N='Subnet Mask';E={
            $dec = [Convert]::ToUInt32($(('1' * $_.IpConfig.IpAddress[0].PrefixLength).PadRight(32, '0')), 2)
            $DottedIP = $( For ($i = 3; $i -gt -1; $i--) {
                    $Remainder = $dec % [Math]::Pow(256, $i)
                    (                        $dec - $Remainder) / [Math]::Pow(256, $i)
                    $dec = $Remainder
                } )
            [String]::Join('.', $DottedIP)
        }},
@{N="DNS";E={[string]::Join(',',($vm.ExtensionData.Guest.IpStack.DnsConfig.IpAddress))}},
@{N='MAC';E={[string]::Join(',',$_.MacAddress)}}}}

The output of it, is in a following style: (several hundred of those "blocks", one per VM, showing two of them)

VM          : VMname1
Host        : ESXi1.domain.com
OS          : Red Hat Enterprise Linux 6 (64-bit)
Tools       : guestToolsRunning
NicType     : Vmxnet3
VLAN        : 123-DMZ-VMnet
IP          : 10.10.10.40
Gateway     : 10.10.10.1
Subnet Mask : 255.255.255.0
DNS         : 10.10.10.11,10.10.10.13
MAC         : 01:50:56:9a:98:62

VM          : VMname2
Host        : ESXi2.domain.com
OS          : Microsoft Windows Server 2012 (64-bit)
Tools       : guestToolsRunning
NicType     : Vmxnet3
VLAN        : 20-VMnet
IP          : 10.55.10.14
Gateway     : 10.55.10.1
Subnet Mask : 255.255.255.0
DNS         : 10.10.10.11,10.10.10.13,10.20.10.11,10.10.231.13
MAC         : 12:50:32:22:68:9c

I have tried to find a correct approach to convert the output to the CSV format:
VM,HOST,OS,Tools,NicType,VLAN,IP,Gateway, Subnet Mask, DNS, MAC
VMname1,ESXi1.domain.com, etc
VMname1,ESXi2.domain.com, etc

With the "conversion script", also found on the internet, which I tried to adjust to meet my needs, I tried to convert the information however it doesn't seems to work.

$list = Get-Content C:\temp\IPs\results.txt
$i = 0
Do
{
$VM1 = $list[$i].value
$Host1 =$list[$i+1].value
$OS1 =$list[$i+2].value
$Tools1 =$list[$i+3].value
$NicType1 =$list[$i+4].value
$VLAN1 =$list[$i+5].value
$IP1 =$list[$i+6].value
$Gateway1 =$list[$i+7].value
$SubnetMask1 =$list[$i+8].value
$DNS1 =$list[$i+9].value
$MAC1 =$list[$i+10].value
[array]$converter += $VM1 + "," + $Host1 + "," + $OS1 + "," + $Tools1 + ","
+ $NicType1 + "," + $VLAN1 + "," + $IP1 + "," + $Gateway1 + "," +
$SubnetMask1 + "," + $DNS1 + "," + $MAC1
$i = $i + 11
} while ($i -le $list.count)
$converter = $converter|convertfrom-csv -header VM1, Host1, OS1, Tools1,
NicType1, VLAN1, IP1, Gateway1, SubnetMask1, DNS1, MAC1
$converter|export-csv C:\temp\IPs\results.csv -notypeinformation

Please note, for some entries such as DNS or IP address, there might be multiple values.

How would I go and convert the rows to columns to capture all the available info?

Thank you.

Body:
The final working code:

&{foreach($vm in (get-VM)) {
$vm.ExtensionData.Guest.Net | select -Property @{N='VM';E={$vm.Name}},
@{N='Host';E={$vm.VMHost.Name}},
@{N='OS';E={$vm.Guest.OSFullName}},
@{N='Tools';E={$vm.ExtensionData.Guest.ToolsRunningStatus}},
@{N='NicType';E={[string]::Join(',',(Get-NetworkAdapter -Vm $vm | Select-Object -ExpandProperty Type))}},
@{N='VLAN';E={[string]::Join(',',(Get-NetworkAdapter -Vm $vm | Select-Object -ExpandProperty NetworkName))}},
@{N='IP';E={[string]::Join(',',($vm.Guest.IPAddress | Where {($_.Split(".")).length -eq 4}))}},
@{N='Gateway';E={[string]::Join(',',($vm.ExtensionData.Guest.IpStack.IpRouteConfig.IpRoute | %{if($_.Gateway.IpAddress){$_.Gateway.IpAddress}}))}},
@{N='Subnet Mask';E={
            $dec = [Convert]::ToUInt32($(('1' * $_.IpConfig.IpAddress[0].PrefixLength).PadRight(32, '0')), 2)
            $DottedIP = $( For ($i = 3; $i -gt -1; $i--) {
                    $Remainder = $dec % [Math]::Pow(256, $i)
                    (                        $dec - $Remainder) / [Math]::Pow(256, $i)
                    $dec = $Remainder
                } )
            [String]::Join('.', $DottedIP)
        }},
@{N="DNS";E={[string]::Join(',',($vm.ExtensionData.Guest.IpStack.DnsConfig.IpAddress))}},
@{N='MAC';E={[string]::Join(',',$_.MacAddress)}}
  }
} | ft -AutoSize | Out-String -Width 4096 | Out-File C:\temp\VM-GetSomeInfo.txt


问:
cakephp3 load plugin for special prefix
I have Cakephp 3 application and i want to load this plugin and the event listener below it just for admin prefix. ( not the entire project ) .

how can i achive this?

this is my

config/bootstrap.php

where i load this plugin . (I load these at end of the file )

```<code>...

Plugin::load('Josegonzalez/Upload');

\Cake\Event\EventManager::instance()->on(new \App\Controller\Event\AppEventListener());
</code>```

i want these to line only run on admin prefix

答:
You can't conditionally run code based upon routing inside boostrap.php as the routing configuration for you app hasn't been loaded yet.

You'll have to do it old school style and use $_SERVER['REQUEST_URI'].

```<code>$url = $_SERVER['REQUEST_URI'];
$admin = '/admin/';
if(substr($url, 0, strlen($admin)) === $admin) {
    Plugin::load('Josegonzalez/Upload');
    \Cake\Event\EventManager::instance()->on(new \App\Controller\Event\AppEventListener());
}
</code>```

Updated

Your plugin should have it's own bootstrap file. Which contains

Upload/config/bootstrap.php:

```<code>\Cake\Event\EventManager::instance()->on(new \App\Controller\Event\AppEventListener());
</code>```

The app's bootstrap then tells CakePHP to include the bootstrap when loading the plugin.

App/config/bootstrap.php:

```<code>    Plugin::load('Josegonzalez/Upload', ['bootstrap' => true]);
</code>```

You shouldn't conditionally load your plugin.

I think you are searching for authentication on requests to your plugin. You want to limit use of your plugin only to authorized administrators. That is not a plugin issue. It is an authentication issue and you should be using the Authentication component in your plugin to verify the request is valid, and that the current user is an administrator.

Title: cakephp3 load plugin for special prefix

Body:
I have Cakephp 3 application and i want to load this plugin and the event listener below it just for admin prefix. ( not the entire project ) .

how can i achive this?

this is my

config/bootstrap.php

where i load this plugin . (I load these at end of the file )

...

Plugin::load('Josegonzalez/Upload');

\Cake\Event\EventManager::instance()->on(new \App\Controller\Event\AppEventListener());

i want these to line only run on admin prefix

Body:
You can't conditionally run code based upon routing inside boostrap.php as the routing configuration for you app hasn't been loaded yet.

You'll have to do it old school style and use $_SERVER['REQUEST_URI'].

$url = $_SERVER['REQUEST_URI'];
$admin = '/admin/';
if(substr($url, 0, strlen($admin)) === $admin) {
    Plugin::load('Josegonzalez/Upload');
    \Cake\Event\EventManager::instance()->on(new \App\Controller\Event\AppEventListener());
}

Updated

Your plugin should have it's own bootstrap file. Which contains

Upload/config/bootstrap.php:

\Cake\Event\EventManager::instance()->on(new \App\Controller\Event\AppEventListener());

The app's bootstrap then tells CakePHP to include the bootstrap when loading the plugin.

App/config/bootstrap.php:

    Plugin::load('Josegonzalez/Upload', ['bootstrap' => true]);

You shouldn't conditionally load your plugin.

I think you are searching for authentication on requests to your plugin. You want to limit use of your plugin only to authorized administrators. That is not a plugin issue. It is an authentication issue and you should be using the Authentication component in your plugin to verify the request is valid, and that the current user is an administrator.


问:
SharePoint jquery javascript does not run but works from console
I have the following code which works from console but does not work on page load.
The page does not have any error.</p>

```<code><div class="nav-report-category">
</div>

<script src="https://code.jquery.com/jquery-3.0.0.js"></script>
<script type="text/javascript">
$(document).ready(function(){
    $(".ms-listviewtable tr[class='ms-gb']").each(function(){
        alert('test 3');
    });
    var $mydiv = document.getElementsByClassName("nav-report-category")[0];
    var $liTag = document.createElement('li');
    var $aTag = document.createElement('a');

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

答:
```

Not sure what you are trying to do but if you wanted it in the DOM you have to also append it.If this is the thing that "was not working".

Body:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="nav-report-category">
</div>

<script src="https://code.jquery.com/jquery-3.0.0.js"></script>
<script type="text/javascript">
$(document).ready(function(){
    $(".ms-listviewtable tr[class='ms-gb']").each(function(){
        alert('test 3');
    });
    var $mydiv = document.getElementsByClassName("nav-report-category")[0];
    var $liTag = document.createElement('li');
    $mydiv.append($liTag);
    var $aTag = document.createElement('a');
    $mydiv.append($aTag);

});
</script>

Not sure what you are trying to do but if you wanted it in the DOM you have to also append it.If this is the thing that "was not working".


Title: How to extract the month, day of month and IP address from the line using sed or awk?

Body:
awk solution:

awk -F'[[:space:]\\[\\]]' '{print $1,$3}' file

-F'[[:space:]\\[\\]]' - complex field separator, either whitespace [:space:] or [ or ]. Thereby, the line, for ex. Nov1 unknown[186.216.99.239]: will be divided into fields: 1) Nov1, 2) unknown, 3) 186.216.99.239 and 4) :

The output:

Nov1 186.216.99.239
Nov1 62.249.196.214
Nov1 110.145.123.120
Nov1 187.190.251.149
Nov1 217.86.129.100
Nov1 103.227.88.130


问:
Linq to SQL query not returning expected results
Can anyone explain to me why these two are different functionally?

The first returns null on my sample data, and the second returns the expected result. I put the + @"" part in to avoid calling replace on a null string.

Code always returns null on my sample data:

```<code>to_follows_contact = db.CONTACTs.Where(n =>
    n.ACCOUNTID == account.ACCOUNTID
    && (
        (n.FIRSTNAME + n.MIDDLENAME + n.LASTNAME + @"").Replace(@" ", @"")
                                                            == @"TOFOLLOW"
        ||
        (n.FIRSTNAME + n.MIDDLENAME + n.LASTNAME + @"").Replace(@" ", @"")
                                                            == @"FOLLOWTO"
    )
).FirstOrDefault();
</code>```

Code returns correct contact on my sample data:

```<code>foreach (CONTACT n in db.CONTACTs.Where(n => n.ACCOUNTID == account.ACCOUNTID))
{
    string ContactName = (n.FIRSTNAME + n.MIDDLENAME + n.LASTNAME + @"")
                         .Replace(@" ", @"");
    if (ContactName == @"TOFOLLOW" || ContactName == @"FOLLOWTO")
        to_follows_contact = n;
}
</code>```

答:
What's happening, is that the first code sample actually solves the problem entirely in T-SQL. Unfortunately, the translation from C# to SQL isn't entirely transparent.

SQL handles null values differently* from .NET. SELECT 'Foo' + NULL + 'Bar' will return NULL. You will need to use COALESCE or something like it. In LINQ to SQL, that translates to:

```<code>(n.FIRSTNAME ?? "" + n.MIDDLENAME ?? "" + n.LASTNAME ?? "").Replace(" ", "")
</code>```

If you use that, it should work fine.

If you're interested, you can use db.GetCommand(IQueryable<T>) to get the generated SQL statement. It's also available when you hover over the IQueryable variable in a piece of source code while debugging.

*: this acually depends on some database options that you can set, but this is the default behavior.

Body:
Can anyone explain to me why these two are different functionally?

The first returns null on my sample data, and the second returns the expected result. I put the + @"" part in to avoid calling replace on a null string.

Code always returns null on my sample data:

to_follows_contact = db.CONTACTs.Where(n =>
    n.ACCOUNTID == account.ACCOUNTID
    && (
        (n.FIRSTNAME + n.MIDDLENAME + n.LASTNAME + @"").Replace(@" ", @"")
                                                            == @"TOFOLLOW"
        ||
        (n.FIRSTNAME + n.MIDDLENAME + n.LASTNAME + @"").Replace(@" ", @"")
                                                            == @"FOLLOWTO"
    )
).FirstOrDefault();

Code returns correct contact on my sample data:

foreach (CONTACT n in db.CONTACTs.Where(n => n.ACCOUNTID == account.ACCOUNTID))
{
    string ContactName = (n.FIRSTNAME + n.MIDDLENAME + n.LASTNAME + @"")
                         .Replace(@" ", @"");
    if (ContactName == @"TOFOLLOW" || ContactName == @"FOLLOWTO")
        to_follows_contact = n;
}

Body:
What's happening, is that the first code sample actually solves the problem entirely in T-SQL. Unfortunately, the translation from C# to SQL isn't entirely transparent.

SQL handles null values differently* from .NET. SELECT 'Foo' + NULL + 'Bar' will return NULL. You will need to use COALESCE or something like it. In LINQ to SQL, that translates to:

(n.FIRSTNAME ?? "" + n.MIDDLENAME ?? "" + n.LASTNAME ?? "").Replace(" ", "")

If you use that, it should work fine.

If you're interested, you can use db.GetCommand(IQueryable<T>) to get the generated SQL statement. It's also available when you hover over the IQueryable variable in a piece of source code while debugging.

*: this acually depends on some database options that you can set, but this is the default behavior.


问:
Enable FIPS on PostgreSQL database
Can someone please specify the steps to enable FIPS on Postgres Database? I have googled but was not able to find anything concrete.</p>

答:
For PostgreSQL on Red Hat Linux, the https://public.cyber.mil/stigs/downloads/ web site has a Security Technical Implementation Guide for PostgreSQL 9.x which has this check.

```<code>Rule Title: PostgreSQL must implement NIST FIPS 140-2 validated
cryptographic modules to protect unclassified information requiring
confidentiality and cryptographic protection, in accordance with the data
owners requirements.
STIG ID:    PGS9-00-008200
Rule ID:    SV-87645r1_rule
Vuln ID:    V-72993
</code>```

The "Fix Text" reads

```<code>Configure OpenSSL to be FIPS compliant.

PostgreSQL uses OpenSSL for cryptographic modules. To configure OpenSSL to
be FIPS 140-2 compliant, see the official RHEL Documentation:
</code>```

https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/6/html/Security_Guide/sect-Security_Guide-Federal_Standards_And_Regulations-Federal_Information_Processing_Standard.html

```<code>For more information on configuring PostgreSQL to use SSL, see supplementary
content APPENDIX-G.
</code>```

Joseph Conway pointed out "the Appendix G the STIG refers to is in the PostgreSQL STIG supplement, not the [postgresql.org] docs. You can get the supplement (and the rest of the STIG) here: https://dl.dod.cyber.mil/wp-content/uploads/stigs/zip/U_PGS_SQL_9-x_V2R1_STIG.zip

Title: Enable FIPS on PostgreSQL database

Body:
For PostgreSQL on Red Hat Linux, the https://public.cyber.mil/stigs/downloads/ web site has a Security Technical Implementation Guide for PostgreSQL 9.x which has this check.

Rule Title: PostgreSQL must implement NIST FIPS 140-2 validated
cryptographic modules to protect unclassified information requiring
confidentiality and cryptographic protection, in accordance with the data
owners requirements.
STIG ID:    PGS9-00-008200
Rule ID:    SV-87645r1_rule
Vuln ID:    V-72993

The "Fix Text" reads

Configure OpenSSL to be FIPS compliant.

PostgreSQL uses OpenSSL for cryptographic modules. To configure OpenSSL to
be FIPS 140-2 compliant, see the official RHEL Documentation:

https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/6/html/Security_Guide/sect-Security_Guide-Federal_Standards_And_Regulations-Federal_Information_Processing_Standard.html

For more information on configuring PostgreSQL to use SSL, see supplementary
content APPENDIX-G.

Joseph Conway pointed out "the Appendix G the STIG refers to is in the PostgreSQL STIG supplement, not the [postgresql.org] docs. You can get the supplement (and the rest of the STIG) here: https://dl.dod.cyber.mil/wp-content/uploads/stigs/zip/U_PGS_SQL_9-x_V2R1_STIG.zip

ContentLicense: CC BY-SA 4.0


问:
Wait For Asynchronous Operation To Complete in Swift
I am not sure how to handle this situation as I am very new to iOS development and Swift. I am performing data fetching like so:

```<code>func application(application: UIApplication!, performFetchWithCompletionHandler completionHandler: ((UIBackgroundFetchResult) -> Void)!)
{
    loadShows()
    completionHandler(UIBackgroundFetchResult.NewData)
    println("Background Fetch Complete")
}
</code>```

My loadShows() function parses a bunch of data it gets from a website loaded into a UIWebView. The problem is that I have a timer that waits for 10 seconds or so in the loadShows function. This allows for the javascript in the page to fully load before I start parsing the data. My problem is that the completion handler completes before my loadShows() does.

What I would like to do is add a bool for "isCompletedParsingShows" and make the completionHandler line wait to complete until that bool is true. What is the best way to handle this?

答:
Details

xCode 9.2, Swift 4

Solution

```<code>class AsyncOperation {

    private let semaphore: DispatchSemaphore
    private let dispatchQueue: DispatchQueue
    typealias CompleteClosure = ()->()

    init(numberOfSimultaneousActions: Int, dispatchQueueLabel: String) {
        semaphore = DispatchSemaphore(value: numberOfSimultaneousActions)
        dispatchQueue = DispatchQueue(label: dispatchQueueLabel)
    }

    func run(closure: @escaping (@escaping CompleteClosure)->()) {
        dispatchQueue.async {
            self.semaphore.wait()
            closure {
                self.semaphore.signal()
            }
        }
    }
}
</code>```

Usage

```<code>let asyncOperation = AsyncOperation(numberOfSimultaneousActions: 1, dispatchQueueLabel: "AnyString")
asyncOperation.run { completeClosure in
    // sync/async action
    // ...

    // action complete
    completeClosure()
}
</code>```

Full sample

```<code>import UIKit

class ViewController: UIViewController {

    let asyncOperation = AsyncOperation(numberOfSimultaneousActions: 1, dispatchQueueLabel: "AnyString")
    var counter = 1

    override func viewDidLoad() {
        super.viewDidLoad()

        let button = UIButton(frame: CGRect(x: 50, y: 50, width: 100, height: 40))
        button.setTitle("Button", for: .normal)
        button.setTitleColor(.blue, for: .normal)
        button.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)
        view.addSubview(button)

    }

    @objc func buttonTapped() {
        print("Button tapped at: \(Date())")
        asyncOperation.run { completeClosure in
            let counter = self.counter
            print("     - Action \(counter) strat at \(Date())")
            self.counter += 1

            DispatchQueue.global(qos: .background).async {
                sleep(1)
                print("     - Action \(counter) end at \(Date())")
                completeClosure()
            }
        }
    }

}
</code>```

Results

Body:
I am not sure how to handle this situation as I am very new to iOS development and Swift. I am performing data fetching like so:

func application(application: UIApplication!, performFetchWithCompletionHandler completionHandler: ((UIBackgroundFetchResult) -> Void)!)
{
    loadShows()
    completionHandler(UIBackgroundFetchResult.NewData)
    println("Background Fetch Complete")
}

My loadShows() function parses a bunch of data it gets from a website loaded into a UIWebView. The problem is that I have a timer that waits for 10 seconds or so in the loadShows function. This allows for the javascript in the page to fully load before I start parsing the data. My problem is that the completion handler completes before my loadShows() does.

What I would like to do is add a bool for "isCompletedParsingShows" and make the completionHandler line wait to complete until that bool is true. What is the best way to handle this?

Body:
Details

xCode 9.2, Swift 4

Solution

class AsyncOperation {

    private let semaphore: DispatchSemaphore
    private let dispatchQueue: DispatchQueue
    typealias CompleteClosure = ()->()

    init(numberOfSimultaneousActions: Int, dispatchQueueLabel: String) {
        semaphore = DispatchSemaphore(value: numberOfSimultaneousActions)
        dispatchQueue = DispatchQueue(label: dispatchQueueLabel)
    }

    func run(closure: @escaping (@escaping CompleteClosure)->()) {
        dispatchQueue.async {
            self.semaphore.wait()
            closure {
                self.semaphore.signal()
            }
        }
    }
}

Usage

let asyncOperation = AsyncOperation(numberOfSimultaneousActions: 1, dispatchQueueLabel: "AnyString")
asyncOperation.run { completeClosure in
    // sync/async action
    // ...

    // action complete
    completeClosure()
}

Full sample

import UIKit

class ViewController: UIViewController {

    let asyncOperation = AsyncOperation(numberOfSimultaneousActions: 1, dispatchQueueLabel: "AnyString")
    var counter = 1

    override func viewDidLoad() {
        super.viewDidLoad()

        let button = UIButton(frame: CGRect(x: 50, y: 50, width: 100, height: 40))
        button.setTitle("Button", for: .normal)
        button.setTitleColor(.blue, for: .normal)
        button.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)
        view.addSubview(button)

    }

    @objc func buttonTapped() {
        print("Button tapped at: \(Date())")
        asyncOperation.run { completeClosure in
            let counter = self.counter
            print("     - Action \(counter) strat at \(Date())")
            self.counter += 1

            DispatchQueue.global(qos: .background).async {
                sleep(1)
                print("     - Action \(counter) end at \(Date())")
                completeClosure()
            }
        }
    }

}

Results


问:
Plot table alongside sns.barplot
```<code>#read data into dataframe
con=pd.read_csv('testOutput.csv')

'''
testOutput.csv looks like :
Sample,Count
sample1,99.9
sample2, 96.6
'''

## set colours to increase with values
sns.set(style="darkgrid")
groupedvalues=con.groupby("Count").sum().reset_index()
pal = sns.color_palette("Greens_d", len(groupedvalues))
rank = groupedvalues["Count"].argsort().argsort()

#get summary stats of data
summary=pd.DataFrame(con['Count'].describe())
#set limits
maxLim=100
minLim=min(con['Count'])-0.1
#barplot horizontal
g=sns.barplot(x='Count', y ='Sample',data=groupedvalues,  palette=np.array(pal[::-1])[rank])
plt.xlim(minLim,maxLim)
plt.xticks(np.arange(minLim, 100, 0.1))
#remove labels
g.set(yticks=[])

g.set(xlabel='BLA BLA BLA', ylabel='Sample')
plt.table(cellText=summary.values,
          rowLabels=summary.index,
          colLabels=summary.columns,
          cellLoc = 'center', rowLoc = 'center',
          loc='right')
#plt.show()
plt.savefig('outTest.png', dpi=150)
</code>```

This outputs :
This table on the right of the image is cut off.  How do I fix this and also just round down to nearest 0.1 on the labels please?

Thanks

答:
In principle, the same strategies than in this question's answer apply here.

Using bbox

You may freely position the table on your graph using the bbox argument, bbox = [left, bottom, width, height] where left, bottom, width, height are fractions of the axes.

```<code>import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

df = pd.DataFrame({"count" : np.sort(np.random.rand(100))*100})

summary=pd.DataFrame(df['count'].describe())

plt.barh(range(len(df)),df["count"])

plt.table(cellText=summary.values,
          rowLabels=summary.index,
          colLabels=summary.columns,
          cellLoc = 'right', rowLoc = 'center',
          loc='right', bbox=[.65,.05,.3,.5])

plt.savefig("out.png")
plt.show()
</code>```

This would also allow to put the table outside the axes by choosing the paramters larger than 1. In order to make space for the table, you can then shrink the subplots, plt.subplots_adjust(right=0.75).

```<code>plt.table(cellText=summary.values,
          rowLabels=summary.index,
          colLabels=summary.columns,
          cellLoc = 'right', rowLoc = 'center',
          loc='right', bbox=[1,.3,.3,.5])

plt.subplots_adjust(right=0.75)
</code>```

Using dedicated subplot

You may use a dedicated subplot to put the table in.

```<code>import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

df = pd.DataFrame({"count" : np.sort(np.random.rand(100))*100})

summary=pd.DataFrame(df['count'].describe())

fig,(ax,tabax) = plt.subplots(ncols=2, gridspec_kw=dict(width_ratios=[2,1]))
ax.barh(range(len(df)),df["count"])

tabax.axis("off")
tabax.table(cellText=summary.values,
          rowLabels=summary.index,
          colLabels=summary.columns,
          cellLoc = 'right', rowLoc = 'center',
          loc='center')

plt.savefig("out.png")
plt.show()
</code>```

Title: Plot table alongside sns.barplot

Body:
#read data into dataframe
con=pd.read_csv('testOutput.csv')

'''
testOutput.csv looks like :
Sample,Count
sample1,99.9
sample2, 96.6
'''

## set colours to increase with values
sns.set(style="darkgrid")
groupedvalues=con.groupby("Count").sum().reset_index()
pal = sns.color_palette("Greens_d", len(groupedvalues))
rank = groupedvalues["Count"].argsort().argsort()

#get summary stats of data
summary=pd.DataFrame(con['Count'].describe())
#set limits
maxLim=100
minLim=min(con['Count'])-0.1
#barplot horizontal
g=sns.barplot(x='Count', y ='Sample',data=groupedvalues,  palette=np.array(pal[::-1])[rank])
plt.xlim(minLim,maxLim)
plt.xticks(np.arange(minLim, 100, 0.1))
#remove labels
g.set(yticks=[])

g.set(xlabel='BLA BLA BLA', ylabel='Sample')
plt.table(cellText=summary.values,
          rowLabels=summary.index,
          colLabels=summary.columns,
          cellLoc = 'center', rowLoc = 'center',
          loc='right')
#plt.show()
plt.savefig('outTest.png', dpi=150)

This outputs :
This table on the right of the image is cut off.  How do I fix this and also just round down to nearest 0.1 on the labels please?

Thanks

Body:
In principle, the same strategies than in this question's answer apply here.

Using bbox

You may freely position the table on your graph using the bbox argument, bbox = [left, bottom, width, height] where left, bottom, width, height are fractions of the axes.

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

df = pd.DataFrame({"count" : np.sort(np.random.rand(100))*100})

summary=pd.DataFrame(df['count'].describe())

plt.barh(range(len(df)),df["count"])

plt.table(cellText=summary.values,
          rowLabels=summary.index,
          colLabels=summary.columns,
          cellLoc = 'right', rowLoc = 'center',
          loc='right', bbox=[.65,.05,.3,.5])

plt.savefig("out.png")
plt.show()

This would also allow to put the table outside the axes by choosing the paramters larger than 1. In order to make space for the table, you can then shrink the subplots, plt.subplots_adjust(right=0.75).

plt.table(cellText=summary.values,
          rowLabels=summary.index,
          colLabels=summary.columns,
          cellLoc = 'right', rowLoc = 'center',
          loc='right', bbox=[1,.3,.3,.5])

plt.subplots_adjust(right=0.75)

Using dedicated subplot

You may use a dedicated subplot to put the table in.

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

df = pd.DataFrame({"count" : np.sort(np.random.rand(100))*100})

summary=pd.DataFrame(df['count'].describe())

fig,(ax,tabax) = plt.subplots(ncols=2, gridspec_kw=dict(width_ratios=[2,1]))
ax.barh(range(len(df)),df["count"])

tabax.axis("off")
tabax.table(cellText=summary.values,
          rowLabels=summary.index,
          colLabels=summary.columns,
          cellLoc = 'right', rowLoc = 'center',
          loc='center')

plt.savefig("out.png")
plt.show()


问:
What are some best practices for optimizing multiple column LIKE SQL queries?
I have a search query that I'm inheriting and attempting to optimize. I am curious to hear if anyone has any best practices and recommendations for such.  The production server is still SQL Server 2000 also.

The query is an advanced customer search stored procedure that accepts 5 different search criteria parameters (i.e. first name, last name, address, phone, etc.) to search a multi-million record table.  There are indexes on all joined columns and columns in the WHERE clause.  In addition, the initial query dumps the records into a table variable for paging capacity.

```<code>INSERT INTO   @tempCustTable (CustomerID, FirstName, LastName, City, StateProvince, Zip, PhoneNumber)
SELECT  DISTINCT cu.CustomerID, cu.FirstName, cu.LastName, a.City,
a.StateProvince, a.Zip, p.PhoneNumber
FROM Customer cu WITH(NOLOCK)
LEFT OUTER JOIN Address a WITH(NOLOCK) ON cu.CustomerID = a.CustomerID
LEFT OUTER JOIN Phone p WITH(NOLOCK) ON cu.CustomerID = p.CustomerID
WHERE  (cu.LastName = @LastName OR cu.LastName LIKE @LastName + '%')
AND (@FirstName IS NULL OR cu.FirstName = @FirstName OR cu.FirstName LIKE @FirstName + '%')
AND (@StateProvince = '' OR a.StateProvince LIKE @StateProvince)
AND (@City = '' OR a.City LIKE @City + '%')
AND (@Zip = '' OR a.Zip = @Zip OR a.Zip LIKE @Zip + '%')
ORDER BY cu.LastName, cu.FirstName
</code>```

Does anyone have any recommendations on how I could improve the performance of the query?

答:
You could build up the query with dynamic sql. That would get rid of most of your ORs and would also mean you would only need to include in the WHERE statement lines for the parameters the user did actually enter.

If you do this, be sure to use sp_executesql rather than exec so you can parameterize the dynamic sql so the query plan can be cached.

OwnerDisplayName: JamesEggers

Body:
I have a search query that I'm inheriting and attempting to optimize. I am curious to hear if anyone has any best practices and recommendations for such.  The production server is still SQL Server 2000 also.

The query is an advanced customer search stored procedure that accepts 5 different search criteria parameters (i.e. first name, last name, address, phone, etc.) to search a multi-million record table.  There are indexes on all joined columns and columns in the WHERE clause.  In addition, the initial query dumps the records into a table variable for paging capacity.

INSERT INTO   @tempCustTable (CustomerID, FirstName, LastName, City, StateProvince, Zip, PhoneNumber)
SELECT  DISTINCT cu.CustomerID, cu.FirstName, cu.LastName, a.City,
a.StateProvince, a.Zip, p.PhoneNumber
FROM Customer cu WITH(NOLOCK)
LEFT OUTER JOIN Address a WITH(NOLOCK) ON cu.CustomerID = a.CustomerID
LEFT OUTER JOIN Phone p WITH(NOLOCK) ON cu.CustomerID = p.CustomerID
WHERE  (cu.LastName = @LastName OR cu.LastName LIKE @LastName + '%')
AND (@FirstName IS NULL OR cu.FirstName = @FirstName OR cu.FirstName LIKE @FirstName + '%')
AND (@StateProvince = '' OR a.StateProvince LIKE @StateProvince)
AND (@City = '' OR a.City LIKE @City + '%')
AND (@Zip = '' OR a.Zip = @Zip OR a.Zip LIKE @Zip + '%')
ORDER BY cu.LastName, cu.FirstName

Does anyone have any recommendations on how I could improve the performance of the query?