问:
How to detect top legit search engine bots?
I want to develop a very robust method to detect only a few top search engines spiders such as googlebot and let them access content on my site, otherwise usual user registeration/login required to view that content.

Note that I also make use of cookies to let users access some content without being registered. So if cookies are disabled on client browser, no content except front page is offered. But I heard search engine spiders dont accept cookies so this will also shut out legitimate search engine bots. Is this correct?

One suggestion I heard is to do reverse lookup from ip address and if it resolves to for example googlebot.com, then do a forward dns lookup and if get back the original ip, then its legitimate and not some one impersonating as googlebot. I am using Java on linux server , so java based solution I am looking for.

I am only letting in top good search engine spiders such as google yahoo bing alexa etc and keep the others out to reduce server loads. But its very important top spiders index my site.

答:
For a more complete answer to your question, you can't rely on only one approach.  The problem is the conflicting nature of what you want to do.  Essentially you want to allow good bots to access your site and index it so you can appear on search engines; but you want to block bad bots from sucking up all your bandwidth and stealing your information.

First line of defense:

Create a robots.txt file at the root of your site.  See http://www.robotstxt.org/ for more information about that.  This will keep good, well behaved bots in the areas of the site that make the most sense.  Keep in mind that robots.txt relies on the User-Agent string if you provide different behavior for one bot vs. another bot.  See http://www.robotstxt.org/db.html

Second line of defense:

Filter on User-Agent and/or IP address.  I've already been criticized for suggesting that, but it's surprising how few bots disguise who and what they are--even the bad ones.  Again, it's not going to stop all bad behavior, but it provides a level of due diligence.  More on leveraging User-Agent later.

Third line of defense:

Monitor your Web server's access logs.  Use a log analyzer to figure out where the bulk of your traffic is comming from.  These logs include both IP address and user-agent strings so you can detect how many instances of a bot is hitting you, and whether it is really who it says it is: see http://www.robotstxt.org/iplookup.html

You may have to whip up your own log analyzer to find out the request rate from different clients.  Anything above a certain threshold (like maybe 10/second) would be a candidate to rate limit later on.

Leveraging User Agent for Alternative Site Content:

An approach we had to take to protect our users from even legitimate bots hammering our site is to split traffic based on the User-Agent.  Basically, if the User-Agent was a known browser, they got the full featured site.  If it was not a known browser it was treated as a bot, and was given a set of simple HTML files with just the meta information and links they needed to do their job.  The bot's HTML files were statically generated four times a day, so there was no processing overhead.  You can also render RSS feeds instead of stripped down HTML which provide the same function.

Final Note:

You only have so many resources, and not every legitimate bot is well behaved (i.e. ignores robots.txt and puts a lot of stress on your server).  You will have to update your approach over time.  For example, if one IP address turns out to be a custom search bot your client (or their client) made, you may have to resort to rate-limiting that IP address instead of blocking it completely.

Essentially you are trying to get a good balance between serving your users, and keeping your site available for search engines.  Do enough to keep your site responsive to the users, and only resort to the more advanced tactics as necessary.


来源: stackexchange

问:
Center Input box and Font Awesome icons
Others have asked something similar but I seem to be struggling vertical aligning the font awesome icon with an input box.  It works okay when you don`t use the sizing to increase the font awesome icons, but as soon as you enter the fa-3x or something like that the margin-top gets added.

Does anybody have any ideas ?

Simple example would be:

```<code><div>
    <i class='icon icon-3x icon-camera'></i>
    <span id="inputfield">
      <input type="text" value="input here">
    </span>
</div>

div {
    border: 1px solid #ccc;
    height: 30px;
    margin: 60px;
    padding: 4px;
    vertical-align: middle;
}
i{
    float: left;
}
#inputfield{
    line-height: 30px;
    float: left;
}
</code>```

答:
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
<form>
<fieldset>
<legend></legend>
<input type="text" class="something">
</fieldset>
</form>```

ContentLicense: CC BY-SA 3.0

Title: Center Input box and Font Awesome icons

Body:
Others have asked something similar but I seem to be struggling vertical aligning the font awesome icon with an input box.  It works okay when you don`t use the sizing to increase the font awesome icons, but as soon as you enter the fa-3x or something like that the margin-top gets added.

Does anybody have any ideas ?

Simple example would be:

      <input type="text" value="input here">

div {
    border: 1px solid #ccc;
    height: 30px;
    margin: 60px;
    padding: 4px;
    vertical-align: middle;
}
i{
    float: left;
}
#inputfield{
    line-height: 30px;
    float: left;
}

Body:
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
<form>
<fieldset>
<legend><i class="fa fa-user" aria-hidden="true"></i></legend>
<input type="text" class="something">
</fieldset>
</form>


问:
winforms window too large
I think the images say enough...
The grey part of the window overlaps the blue side.

I can fix the problem with the normal window by making it a little bit larger or if I change scaling to DPI. My laptop is set to 125% scaling, I think that is the problem? But how do I fix the messagebox?

I am using Visual studio 2017 15.2 it's an C# Winforms app with .net framework 4.6.2

MessageBox window too large:

Window too large:

答: You could try not using 125% scaling, or you could just resize it to fit properly. In Visual Studio you can edit the size of the window (min and max size), fiddle around with those and you might find a good size for your project.</p>

Title: winforms window too large


问:
JPA: What's a good way to update data from an external source?
I have some text files, from an external source, from which data is parsed. The output of the Java based parser is a list of Java objects representing the parsed data. The data objects have been annotated with JPA tags and are persisted into a database.

I receive regular updates to these text files, which may or may not have been changed. When the parser runs again on the updated data, it creates a new list of the objects. I need to consolidate the newer version of the objects with the ones already in the database. What is a good approach to figuring out what is different from the objects from the newly pared text files and what already exists in the database so that any updates or new data can be persisted?

答:
You lack some idnetifier. Create a column in your tables which will represent the source whcih  you have created the object from( filename, or line of a particular file - you haven't described the format).

Then you will be able to read the object from database, update it with the new values and write it to the db back.

ContentLicense: CC BY-SA 2.5


问:
How to insert item into list in order?
I have a List of DateTimeOffset objects, and I want to insert new ones into the list in order.

```<code>List<DateTimeOffset> TimeList = ...
// determine the order before insert or add the new item
</code>```

Sorry, need to update my question.

```<code>List<customizedClass> ItemList = ...
//customizedClass contains DateTimeOffset object and other strings, int, etc.

ItemList.Sort();    // this won't work until set data comparison with DateTimeOffset
ItemList.OrderBy(); // this won't work until set data comparison with DateTimeOffset
</code>```

Also, how to put DateTimeOffset as the parameter of .OrderBy()?

I have also tried:

```<code>ItemList = from s in ItemList
           orderby s.PublishDate descending    // .PublishDate is type DateTime
           select s;
</code>```

However, it returns this error message,

Cannot implicitly convert type 'System.Linq.IOrderedEnumerable' to 'System.Collections.Gerneric.List'. An explicit conversion exist (are  you missing a cast?)

答:
very simple,
after adding data into list</p>

```<code>list.OrderBy(a => a.ColumnName).ToList();
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to insert item into list in order?

Body:
I have a List of DateTimeOffset objects, and I want to insert new ones into the list in order.

List<DateTimeOffset> TimeList = ...
// determine the order before insert or add the new item

Sorry, need to update my question.

List<customizedClass> ItemList = ...
//customizedClass contains DateTimeOffset object and other strings, int, etc.

ItemList.Sort();    // this won't work until set data comparison with DateTimeOffset
ItemList.OrderBy(); // this won't work until set data comparison with DateTimeOffset

Also, how to put DateTimeOffset as the parameter of .OrderBy()?

I have also tried:

ItemList = from s in ItemList
           orderby s.PublishDate descending    // .PublishDate is type DateTime
           select s;

However, it returns this error message,

Cannot implicitly convert type 'System.Linq.IOrderedEnumerable' to 'System.Collections.Gerneric.List'. An explicit conversion exist (are  you missing a cast?)

Body:
very simple,
after adding data into list

list.OrderBy(a => a.ColumnName).ToList();


问:
Examples Realm Butterknife
I was wondering if anyone had any examples of using realm and butter knife together. Is it possible to use the two together? </p>

<p>So far what I have tried is the following, But I am not certain it is correct. I was told to use ExecuteTransaction but I'm not certain it's appropriate. </p>

```<code>public class MainFragmentActivity extends FragmentActivity {

    MainFragmentAdaptor mMainFragmentAdaptor;
    ViewPager mViewPager;
    Player player;
    Realm realm;

    @BindView(R.id.et_character_name)
    EditText et_character_name;

    @OnTextChanged(R.id.et_character_name)
    protected void onTextChanged(CharSequence text) {
        String name = text.toString();
        player.setName(name);

        try {
            realm.executeTransaction(new Realm.Transaction() {
                @Override
                public void execute(Realm realm) {

                    realm.copyToRealmOrUpdate(player);
                    player.setCurrentHP(37);
                }
            });
        } catch (Exception e) {
            Log.e("REALM SET PLAYER ERROR", e.toString());
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);

        realm = Realm.getDefaultInstance();
        setContentView(R.layout.activity_main_fragment);
        mViewPager = (ViewPager) findViewById(R.id.viewpager);
        mViewPager.setAdapter(mMainFragmentAdaptor);

        try {
            realm.executeTransaction(new Realm.Transaction() {
                @Override
                public void execute(Realm realm) {
                    player = realm.createObject(Player.class);
                    player.setCurrentHP(37);
                }
            });
        } catch (Exception e) {
            Log.e("REALM SET PLAYER ERROR", e.toString());
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (realm != null) { // guard against weird low-budget phones
            realm.close();
            realm = null;
        }
    }
}
</code>```

答:
Is it possible to use the two together?

Yes. both are independent of each other.

I was told to use ExecuteTransaction but I'm not certain it's
  appropriate.

You should in most cases use executeTransaction() since it will handle errors for you. The only reason for using beginTransaction() is normally if you want to have some custom error handling.*

For more information see this link

Title: Examples Realm Butterknife

Body:
I was wondering if anyone had any examples of using realm and butter knife together. Is it possible to use the two together?

So far what I have tried is the following, But I am not certain it is correct. I was told to use ExecuteTransaction but I'm not certain it's appropriate.

public class MainFragmentActivity extends FragmentActivity {

    MainFragmentAdaptor mMainFragmentAdaptor;
    ViewPager mViewPager;
    Player player;
    Realm realm;

    @BindView(R.id.et_character_name)
    EditText et_character_name;

    @OnTextChanged(R.id.et_character_name)
    protected void onTextChanged(CharSequence text) {
        String name = text.toString();
        player.setName(name);

        try {
            realm.executeTransaction(new Realm.Transaction() {
                @Override
                public void execute(Realm realm) {

                    realm.copyToRealmOrUpdate(player);
                    player.setCurrentHP(37);
                }
            });
        } catch (Exception e) {
            Log.e("REALM SET PLAYER ERROR", e.toString());
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);

        realm = Realm.getDefaultInstance();
        setContentView(R.layout.activity_main_fragment);
        mViewPager = (ViewPager) findViewById(R.id.viewpager);
        mViewPager.setAdapter(mMainFragmentAdaptor);

        try {
            realm.executeTransaction(new Realm.Transaction() {
                @Override
                public void execute(Realm realm) {
                    player = realm.createObject(Player.class);
                    player.setCurrentHP(37);
                }
            });
        } catch (Exception e) {
            Log.e("REALM SET PLAYER ERROR", e.toString());
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (realm != null) { // guard against weird low-budget phones
            realm.close();
            realm = null;
        }
    }
}


问:
r transpose column of strings to rows using a 'stop' value to create rows of irregular length
I have a dataset for which I want to create groups based on some marking values.
As an example, the data set looks like thisinput

The values are ad in chronological sequence, with every value up to the value 'end' being one day. I'm trying to reorganise the data so that the values of the first column appear like this:
output

At first, I assumed it would be a simple transpose problem, but I can't see any argument or parameter to specify that the groups are delimited by the value 'end'

As I type, it occurs to me that maybe a for loop could run through the values and reorganise them, using the 'end' value like a stop codon in DNA transcription, but I'd like to make sure the isn't a simpler way before I start down that road.

答:
How's this?</p>

```<code>df <- data.frame(name = c("aa",
                          "bb",
                          "cc",
                          "dd",
                          "end",
                          "ee",
                          "ff",
                          "gg",
                          "end"))

unlist(strsplit(paste(df$name, collapse = " "), " end "))
</code>```

Body:
How's this?

df <- data.frame(name = c("aa",
                          "bb",
                          "cc",
                          "dd",
                          "end",
                          "ee",
                          "ff",
                          "gg",
                          "end"))

unlist(strsplit(paste(df$name, collapse = " "), " end "))


答:
You can try:</p>

```<code>library(tidyverse)
df2 %>%
   semi_join(df1, by="Date") %>%
   group_by(Date) %>%
   filter(n() < 2) %>%
   mutate(Miss=ifelse(name== "p1", "p2", "p1"))
Source: local data frame [2 x 3]
Groups: V1 [2]

                 Date   name  Miss
               <fctr> <fctr> <chr>
1 2014-01-01 01:02:00     p2    p1
2 2014-01-01 01:03:00     p1    p2
</code>```

Title: how to extract the rows which are not matching with df

Body:
df1

Date
2014-01-01 01:01:00
2014-01-01 01:02:00
2014-01-01 01:03:00

df2
Date                      **name**
2014-01-01 01:01:00        **p1**
2014-01-01 01:03:00        **p1**
2014-01-01 01:01:00        **p2**
2014-01-01 01:02:00        **p2**

How do we get missing rows from df2 i.e
time series with minute 02 is missing for "p1" and 03 for p2

I have tried with below code

a=merge(x = df1, y = df2, by = "Date", all.x = TRUE)

and getting only missind dates

o/p

Date                    **name**
2014-01-01 01:02:00     **p1**
2014-01-01 01:03:00     **p2**

Thanks in advance

Body:
You can try:

library(tidyverse)
df2 %>%
   semi_join(df1, by="Date") %>%
   group_by(Date) %>%
   filter(n() < 2) %>%
   mutate(Miss=ifelse(name== "p1", "p2", "p1"))
Source: local data frame [2 x 3]
Groups: V1 [2]

                 Date   name  Miss
               <fctr> <fctr> <chr>
1 2014-01-01 01:02:00     p2    p1
2 2014-01-01 01:03:00     p1    p2


问:
How do I resolve xsl:include directives in c++ (can't use .NET framework)
I need to load an xslt from a database and hold it in memory so that it can be included by another xslt.

I know you can do this using the .NET framework and the xmlPreLoadedResolver class, but unfortunately, we're not allowed to write this as a .NET dll.

Does anyone know if its possible to do this using the msxml6 C++ interfaces?

答:
MSXML does support XSLT 1.0. See here for more on this: Creating XSLT Solutions

Basically everything is based on the transformNode and transformNodeToObject methods: transformNode Method


问:
Why does a function parameter call a constructor with an argument?
I have this code(stolen from cplusplus.com):

```<code>// explicit:
#include <iostream>
using namespace std;

class A {};

class B {
public:
  explicit B (const A& x) {}
  B& operator= (const A& x) {return *this;}
  operator A() {return A();}
};

void fn (B x) {}

int main ()
{
  A foo;
  B bar (foo);
  bar = foo;
  foo = bar;

//  fn (foo);  // not allowed for explicit ctor.
  fn (bar);

  return 0;
}
</code>```

So apparently the statement fn (foo); would call the constructor defined in class B, and I do not really get why. Why would that call a constructor with an argument, I mean aren't things simply copied to the function parameters when not using a reference? If fn (foo); calls the constructor B (const A& x) {}, shouldn't fn (bar); generate an error since there is no constructor defined for an argument of type B, such as B (const B& x) {}?

答:
From the C++ Standard

15 The initialization that occurs in the = form of a brace-or-equal-initializer or condition (6.4), as well as in argument passing, function return, throwing an exception (15.1), handling an exception (15.3), and aggregate member initialization (8.6.1), is called copy-initialization. [ Note: Copy-nitialization may invoke a move (12.8).—end note ]

Thus for the explicit constructor

```<code>explicit B (const A& x) {}
</code>```

this initialization that in fact is used for the initialization of the function parameter

```<code>A foo;
B bar = foo;
</code>```

is wrong.

It is the direct initialization that can be used with the explicit constructor as it is shown in your program

```<code>A foo;
B bar( foo );
</code>```

Body:
I have this code(stolen from cplusplus.com):

// explicit:
#include <iostream>
using namespace std;

class A {};

class B {
public:
  explicit B (const A& x) {}
  B& operator= (const A& x) {return *this;}
  operator A() {return A();}
};

void fn (B x) {}

int main ()
{
  A foo;
  B bar (foo);
  bar = foo;
  foo = bar;

//  fn (foo);  // not allowed for explicit ctor.
  fn (bar);

  return 0;
}

So apparently the statement fn (foo); would call the constructor defined in class B, and I do not really get why. Why would that call a constructor with an argument, I mean aren't things simply copied to the function parameters when not using a reference? If fn (foo); calls the constructor B (const A& x) {}, shouldn't fn (bar); generate an error since there is no constructor defined for an argument of type B, such as B (const B& x) {}?

Body:
From the C++ Standard

15 The initialization that occurs in the = form of a brace-or-equal-initializer or condition (6.4), as well as in argument passing, function return, throwing an exception (15.1), handling an exception (15.3), and aggregate member initialization (8.6.1), is called copy-initialization. [ Note: Copy-nitialization may invoke a move (12.8).—end note ]

Thus for the explicit constructor

explicit B (const A& x) {}

this initialization that in fact is used for the initialization of the function parameter

A foo;
B bar = foo;

is wrong.

It is the direct initialization that can be used with the explicit constructor as it is shown in your program

A foo;
B bar( foo );


问:
Getting confused while padding number into integer number
Using String.format

If I use %5  I get output with space as output 1.

If I use %05 I get output as output 2.

Why is output 1 printing space instead of padding number?

 Output 1 ::    12 (String str = String.format("%5d", 12);)
 Output 2 :: 00012 (String str = String.format("%05d", 12);)
```

Output 2 is correct. But my question is what is need to '0' with '%'?

答:
As the String.format redirect to the Formatter page, you can found the syntax about numeric, more important, the flags :

Flags

'0'    -   Requires the output to be padded with leading zeros to the minimum field width following any sign or radix indicator except when converting NaN or infinity. If the width is not provided, then a MissingFormatWidthException will be thrown.
      ...

This explained why you have leading '0'

Then, you have default style saying that if you don't specify it,

The output is right-justified within the width

So it use space the right-justified by default, or '0' if you ask leading 0.

Body:
Using String.format

If I use %5  I get output with space as output 1.

If I use %05 I get output as output 2.

Why is output 1 printing space instead of padding number?

 Output 1 ::    12 (String str = String.format("%5d", 12);)
 Output 2 :: 00012 (String str = String.format("%05d", 12);)

Output 2 is correct. But my question is what is need to '0' with '%'?


问:
App is in foreground for more time
If an IOS app is in the foreground for more time, screen is not locked, even though the User is not doing any actions on the app. After 10 mts, what will be the app state?

Should the app request and respond for every 10 minutes to determine whether the app will be able to send the request for every 10 minutes?

答:
If you want your app to be able to use WiFi even after longer time of user inactivity you have to use this key in info.plist:

```<code><key>UIRequiresPersistentWiFi</key>
<true/>
</code>```

And if you need to keep the screen on as well you can disable idle timer:

```<code>[[UIApplication sharedApplication] setIdleTimerDisabled:YES];
</code>```

Title: App is in foreground for more time

Body:
If you want your app to be able to use WiFi even after longer time of user inactivity you have to use this key in info.plist:

<key>UIRequiresPersistentWiFi</key>
<true/>

And if you need to keep the screen on as well you can disable idle timer:

[[UIApplication sharedApplication] setIdleTimerDisabled:YES];


问:
Search and replace of several sentences using bash
now, i have script to search and replace words. How can i do the same for sentences or wordcombinations.
Look on my script:

```<code>first_words="wwe wwf ziggler"
second_words="tna njpw okada"

mywords=( $first_words )
mywords2=( $second_words )

if [ ${#mywords[@]} != ${#mywords2[@]} ];then
        echo "you should use the same count of words"
        exit 1
else
        echo "you are using the same count of words, continue ..."
fi

for ((i=0;i<"${#mywords[@]}";++i)); do
        sed -i "s/${mywords[$i]}/${mywords2[$i]}/g" text.txt
done
</code>```

It works, but only replace word by word. But if i want to replace several wordcombinations on several wordcombinations.
For example "dolph ziggler, john cena, randy orton" i want to replace on "cm punk, hulk hogan, rey mysterio". What i should do in this situnation. May be i should handle some delimiter. In first case, the space was delimiter for words, but in this situation, i can't use space. What i can do ? Please help.

答:
```<code>mysentences=( "first sentence" "second sentence" )
mysentences2=( "new first" "new second" )
...
for ((i=0;i<"${#mysentences[@]}";++i)); do
    sed -i "s/${mysentences[$i]}/${mysentences2[$i]}/g" text.txt
done
</code>```

Warning, if sentences can contain / they must be escaped and if they can contain character which have a special meaning in regex can be escaped in perl with \Q and \E.

```<code>perl -i -pe 's/\Q'"${mysentences[$i]//\//\\/}"'\E/'"${mysentences2[$i]//\//\\/}/g" text.txt
</code>```

Note: it's not safe, injection still possible

```<code>mysentences=( "bar" )
mysentences2=( '@{[`echo ok >&2`]}' )

perl -pe 's/\Q'"${mysentences[$i]//\//\\/}"'\E/'"${mysentences2[$i]//\//\\/}/g" <<<"foo bar baz"
</code>```

passing sentences as arguments to prevent injection

```<code>perl -pe 'BEGIN{$oldtext=shift;$newtext=shift}s/\Q$oldtext\E/$newtext/g' "${mysentences[$i]//\//\\/}" "${mysentences2[$i]//\//\\/}" <<<"foo bar baz"
</code>```

Body:
now, i have script to search and replace words. How can i do the same for sentences or wordcombinations.
Look on my script:

first_words="wwe wwf ziggler"
second_words="tna njpw okada"

mywords=( $first_words )
mywords2=( $second_words )

if [ ${#mywords[@]} != ${#mywords2[@]} ];then
        echo "you should use the same count of words"
        exit 1
else
        echo "you are using the same count of words, continue ..."
fi

for ((i=0;i<"${#mywords[@]}";++i)); do
        sed -i "s/${mywords[$i]}/${mywords2[$i]}/g" text.txt
done

It works, but only replace word by word. But if i want to replace several wordcombinations on several wordcombinations.
For example "dolph ziggler, john cena, randy orton" i want to replace on "cm punk, hulk hogan, rey mysterio". What i should do in this situnation. May be i should handle some delimiter. In first case, the space was delimiter for words, but in this situation, i can't use space. What i can do ? Please help.

Body:
mysentences=( "first sentence" "second sentence" )
mysentences2=( "new first" "new second" )
...
for ((i=0;i<"${#mysentences[@]}";++i)); do
    sed -i "s/${mysentences[$i]}/${mysentences2[$i]}/g" text.txt
done

Warning, if sentences can contain / they must be escaped and if they can contain character which have a special meaning in regex can be escaped in perl with \Q and \E.

perl -i -pe 's/\Q'"${mysentences[$i]//\//\\/}"'\E/'"${mysentences2[$i]//\//\\/}/g" text.txt

Note: it's not safe, injection still possible

mysentences=( "bar" )
mysentences2=( '@{[`echo ok >&2`]}' )

perl -pe 's/\Q'"${mysentences[$i]//\//\\/}"'\E/'"${mysentences2[$i]//\//\\/}/g" <<<"foo bar baz"

passing sentences as arguments to prevent injection

perl -pe 'BEGIN{$oldtext=shift;$newtext=shift}s/\Q$oldtext\E/$newtext/g' "${mysentences[$i]//\//\\/}" "${mysentences2[$i]//\//\\/}" <<<"foo bar baz"


问:
You have not defined a default connection
How I can resolve this error?

```<code>File "/usr/local/lib/python2.7/dist-packages/mongoengine/connection.py", line 95, in get_connection
    raise ConnectionError(msg)
mongoengine.connection.ConnectionError: You have not defined a default connection
</code>```

model.py:

```<code>from flask.ext.mongoengine import MongoEngine

db = MongoEngine()

class Currencies(db.Document):
    # meta = {"db_alias": "currencies"}
    name = db.StringField(max_length=40, min_length=3)
    def __unicode__(self):
        return self.name
</code>```

MongoEngine config in app.py:

```<code>from models import db

app = Flask(__name__)
app.config['MONGODB_SETTINGS'] = {'DB':'testing'}
db.init_app(app)
</code>```

views.py:

```<code>from models import Currencies

print Currencies.objects.find()
</code>```

Flask-Admin normally works.

答:
You can deal this problem with setting the DEFAULT_CONNECTION_NAME in your config file like this:

from mongoengine import connect

DEFAULT_CONNECTION_NAME = connect('blog')

Body:
How I can resolve this error?

File "/usr/local/lib/python2.7/dist-packages/mongoengine/connection.py", line 95, in get_connection
    raise ConnectionError(msg)
mongoengine.connection.ConnectionError: You have not defined a default connection

model.py:

from flask.ext.mongoengine import MongoEngine

db = MongoEngine()

class Currencies(db.Document):
    # meta = {"db_alias": "currencies"}
    name = db.StringField(max_length=40, min_length=3)
    def __unicode__(self):
        return self.name

MongoEngine config in app.py:

from models import db

app = Flask(__name__)
app.config['MONGODB_SETTINGS'] = {'DB':'testing'}
db.init_app(app)

views.py:

from models import Currencies

print Currencies.objects.find()

Flask-Admin normally works.


问:
django.core.exceptions.ImproperlyConfigured: Error loading either pysqlite2 or sqlite3 modules (tried in that order): No module named _sqlite3
I tried re-installing python 2 in my environment.

Re-installed pip, setuptools

when I try to run python manage.py runserver it throws the error

```<code>django.core.exceptions.ImproperlyConfigured: Error loading either pysqlite2 or sqlite3 modules (tried in that order): No module named _sqlite3
</code>```

I tried installing sqlite 3 , its already installed

I tried installing pysqlite2 , its already installed

both python 2 and installed in my ubuntu 16.04, django version = 1.8.X

Still unaware of what cause the error?

答:
For Ubuntu users:
Download the source file of the Python version that you need, from source. Extract the folder somewhere, cd into the folder,

```<code>./configure
make
make install
</code>```

this should fix your issue.
(This can be done outside VE, i just had the same issues with python 3.4)

Body:
I tried re-installing python 2 in my environment.

Re-installed pip, setuptools

when I try to run python manage.py runserver it throws the error

django.core.exceptions.ImproperlyConfigured: Error loading either pysqlite2 or sqlite3 modules (tried in that order): No module named _sqlite3

I tried installing sqlite 3 , its already installed

I tried installing pysqlite2 , its already installed

both python 2 and installed in my ubuntu 16.04, django version = 1.8.X

Still unaware of what cause the error?

Body:
For Ubuntu users:
Download the source file of the Python version that you need, from source. Extract the folder somewhere, cd into the folder,

./configure
make
make install

this should fix your issue.
(This can be done outside VE, i just had the same issues with python 3.4)


问:
Cannot read file within jar file
I developped an application using spring-boot, I need to read a csv file that contain emails.

this is a snippet how I do:

```<code>public Set<String> readFile() {
        Set<String> setOfEmails = new HashSet<String>();

        try {
            ClassPathResource cl = new ClassPathResource("myFile.csv");
            File file = cl.getFile();
            Stream<String> stream = Files.lines(Paths.get(file.getPath()));
            setOfEmails = stream.collect(Collectors.toSet());

        } catch (IOException e) {
            logger.error("file error " + e.getMessage());
        }
        return setOfEmails;
    }
</code>```

It works when I execute the application using eclipse: run As --> spring-boot app

But when I put the jar into a container docker the method readFile() return an empty set.

I use gradle for build the application

Would you have any ideas ?

答:
The javadocs for ClassPathResource state:

Supports resolution as java.io.File if the class path resource resides in the file system, but not for resources in a JAR. Always supports resolution as URL.

So when the resource (the CSV file) is in a JAR file, getFile() is going to fail.

The solution is to use getURL() instead, then open the URL as an input stream, etcetera.  Something like this:

```<code>public Set<String> readFile() {
    Set<String> setOfEmails = new HashSet<String>();

    ClassPathResource cl = new ClassPathResource("myFile.csv");
    URL url = cl.getURL();
    try (BufferedReader br = new BufferedReader(
                             new InputStreamReader(url.openStream()))) {

        Stream<String> stream = br.lines();
        setOfEmails = stream.collect(Collectors.toSet());
    } catch (IOException e) {
        logger.error("file error " + e.getMessage());
    }
    return setOfEmails;
}
</code>```

If it still fails check that you are using the correct resource path.

Title: Cannot read file within jar file

Body:
I developped an application using spring-boot, I need to read a csv file that contain emails.

this is a snippet how I do:

public Set<String> readFile() {
        Set<String> setOfEmails = new HashSet<String>();

        try {
            ClassPathResource cl = new ClassPathResource("myFile.csv");
            File file = cl.getFile();
            Stream<String> stream = Files.lines(Paths.get(file.getPath()));
            setOfEmails = stream.collect(Collectors.toSet());

        } catch (IOException e) {
            logger.error("file error " + e.getMessage());
        }
        return setOfEmails;
    }

It works when I execute the application using eclipse: run As --> spring-boot app

But when I put the jar into a container docker the method readFile() return an empty set.

I use gradle for build the application

Would you have any ideas ?

Body:
The javadocs for ClassPathResource state:

Supports resolution as java.io.File if the class path resource resides in the file system, but not for resources in a JAR. Always supports resolution as URL.

So when the resource (the CSV file) is in a JAR file, getFile() is going to fail.

The solution is to use getURL() instead, then open the URL as an input stream, etcetera.  Something like this:

public Set<String> readFile() {
    Set<String> setOfEmails = new HashSet<String>();

    ClassPathResource cl = new ClassPathResource("myFile.csv");
    URL url = cl.getURL();
    try (BufferedReader br = new BufferedReader(
                             new InputStreamReader(url.openStream()))) {

        Stream<String> stream = br.lines();
        setOfEmails = stream.collect(Collectors.toSet());
    } catch (IOException e) {
        logger.error("file error " + e.getMessage());
    }
    return setOfEmails;
}

If it still fails check that you are using the correct resource path.


问:
When to use an object or an array in javascript?
I just found out that Arrays inherit directly from Object in javascript.  I'm finding the difference between an array and an object is fairly minuscule.

How do i know when to use one over the other?

答:
I'd use an Array [] when I'm dealing with a list of objects the same type* (like a list of strings) that I want the order of and an Object {} when I'm dealing with something that I want properties of (and the properties are of different types, usually).

For example:

```<code>var numberNames = ["one","two","three","four"];

var computer = {
     motherBoard : "mother",
     psu : psu_object(),
     ram : {
             ram1 : GB,
             ram2 : TwoGB
     }
};
</code>```

* This is just my preference. Arrays can contain elements of multiple different types.

Body:
I'd use an Array [] when I'm dealing with a list of objects the same type* (like a list of strings) that I want the order of and an Object {} when I'm dealing with something that I want properties of (and the properties are of different types, usually).

For example:

var numberNames = ["one","two","three","four"];

var computer = {
     motherBoard : "mother",
     psu : psu_object(),
     ram : {
             ram1 : GB,
             ram2 : TwoGB
     }
};

* This is just my preference. Arrays can contain elements of multiple different types.


问:
How to highlight the current line number in `nlinum-mode`
I am writing a minor mode to highlight the current line number when using nlinum-mode (written by @Stefan), and I got everything working except when the cursor is on the first line at the top of the window.

The code for nlinum-mode can be found here:  http://elpa.gnu.org/packages/nlinum.html

Any assistance in figuring out why this doesn't work (i.e., when the cursor is on the first line at the top of the window) would be greatly appreciated.

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; M-x hl-nlinum-mode

(defvar nlinum-highlight-current-line-number-string nil
  "An overlay string used to highlight the current line number.")
(make-variable-buffer-local 'nlinum-highlight-current-line-number-string)

(defvar nlinum-highlight-p nil
  "Set to non-`nil` when overlay is present, and `nil` when not present.")
(make-variable-buffer-local 'nlinum-highlight-p)

(defface ln-active-face
  '((t (:foreground "black" :background "#eab700" :bold nil :italic nil
      :underline nil :box nil :overline nil)))
  "Face for `ln-active-face`."
  :group 'linum)

(defface ln-inactive-face
  '((t (:foreground "SteelBlue" :background "black" :bold t :italic nil
      :underline nil :box nil :overline nil)))
  "Face for `ln-active-face`."
  :group 'linum)

(defun hl-nlinum-remove-overlay ()
  (when nlinum-highlight-p
    (remove-overlays (point-min) (point-max)
      'before-string nlinum-highlight-current-line-number-string)
    (setq nlinum-highlight-p nil)))

(defun nlinum-highlight-current-line-number ()
  (when nlinum-mode
    (hl-nlinum-remove-overlay)
    (let* (
        (pbol (point-at-bol))
        (line (nlinum--line-number-at-pos))
        (line-mod
          (cond
            ((eq nlinum--width 2)
              (cond
                ((< line 10)
                  (concat " " (format "%s" line)))
                (t (format "%s" line))))
            ((eq nlinum--width 3)
              (cond
                ((< line 10)
                  (concat "  " (format "%s" line)))
                ((and
                    (> line 9)
                    (< line 100))
                  (concat " " (format "%s" line)))
                (t (format "%s" line))))
            ((eq nlinum--width 4)
              (cond
                ((< line 10)
                  (concat "   " (format "%s" line)))
                ((and
                    (> line 9)
                    (< line 100))
                  (concat "  " (format "%s" line)))
                ((and
                    (> line 99)
                    (< line 1000))
                  (concat " " (format "%s" line)))
                (t (format "%s" line))))
            (t (format "%s" line))))
        (str (propertize line-mod 'face 'ln-active-face) )
        (final-line-number (propertize " " 'display `((margin left-margin) ,str))))
      (setq nlinum-highlight-current-line-number-string final-line-number)
      (overlay-put (make-overlay pbol pbol)
        'before-string nlinum-highlight-current-line-number-string)
      (setq nlinum-highlight-p t))))

(define-minor-mode hl-nlinum-mode
"A minor-mode for highlighting the current line number when nlinum-mode is active."
  :init-value nil
  :lighter " HL#"
  :keymap nil
  :global nil
  :group 'linum
  (cond
    (hl-nlinum-mode
      (when (not nlinum-mode)
         (nlinum-mode 1))
      (add-hook 'post-command-hook #'nlinum-highlight-current-line-number nil t))
    (t
      (remove-hook 'post-command-hook #'nlinum-highlight-current-line-number t)
      (remove-overlays (point-min) (point-max)
        'before-string nlinum-highlight-current-line-number-string))))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
```

答:
You can enable highlighting the current line number in version 1.7 of nlinum package by setting this in your config:

(setq nlinum-highlight-current-line t)
```


问:
Android In-App Billing invalidKeySpecException wrong tag
I am implementing basic usage of android billing purchase v3 using IabHelper and I am still encountering this issue when I am testing on real device. I run the first time and after successful purchase i consume the product. Now I'am getting the error again and again.

I have already checked my public key (even using different encoding) so i don't think it is the problem. I have consumed all android.test.* products after testing static responses. I also tried to edit the verifyPurchase method in Security.java but it seems the error occurs at this call PublicKey key = Security.generatePublicKey(base64PublicKey);

Has somebody managed to solve definitely the issue?

Here is the log for the error :

```<code>java.lang.IllegalArgumentException: java.security.spec.InvalidKeySpecException: java.lang.RuntimeException: error:0c0890ba:ASN.1 encoding routines:asn1_check_tlen:WRONG_TAG
                                                                          at com.hubsante.nutrition.utils.util.Security.generatePublicKey(Security.java:82)
                                                                          at com.hubsante.nutrition.utils.util.Security.verifyPurchase(Security.java:62)
                                                                          at com.hubsante.nutrition.utils.util.IabHelper.queryPurchases(IabHelper.java:972)
                                                                          at com.hubsante.nutrition.utils.util.IabHelper.queryInventory(IabHelper.java:624)
                                                                          at com.hubsante.nutrition.utils.util.IabHelper$2.run(IabHelper.java:698)
                                                                          at java.lang.Thread.run(Thread.java:818)
</code>```

答: It seems that the format of the public key was incorrect, i corrected it and now it's working.</p>

Body:
I am implementing basic usage of android billing purchase v3 using IabHelper and I am still encountering this issue when I am testing on real device. I run the first time and after successful purchase i consume the product. Now I'am getting the error again and again.

I have already checked my public key (even using different encoding) so i don't think it is the problem. I have consumed all android.test.* products after testing static responses. I also tried to edit the verifyPurchase method in Security.java but it seems the error occurs at this call PublicKey key = Security.generatePublicKey(base64PublicKey);

Has somebody managed to solve definitely the issue?

Here is the log for the error :

java.lang.IllegalArgumentException: java.security.spec.InvalidKeySpecException: java.lang.RuntimeException: error:0c0890ba:ASN.1 encoding routines:asn1_check_tlen:WRONG_TAG
                                                                          at com.hubsante.nutrition.utils.util.Security.generatePublicKey(Security.java:82)
                                                                          at com.hubsante.nutrition.utils.util.Security.verifyPurchase(Security.java:62)
                                                                          at com.hubsante.nutrition.utils.util.IabHelper.queryPurchases(IabHelper.java:972)
                                                                          at com.hubsante.nutrition.utils.util.IabHelper.queryInventory(IabHelper.java:624)
                                                                          at com.hubsante.nutrition.utils.util.IabHelper$2.run(IabHelper.java:698)
                                                                          at java.lang.Thread.run(Thread.java:818)


问:
Change color for default blue location marker
It is possible to set My own colors for a blue location marker and an accuracy circle?

For example, I need to use the orange palett for this.

Thanks!

答:
Use you custom Image for marker

you can use following code to set custom marker

FIRST METHOD:

```<code>int height = 100;
    int width = 80;
    BitmapDrawable bitmapdraw = (BitmapDrawable)
    ContextCompat.getDrawable(this, R.drawable.current_loc_marker);
    Bitmap b = bitmapdraw.getBitmap();
    Bitmap smallMarker = Bitmap.createScaledBitmap(b, width, height, false);
    LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
    MarkerOptions markerOptions = new MarkerOptions();
    markerOptions.position(latLng);
    markerOptions.title("Current Position");
    markerOptions.icon(BitmapDescriptorFactory.fromBitmap(smallMarker));
    mMap.addMarker(markerOptions);
</code>```

SECOND METHOD :

This is how to make a default marker

```<code>Marker melbourne = mMap.addMarker(new MarkerOptions().position(MELBOURNE)
    .icon(BitmapDescriptorFactory
        .defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
</code>```

and these are the constants you can use

float   HUE_AZURE

float   HUE_BLUE

float   HUE_CYAN

float   HUE_GREEN

float   HUE_MAGENTA
float   HUE_ORANGE

float   HUE_RED
float   HUE_ROSE

float   HUE_VIOLET

float   HUE_YELLOW

THIRD METHOD:

```<code>Marker melbourne = mMap.addMarker(new MarkerOptions().position(MELBOURNE)
.icon(getMarkerIcon("#ff2299")));

public BitmapDescriptor getMarkerIcon(String color) {
    float[] hsv = new float[3];
    Color.colorToHSV(Color.parseColor(color), hsv);
        return BitmapDescriptorFactory.defaultMarker(hsv[0]);
}
</code>```

Body:
Use you custom Image for marker

you can use following code to set custom marker

FIRST METHOD:

int height = 100;
    int width = 80;
    BitmapDrawable bitmapdraw = (BitmapDrawable)
    ContextCompat.getDrawable(this, R.drawable.current_loc_marker);
    Bitmap b = bitmapdraw.getBitmap();
    Bitmap smallMarker = Bitmap.createScaledBitmap(b, width, height, false);
    LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
    MarkerOptions markerOptions = new MarkerOptions();
    markerOptions.position(latLng);
    markerOptions.title("Current Position");
    markerOptions.icon(BitmapDescriptorFactory.fromBitmap(smallMarker));
    mMap.addMarker(markerOptions);

SECOND METHOD :

This is how to make a default marker

Marker melbourne = mMap.addMarker(new MarkerOptions().position(MELBOURNE)
    .icon(BitmapDescriptorFactory
        .defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));

and these are the constants you can use

float   HUE_AZURE

float   HUE_BLUE

float   HUE_CYAN

float   HUE_GREEN

float   HUE_MAGENTA
float   HUE_ORANGE

float   HUE_RED
float   HUE_ROSE

float   HUE_VIOLET

float   HUE_YELLOW

THIRD METHOD:

Marker melbourne = mMap.addMarker(new MarkerOptions().position(MELBOURNE)
.icon(getMarkerIcon("#ff2299")));

public BitmapDescriptor getMarkerIcon(String color) {
    float[] hsv = new float[3];
    Color.colorToHSV(Color.parseColor(color), hsv);
        return BitmapDescriptorFactory.defaultMarker(hsv[0]);
}


问:
Indexing arrays with enums in C#
I have a lot of fixed-size collections of numbers where each entry can be accessed with a constant. Naturally this seems to point to arrays and enums:

```<code>enum StatType {
    Foo = 0,
    Bar
    // ...
}

float[] stats = new float[...];
stats[StatType.Foo] = 1.23f;
</code>```

The problem with this is of course that you cannot use an enum to index an array without a cast (though the compiled IL is using plain ints). So you have to write this all over the place:

```<code>stats[(int)StatType.foo] = 1.23f;
</code>```

I have tried to find ways to use the same easy syntax without casting but haven't found a perfect solution yet. Using a dictionary seems to be out of the question since I found it to be around 320 times slower than an array. I also tried to write a generic class for an array with enums as index:

```<code>public sealed class EnumArray<T>
{
    private T[] array;
    public EnumArray(int size)
    {
        array = new T[size];
    }
    // slow!
    public T this[Enum idx]
    {
        get { return array[(int)(object)idx]; }
        set { array[(int)(object)idx] = value; }
    }
}
</code>```

or even a variant with a second generic parameter specifying the enum. This comes quite close to what I want but the problem is that you cannot just cast an unspecific enum (be it from a generic parameter or the boxed type Enum) to int. Instead you have to first box it with a cast to object and then cast it back. This works, but is quite slow. I found that the generated IL for the indexer looks something like this:

```<code>.method public hidebysig specialname instance !T get_Item(!E idx) cil managed
{
    .maxstack 8
    L_0000: ldarg.0
    L_0001: ldfld !0[] EnumArray`2<!T, !E>::array
    L_0006: ldarg.1
    L_0007: box !E
    L_000c: unbox.any int32
    L_0011: ldelem.any !T
    L_0016: ret
}
</code>```

As you can see there are unnecessary box and unbox instructions there. If you strip them from the binary the code works just fine and is just a tad slower than pure array access.

Is there any way to easily overcome this problem? Or maybe even better ways?
I think it would also be possible to tag such indexer methods with a custom attribute and strip those two instructions post-compile. What would be a suitable library for that? Maybe Mono.Cecil?

Of course there's always the possibility to drop enums and use constants like this:

```<code>static class StatType {
    public const int Foo = 0;
    public const int Bar = 1;
    public const int End = 2;
}
</code>```

which may be the fastest way since you can directly access the array.

答:
If your EnumArray wasn't generic, but instead explicitly took a StatType indexer - then you'd be fine. If that's not desirable, then I'd probably use the const approach myself. However, a quick test with passing in a Func<T, E> shows no appreciable difference vs direct access.</p>

```<code> public class EnumArray<T, E> where E:struct {
    private T[] _array;
    private Func<E, int> _convert;

    public EnumArray(int size, Func<E, int> convert) {
        this._array = new T[size];
        this._convert = convert;
    }

    public T this[E index] {
        get { return this._array[this._convert(index)]; }
        set { this._array[this._convert(index)] = value; }
    }
 }
</code>```

Title: Indexing arrays with enums in C#

Body:
I have a lot of fixed-size collections of numbers where each entry can be accessed with a constant. Naturally this seems to point to arrays and enums:

enum StatType {
    Foo = 0,
    Bar
    // ...
}

float[] stats = new float[...];
stats[StatType.Foo] = 1.23f;

The problem with this is of course that you cannot use an enum to index an array without a cast (though the compiled IL is using plain ints). So you have to write this all over the place:

stats[(int)StatType.foo] = 1.23f;

I have tried to find ways to use the same easy syntax without casting but haven't found a perfect solution yet. Using a dictionary seems to be out of the question since I found it to be around 320 times slower than an array. I also tried to write a generic class for an array with enums as index:

public sealed class EnumArray<T>
{
    private T[] array;
    public EnumArray(int size)
    {
        array = new T[size];
    }
    // slow!
    public T this[Enum idx]
    {
        get { return array[(int)(object)idx]; }
        set { array[(int)(object)idx] = value; }
    }
}

or even a variant with a second generic parameter specifying the enum. This comes quite close to what I want but the problem is that you cannot just cast an unspecific enum (be it from a generic parameter or the boxed type Enum) to int. Instead you have to first box it with a cast to object and then cast it back. This works, but is quite slow. I found that the generated IL for the indexer looks something like this:

.method public hidebysig specialname instance !T get_Item(!E idx) cil managed
{
    .maxstack 8
    L_0000: ldarg.0
    L_0001: ldfld !0[] EnumArray`2<!T, !E>::array
    L_0006: ldarg.1
    L_0007: box !E
    L_000c: unbox.any int32
    L_0011: ldelem.any !T
    L_0016: ret
}

As you can see there are unnecessary box and unbox instructions there. If you strip them from the binary the code works just fine and is just a tad slower than pure array access.

Is there any way to easily overcome this problem? Or maybe even better ways?
I think it would also be possible to tag such indexer methods with a custom attribute and strip those two instructions post-compile. What would be a suitable library for that? Maybe Mono.Cecil?

Of course there's always the possibility to drop enums and use constants like this:

static class StatType {
    public const int Foo = 0;
    public const int Bar = 1;
    public const int End = 2;
}

which may be the fastest way since you can directly access the array.

Body:
If your EnumArray wasn't generic, but instead explicitly took a StatType indexer - then you'd be fine. If that's not desirable, then I'd probably use the const approach myself. However, a quick test with passing in a Func<T, E> shows no appreciable difference vs direct access.

 public class EnumArray<T, E> where E:struct {
    private T[] _array;
    private Func<E, int> _convert;

    public EnumArray(int size, Func<E, int> convert) {
        this._array = new T[size];
        this._convert = convert;
    }

    public T this[E index] {
        get { return this._array[this._convert(index)]; }
        set { this._array[this._convert(index)] = value; }
    }
 }

OwnerDisplayName: Mark Brackett


问:
Manage automatic header height with dynamic label width in UITableView
I want to create a UITableView header with dynamic height. I have four labels in the view and the height of the header must be adjusted according to the content in each of the UILabels. I want to achieve something similar to this image. Sample image.

Here the width of the labels would be dynamic according to the screen size. The "type" label would cover around 2/3 of the screen and the rest will be divided equally between the three labels. Here the according to the screen size the labels could be multiline and I want to manage the height of the main view according to the contents of the label.

When I give fixed width constraint to the labels, I am successfully able to manage the height, but I want to keep the width of labels dynamic. This is a UITableView header. Any help would be much appreciated.

答:
Make a customCell just like tableViewCell for header and design like this.

How design is done:

SMS EMAIL and PUSH NOTIFICATION are encapsulated into a stackView and it has been auto layout with TYPE label.

this is the hierarchy.

And this is the layout design for Type(2/3).Calculate accurately by yourself.

This is for stackView.

Both are autolayout with superView(that is cell)

StackView:

and for TYPE label.

Insert this cell as a headerView of your tableView.

How?

in viewDidLoad:

```<code>tableView.register(UINib.init(nibName: String(describing: TableHeader.self), bundle: nil), forCellReuseIdentifier: "headerCell")
</code>```

Add this two function in your respectivew view controller.

```<code>func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let cell = tableView.dequeueReusableCell(withIdentifier: "headerCell") as! TableHeader
    return cell
}

func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return 58
}
</code>```

And here is the output:

For iOS 8:

StackView is absent so we need to use UIView instead.As explaining autolayout is tricky so i just shared my project which is easier to understand.You can checkout from here

The output without using StackView is down below:

2 Views are taken. Color has been given for better understanding.

Body:
Make a customCell just like tableViewCell for header and design like this.

How design is done:

SMS EMAIL and PUSH NOTIFICATION are encapsulated into a stackView and it has been auto layout with TYPE label.

this is the hierarchy.

And this is the layout design for Type(2/3).Calculate accurately by yourself.

This is for stackView.

Both are autolayout with superView(that is cell)

StackView:

and for TYPE label.

Insert this cell as a headerView of your tableView.

How?

in viewDidLoad:

tableView.register(UINib.init(nibName: String(describing: TableHeader.self), bundle: nil), forCellReuseIdentifier: "headerCell")

Add this two function in your respectivew view controller.

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let cell = tableView.dequeueReusableCell(withIdentifier: "headerCell") as! TableHeader
    return cell
}

func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return 58
}

And here is the output:

For iOS 8:

StackView is absent so we need to use UIView instead.As explaining autolayout is tricky so i just shared my project which is easier to understand.You can checkout from here

The output without using StackView is down below:

2 Views are taken. Color has been given for better understanding.


问:
How to Retrieve a Listing of Employee's Superiors in SQL
Essentially, I have a table that lists an employee's number and the employeeNumber of who they report to.

```<code> EmpNum | Name         | ReportsTo
 ---------------------------------
 1234   | John Smith   | 4523
 3245   | Annie Apples | 1234
 1532   | Bob Rogers   | 3245
 6574   | Dong Wong    | 1532
</code>```

Etc. Etc. So Dong Wong's hierarchy would be: He reports to -> 1532 which reports to -> 3245 which reports to -> 1234.

(I'm new to SQL, so clean and understandable solutions would be appreciated)

答:
Try this, cte is best for recursion. SO already has many solutions for such problem </p>

```<code>create table #emp(
EmpNum int,
Name varchar(50),
ReportsTo int
);

insert into  #emp
values
(1234,'John',4523),
(3245,'Annie',1234),
(1532,'Bob',3245),
(6574,'Dong',1532)

with rec as (
    select #emp.ReportsTo, #emp.EmpNum, #emp.Name, 1 as level from #emp where Name = 'Bob'
    union all
    select  #emp.ReportsTo, #emp.EmpNum, #emp.Name, level + 1 as level from #emp
    inner join rec
    on #emp.EmpNum = rec.ReportsTo
)
select ReportsTo, EmpNum, Name, level from rec
where level = (select max(level) from rec)
OPTION (MAXRECURSION 0)
</code>```

Body:
Essentially, I have a table that lists an employee's number and the employeeNumber of who they report to.

 EmpNum | Name         | ReportsTo
 ---------------------------------
 1234   | John Smith   | 4523
 3245   | Annie Apples | 1234
 1532   | Bob Rogers   | 3245
 6574   | Dong Wong    | 1532

Etc. Etc. So Dong Wong's hierarchy would be: He reports to -> 1532 which reports to -> 3245 which reports to -> 1234.

(I'm new to SQL, so clean and understandable solutions would be appreciated)

Body:
Try this, cte is best for recursion. SO already has many solutions for such problem

create table #emp(
EmpNum int,
Name varchar(50),
ReportsTo int
);

insert into  #emp
values
(1234,'John',4523),
(3245,'Annie',1234),
(1532,'Bob',3245),
(6574,'Dong',1532)

with rec as (
    select #emp.ReportsTo, #emp.EmpNum, #emp.Name, 1 as level from #emp where Name = 'Bob'
    union all
    select  #emp.ReportsTo, #emp.EmpNum, #emp.Name, level + 1 as level from #emp
    inner join rec
    on #emp.EmpNum = rec.ReportsTo
)
select ReportsTo, EmpNum, Name, level from rec
where level = (select max(level) from rec)
OPTION (MAXRECURSION 0)


问:
Does Powershell have an automatic log, or do I have to write log functions to my scrips?
I have mainly been writing syntax for statistics software such as SPSS, STATA and SAS, and I am fairly new to coding in PowerShell. I am used to beeing able to scan a log file for finding out what my script does, for example what values are assigned to a variable or which iteration of a loop is running.

But when I run my PowerShell script (using PowerShell ISE), I dont get any message at all unless there is a fatal error in the script. I get no errors, but the script doesn't execute the rigth action, so I know there is an error somewhere. When I  write the code sentence by sentence to the console, I get outputs telling me what goes on, but once I run the enitre script, there is no output to keep track on. Is there a way to view a log from the script, or do I have to implicitly write log functions into the script? From my googling, this seems to be the case, but I would hate to spend hours writing log-code just to find that I could have just openede x folder and find what I was looking for

答:
start-transcript is mainly based on recording screen output (Write-Host) which is often questionable where it concerns variables with unexpected contents. Besides, there are no time stamps and other features you might expect from script logging.

Therefore I have written my own Log-Entry framework.


问:
How to get All the sundays in Array of date ios
i just want an array who contain all the Mondays in the year in the form of NSDate but in swift.
i am using the folowing code in the objective -c but dont know how to user it in swift.</p>

```<code> NSDate *pickerDate = [NSDate date];
    NSLog(@"pickerDate: %@", pickerDate);

    NSDateComponents *dateComponents;
    NSCalendar *calendar = [NSCalendar currentCalendar];

    dateComponents = [calendar components:NSWeekdayCalendarUnit fromDate:pickerDate];
    NSInteger firstMondayOrdinal = 9 - [dateComponents weekday];
    dateComponents = [[NSDateComponents alloc] init];
    [dateComponents setDay:firstMondayOrdinal];
    NSDate *firstMondayDate = [calendar dateByAddingComponents:dateComponents toDate:pickerDate options:0];

    dateComponents = [[NSDateComponents alloc] init];
    [dateComponents setWeek:1];

    for (int i=0; i<64; i++) {
        [dateComponents setWeek:i];
        NSDate *mondayDate = [calendar dateByAddingComponents:dateComponents toDate:firstMondayDate options:0];
        NSLog(@"week#: %i, mondayDate: %@", i, mondayDate);
    }
</code>```

答:
There is an underestimated but very convenient method enumerateDates(startingAfter:matching:matchingPolicy:) of Calendar

```<code>// Create the date component matching the weekday (Sunday = 1)
let mondayComponent = DateComponents(weekday: 2)

// Calculate Jan 1st of the current date
let calendar = Calendar.current
let currentDate = Date()
var startOfYear = currentDate
var interval : TimeInterval = 0.0
_ = calendar.dateInterval(of:.year, start: &startOfYear, interval: &interval, for: currentDate)

// Get the current year as integer
let thisYear = calendar.component(.year, from: startOfYear)

// Create an array for the result
var allMondays = [Date]()

// If Jan 1st is a Monday append it to the array
if calendar.component(.weekday, from: startOfYear) == 2 { allMondays.append(startOfYear) }

// Now enumerate all dates matching the weekday component within this year
// If the year reaches thisYear + 1 the block will be exited.
calendar.enumerateDates(startingAfter: startOfYear, matching: mondayComponent, matchingPolicy: .nextTime) { (date, strict, stop) in
    guard let date = date else { return }
    if calendar.component(.year, from: date) > thisYear {
        stop = true
    } else {
        allMondays.append(date)
    }
}
</code>```

Body:
i just want an array who contain all the Mondays in the year in the form of NSDate but in swift.
i am using the folowing code in the objective -c but dont know how to user it in swift.

 NSDate *pickerDate = [NSDate date];
    NSLog(@"pickerDate: %@", pickerDate);

    NSDateComponents *dateComponents;
    NSCalendar *calendar = [NSCalendar currentCalendar];

    dateComponents = [calendar components:NSWeekdayCalendarUnit fromDate:pickerDate];
    NSInteger firstMondayOrdinal = 9 - [dateComponents weekday];
    dateComponents = [[NSDateComponents alloc] init];
    [dateComponents setDay:firstMondayOrdinal];
    NSDate *firstMondayDate = [calendar dateByAddingComponents:dateComponents toDate:pickerDate options:0];

    dateComponents = [[NSDateComponents alloc] init];
    [dateComponents setWeek:1];

    for (int i=0; i<64; i++) {
        [dateComponents setWeek:i];
        NSDate *mondayDate = [calendar dateByAddingComponents:dateComponents toDate:firstMondayDate options:0];
        NSLog(@"week#: %i, mondayDate: %@", i, mondayDate);
    }

Body:
There is an underestimated but very convenient method enumerateDates(startingAfter:matching:matchingPolicy:) of Calendar

// Create the date component matching the weekday (Sunday = 1)
let mondayComponent = DateComponents(weekday: 2)

// Calculate Jan 1st of the current date
let calendar = Calendar.current
let currentDate = Date()
var startOfYear = currentDate
var interval : TimeInterval = 0.0
_ = calendar.dateInterval(of:.year, start: &startOfYear, interval: &interval, for: currentDate)

// Get the current year as integer
let thisYear = calendar.component(.year, from: startOfYear)

// Create an array for the result
var allMondays = [Date]()

// If Jan 1st is a Monday append it to the array
if calendar.component(.weekday, from: startOfYear) == 2 { allMondays.append(startOfYear) }

// Now enumerate all dates matching the weekday component within this year
// If the year reaches thisYear + 1 the block will be exited.
calendar.enumerateDates(startingAfter: startOfYear, matching: mondayComponent, matchingPolicy: .nextTime) { (date, strict, stop) in
    guard let date = date else { return }
    if calendar.component(.year, from: date) > thisYear {
        stop = true
    } else {
        allMondays.append(date)
    }
}


问:
Append auto-incrementing suffix to duplicated elements of a List
Given the following list :

```<code>val l = List("A", "A", "C", "C", "B", "C")
</code>```

How can I add an auto-incrementing suffix to every elements so that I end up with a list containing no more duplicates, like the following (the ordering doesn't matter) :

```<code>List("A0", "A1", "C0", "C1", "C2", "B0")
</code>```

答:
I found it out by myself just after having written this question

```<code>val l = List("A", "A", "C", "C", "B", "C")
l.groupBy(identity) // Map(A->List(A,A),C->List(C,C,C),B->List(B))
  .values.flatMap(_.zipWithIndex) // List((A,0),(A,1),(C,0),(C,1),(C,2),(B,0))
  .map{ case (str, i) => s"$str$i"}
</code>```

If there is a better solution (using foldLeft maybe) please let me know

Body:
Given the following list :

val l = List("A", "A", "C", "C", "B", "C")

How can I add an auto-incrementing suffix to every elements so that I end up with a list containing no more duplicates, like the following (the ordering doesn't matter) :

List("A0", "A1", "C0", "C1", "C2", "B0")

Body:
I found it out by myself just after having written this question

val l = List("A", "A", "C", "C", "B", "C")
l.groupBy(identity) // Map(A->List(A,A),C->List(C,C,C),B->List(B))
  .values.flatMap(_.zipWithIndex) // List((A,0),(A,1),(C,0),(C,1),(C,2),(B,0))
  .map{ case (str, i) => s"$str$i"}

If there is a better solution (using foldLeft maybe) please let me know


问:
Modifying PostgreSQL View Owner dynamiclly
I need to modify the owner of the view as current logged in user

for eg:

```<code>create view test as select * from test where owner = current_user //like this
</code>```

Can I do it like this?

答:
The owner of the View will be the currently logged in user by default, you only have to modify it if you want the owner to be someone other than the currently logged in user.

To modify the owner you can use

ALTER VIEW [ IF EXISTS ] name OWNER TO { new_owner | CURRENT_USER | SESSION_USER } from https://www.postgresql.org/docs/current/static/sql-alterview.html

If your intention is to apply row level security then you should apply it to the underlying table, not the view, which should restrict the returned rows appropriately to the view.

    CREATE POLICY name ON table_name
    [ FOR { ALL | SELECT | INSERT | UPDATE | DELETE } ]
    [ TO { role_name | PUBLIC | CURRENT_USER | SESSION_USER } [, ...] ]
    [ USING ( using_expression ) ]
    [ WITH CHECK ( check_expression ) ]

https://www.postgresql.org/docs/current/static/sql-createpolicy.html

Body:
I need to modify the owner of the view as current logged in user

for eg:

create view test as select * from test where owner = current_user //like this

Can I do it like this?


问:
Restrict width in ConstraintLayout by another view
Is there a possibility (in ConstraintLayout) to let a view grow only as long as there is space for another view at his right?

The use case is to have a value and unit TextViews besides each other. The value TextView should be able to grow as long as there is space for the unit. If there is not enough space, the value should be cut.

I've tried it with chains and some other things but can't get it done. The value doesn't stop growing and then the unit is not visible anymore. Here's the current code:

```<code><TextView
    android:id="@+id/value"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="8dp"
    android:lines="1"
    app:layout_constraintBaseline_toBaselineOf="@+id/unit"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintHorizontal_chainStyle="packed"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toLeftOf="@id/unit"
    tools:text="12533939532" />

<TextView
    android:id="@+id/unit"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginEnd="8dp"
    android:layout_marginStart="8dp"
    app:layout_constraintHorizontal_chainStyle="packed"
    app:layout_constraintLeft_toRightOf="@id/value"
    app:layout_constraintRight_toRightOf="parent"
    tools:text="km" />
</code>```

答:
yes you can by using match_constraint (0dp) which equal to match_parent for other layout, so by using match_constraint we set weight for first view which will occupies all available space also add

```<code>app:layout_constraintWidth_default="wrap"
</code>```

to apply default width behavior as wrap_content

here is code with change

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto">

        <TextView
            android:id="@+id/value"
            android:layout_width="0dp"
            app:layout_constraintWidth_default="wrap"
            android:layout_height="wrap_content"
            android:layout_marginStart="8dp"
            android:lines="1"
            app:layout_constraintBaseline_toBaselineOf="@+id/unit"
            app:layout_constraintHorizontal_bias="0.0"
            app:layout_constraintHorizontal_chainStyle="packed"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toLeftOf="@id/unit"
            tools:text="12533939532" />

        <TextView
            android:id="@+id/unit"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginEnd="8dp"
            android:layout_marginStart="8dp"
            app:layout_constraintLeft_toRightOf="@id/value"
            app:layout_constraintRight_toRightOf="parent"
            tools:text="km" />

    </android.support.constraint.ConstraintLayout>
</code>```

got some explanation from site

Better view dimension controls

The new available behaviors when a dimension is set to 0dp (MATCH_CONSTRAINT). As before, both endpoints (left/right or top/bottom) need to be connected to targets.

layout_constraintWidth_default = spread (default, similar to the previous behavior)
layout_constraintWidth_default = wrap
layout_constraintHeight_default = spread
layout_constraintHeight_default = wrap

Wrap provides a significant new behaviour, with the widget resizing as if wrap_content was used, but limited by the connected constraints. A widget will thus not grow beyond the endpoints.

http://tools.android.com/recent/constraintlayoutbeta5isnowavailable

Body:
Is there a possibility (in ConstraintLayout) to let a view grow only as long as there is space for another view at his right?

The use case is to have a value and unit TextViews besides each other. The value TextView should be able to grow as long as there is space for the unit. If there is not enough space, the value should be cut.

I've tried it with chains and some other things but can't get it done. The value doesn't stop growing and then the unit is not visible anymore. Here's the current code:

<TextView
    android:id="@+id/value"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="8dp"
    android:lines="1"
    app:layout_constraintBaseline_toBaselineOf="@+id/unit"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintHorizontal_chainStyle="packed"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toLeftOf="@id/unit"
    tools:text="12533939532" />

<TextView
    android:id="@+id/unit"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginEnd="8dp"
    android:layout_marginStart="8dp"
    app:layout_constraintHorizontal_chainStyle="packed"
    app:layout_constraintLeft_toRightOf="@id/value"
    app:layout_constraintRight_toRightOf="parent"
    tools:text="km" />

Body:
yes you can by using match_constraint (0dp) which equal to match_parent for other layout, so by using match_constraint we set weight for first view which will occupies all available space also add

app:layout_constraintWidth_default="wrap"

to apply default width behavior as wrap_content

here is code with change

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto">

        <TextView
            android:id="@+id/value"
            android:layout_width="0dp"
            app:layout_constraintWidth_default="wrap"
            android:layout_height="wrap_content"
            android:layout_marginStart="8dp"
            android:lines="1"
            app:layout_constraintBaseline_toBaselineOf="@+id/unit"
            app:layout_constraintHorizontal_bias="0.0"
            app:layout_constraintHorizontal_chainStyle="packed"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toLeftOf="@id/unit"
            tools:text="12533939532" />

        <TextView
            android:id="@+id/unit"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginEnd="8dp"
            android:layout_marginStart="8dp"
            app:layout_constraintLeft_toRightOf="@id/value"
            app:layout_constraintRight_toRightOf="parent"
            tools:text="km" />

    </android.support.constraint.ConstraintLayout>

got some explanation from site

Better view dimension controls

The new available behaviors when a dimension is set to 0dp (MATCH_CONSTRAINT). As before, both endpoints (left/right or top/bottom) need to be connected to targets.

layout_constraintWidth_default = spread (default, similar to the previous behavior)
layout_constraintWidth_default = wrap
layout_constraintHeight_default = spread
layout_constraintHeight_default = wrap

Wrap provides a significant new behaviour, with the widget resizing as if wrap_content was used, but limited by the connected constraints. A widget will thus not grow beyond the endpoints.

http://tools.android.com/recent/constraintlayoutbeta5isnowavailable


问:
How to set month value based on count
How to get the correct month in javascript. I don't want to use any plugin for this.

var date = new Date();
var month = date.getMonth();
// value is 06 current month;

var month = date.getMonth() + 15;
// now value is 21```
</div>
</div>
</p>

<p>Here, if the getMonth() count more than 12 means how can I get the correct month.
If more than 12 means I need to increase the year also right. </p>

<p>For Example,</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>// assume current month December
var month = date.getMonth()+3;  // value is 14</code>```

I want to show the month as "03" (MARCH). Please help me how can I do this

答:
Do with %12 .it will subtract the month with 12 .Remaining will show on

Note: Remember  month value start from 0 0=January

var date = new Date();
var month = date.getMonth();
console.log('default month value ='+month)
month = (date.getMonth() + 15) % 12;
console.log(month)```

Title: How to set month value based on count

Body:
How to get the correct month in javascript. I don't want to use any plugin for this.

var date = new Date();
var month = date.getMonth();
// value is 06 current month;

var month = date.getMonth() + 15;
// now value is 21

Here, if the getMonth() count more than 12 means how can I get the correct month.
If more than 12 means I need to increase the year also right.

For Example,

// assume current month December
var month = date.getMonth()+3;  // value is 14

I want to show the month as "03" (MARCH). Please help me how can I do this


答:
```<code>lists = [[2, 3, 5],[ 8, 7, 1],[ 0, 4, 6]]
output_list = [item for list in lists for item in list]
</code>```

Title: Python: 2D to 1D list in clockwise direction?

Body:
I am a bit newbie to Python and I am looking for a function that will convert any n x n 2D list to a 1D list in clockwise direction.

For example:

When n = 3

list = [[2, 3, 5],[ 8, 7, 1],[ 0, 4, 6]]

or

list = [[2, 3, 5]
       ,[8, 7, 1]
       ,[0, 4, 6]]

would become

result = [2, 3, 5, 1, 6, 4, 0, 8, 7]

and when n = 5

list = [[2, 3, 5, 9, 10],[ 8, 7, 1, 11, 13],[ 0, 4, 6, 21, 22], [12, 19, 17, 18, 25], [14, 15, 16, 23, 24]]

or

list = [[  2,  3,  5,  9, 10]
       ,[  8,  7,  1, 11, 13]
       ,[  0,  4,  6, 21, 22]
       ,[ 12, 19, 17, 18, 25]
      , [ 14, 15, 16, 23, 24]]

would become

result = [2, 3, 5, 9, 10, 13, 22, 25, 24, 23, 16, 15, 14, 12, 0, 8, 7, 1, 11, 21, 18, 17, 19, 4, 6]

How can I efficiently do that for any value of nxn ??


问:
SQLite: How would you rephrase the query?
I created a basic movie database and for that I'm working with SQLite.

I have a table, which looks like this:

```
CREATE TABLE movie_collection (
    user_id INTEGER NOT NULL,
    movie_id INTEGER NOT NULL,
    PRIMARY KEY (user_id, movie_id),
    FOREIGN KEY (user_id) REFERENCES user (id),
    FOREIGN KEY (movie_id) REFERENCES movie (id)
)
```

As one simple task, I want to show one user (let's say user_id = 1) the whole movie collections, in which the actual user(user_id = 1) might or might not have some movie collection. I also have to prevent the multiple result sets, where more than one user have the same movie record in their collection, especially if this involves the actual user (user_id = 1) then he has the priority, that is if there are let's say 3 records as following:

```
user_id   movie_id
--------  ---------
  1          17
  5          17
  8          17
```

Then the result set must have the record (1, 17) and not other two.

For this task I wrote a sql query like this:

```
SELECT movie_collect.user_id, movie_collect.movie_id
FROM (
    SELECT user_id, movie_id FROM movie_collection WHERE user_id = 1
    UNION
    SELECT user_id, movie_id FROM movie_collection WHERE user_id != 1 AND movie_id NOT IN (SELECT movie_id FROM movie_collection WHERE user_id = 1)
) AS movie_collect
```

Altough this query delivers pretty much that what I need, but just out of curiosity I wanted to ask, if someone else has an another idea to solve this problem.

Thank you.

答:
The outer query is superfluous:

```<code>SELECT user_id, movie_id
FROM movie_collection
WHERE user_id = 1

UNION

SELECT user_id, movie_id
FROM movie_collection
WHERE user_id != 1
  AND movie_id NOT IN (SELECT movie_id
                       FROM movie_collection
                       WHERE user_id = 1)
</code>```

And UNION removes duplicates, so you do not need to check for uid in the second subquery:

```<code>SELECT user_id, movie_id
FROM movie_collection
WHERE user_id = 1

UNION

SELECT user_id, movie_id
FROM movie_collection
WHERE movie_id NOT IN (SELECT movie_id
                       FROM movie_collection
                       WHERE user_id = 1)
</code>```

And the only difference between the two subqueries is the WHERE clause, so you can combine them:

```<code>SELECT user_id, movie_id
FROM movie_collection
WHERE user_id = 1
   OR movie_id NOT IN (SELECT movie_id
                       FROM movie_collection
                       WHERE user_id = 1);
</code>```

Body:
I created a basic movie database and for that I'm working with SQLite.

I have a table, which looks like this:

CREATE TABLE movie_collection (
    user_id INTEGER NOT NULL,
    movie_id INTEGER NOT NULL,
    PRIMARY KEY (user_id, movie_id),
    FOREIGN KEY (user_id) REFERENCES user (id),
    FOREIGN KEY (movie_id) REFERENCES movie (id)
)

As one simple task, I want to show one user (let's say user_id = 1) the whole movie collections, in which the actual user(user_id = 1) might or might not have some movie collection. I also have to prevent the multiple result sets, where more than one user have the same movie record in their collection, especially if this involves the actual user (user_id = 1) then he has the priority, that is if there are let's say 3 records as following:

user_id   movie_id
--------  ---------
  1          17
  5          17
  8          17

Then the result set must have the record (1, 17) and not other two.

For this task I wrote a sql query like this:

SELECT movie_collect.user_id, movie_collect.movie_id
FROM (
    SELECT user_id, movie_id FROM movie_collection WHERE user_id = 1
    UNION
    SELECT user_id, movie_id FROM movie_collection WHERE user_id != 1 AND movie_id NOT IN (SELECT movie_id FROM movie_collection WHERE user_id = 1)
) AS movie_collect

Altough this query delivers pretty much that what I need, but just out of curiosity I wanted to ask, if someone else has an another idea to solve this problem.

Thank you.

Body:
The outer query is superfluous:

SELECT user_id, movie_id
FROM movie_collection
WHERE user_id = 1

UNION

SELECT user_id, movie_id
FROM movie_collection
WHERE user_id != 1
  AND movie_id NOT IN (SELECT movie_id
                       FROM movie_collection
                       WHERE user_id = 1)

And UNION removes duplicates, so you do not need to check for uid in the second subquery:

SELECT user_id, movie_id
FROM movie_collection
WHERE user_id = 1

UNION

SELECT user_id, movie_id
FROM movie_collection
WHERE movie_id NOT IN (SELECT movie_id
                       FROM movie_collection
                       WHERE user_id = 1)

And the only difference between the two subqueries is the WHERE clause, so you can combine them:

SELECT user_id, movie_id
FROM movie_collection
WHERE user_id = 1
   OR movie_id NOT IN (SELECT movie_id
                       FROM movie_collection
                       WHERE user_id = 1);


问:
How can I add ComponentGroupRefs to a feature automatically after generating fragments with heat.exe
I have a requirement to dynamically create an installer using for a list of files contained in a text file.

The file list contains individual files from many different directories, and is prone to change on a fairly regular basis. I am attempting to create an installer that will not need to be updated each time a new version of the file list is created.

So far I am calling heat.exe from the command line inside a cmd script, where I use a for loop to iterate through the file list, running a heat command against each file to create a fragment of the component.

```<code>FOR /F "delims=;"  %%a IN (FileList.txt) DO (heat.exe file "%%a" -cg ComponentGroupName -gg -g1 -sfrag -dr DirectoryName %%~da -out "%~dp0%%~na.wxs")
</code>```

Obviously this bit of code will give each ComponentGroup the same name, which poses an issue, but I can solve that by using the name of the file inside the component group name when I get around to it.

The bit I am struggling with is how to add the name of the component group to a feature element inside my Project.wsx file.

I have read through the  Wix Toolset Documentation Manual and the relevant sections in the book WiX 3.6: A Developer's Guide to Windows Installer XML and cannot find out how to do this.

I appreciate that I could use some form of text replacement to do this, but I was hoping there was something built into the Wix Toolset as I cant be the first person with the need to dynamically create heat generated components.

答:
Ive come up with an acceptable solution to my issue.
What im doing is running a cmd file to generate the heat components. Each of these components is stored in its own componentGroup, identified by the id "ComponentGroup" + the iterative counter of the file in the list of files.

After the heat components have been generated, I then create a further ComponenGroup in a separate wxs file, which contains ComponentGroupRefs to each of the ComponentGroups created by heat.

As this ComponentGroup is created from the cmd file and I know the Id of, I am able to reference it in my feature.

```<code>    @echo off
setlocal enabledelayedexpansion

set /a count = 0
FOR /F "delims=;" %%a IN (FileList.txt) DO (
set /a count=count+1
heat.exe file "%%a" -cg "ComponentGroup!count!" -gg -g1 -sfrag -dr NotSureWhatGoesHereYet %%~da -out "%~dp0%%~na.wxs"
)

(
echo ^<?xml version="1.0" encoding="utf-8"?^>
echo ^<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi"^>
echo      ^<Fragment^>
echo          ^<ComponentGroup Id="ComponentGroup"^>
) > test.wxs

FOR /L %%i IN (1,1,%count%) DO (
  echo              ^<ComponentGroupRef Id="ComponentGroup%%i" /^> >> Components.wxs
)

(
echo          ^</ComponentGroup^>
echo     ^</Fragment^>
echo ^</Wix^>
) >> Components.wxs
</code>```

Thanks for the responses guys. @TomBlodget I took inspiration from your first answer. Thanks for your time

Body:
I have a requirement to dynamically create an installer using for a list of files contained in a text file.

The file list contains individual files from many different directories, and is prone to change on a fairly regular basis. I am attempting to create an installer that will not need to be updated each time a new version of the file list is created.

So far I am calling heat.exe from the command line inside a cmd script, where I use a for loop to iterate through the file list, running a heat command against each file to create a fragment of the component.

FOR /F "delims=;"  %%a IN (FileList.txt) DO (heat.exe file "%%a" -cg ComponentGroupName -gg -g1 -sfrag -dr DirectoryName %%~da -out "%~dp0%%~na.wxs")

Obviously this bit of code will give each ComponentGroup the same name, which poses an issue, but I can solve that by using the name of the file inside the component group name when I get around to it.

The bit I am struggling with is how to add the name of the component group to a feature element inside my Project.wsx file.

I have read through the  Wix Toolset Documentation Manual and the relevant sections in the book WiX 3.6: A Developer's Guide to Windows Installer XML and cannot find out how to do this.

I appreciate that I could use some form of text replacement to do this, but I was hoping there was something built into the Wix Toolset as I cant be the first person with the need to dynamically create heat generated components.

Body:
Ive come up with an acceptable solution to my issue.
What im doing is running a cmd file to generate the heat components. Each of these components is stored in its own componentGroup, identified by the id "ComponentGroup" + the iterative counter of the file in the list of files.

After the heat components have been generated, I then create a further ComponenGroup in a separate wxs file, which contains ComponentGroupRefs to each of the ComponentGroups created by heat.

As this ComponentGroup is created from the cmd file and I know the Id of, I am able to reference it in my feature.

    @echo off
setlocal enabledelayedexpansion

set /a count = 0
FOR /F "delims=;" %%a IN (FileList.txt) DO (
set /a count=count+1
heat.exe file "%%a" -cg "ComponentGroup!count!" -gg -g1 -sfrag -dr NotSureWhatGoesHereYet %%~da -out "%~dp0%%~na.wxs"
)

(
echo ^<?xml version="1.0" encoding="utf-8"?^>
echo ^<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi"^>
echo      ^<Fragment^>
echo          ^<ComponentGroup Id="ComponentGroup"^>
) > test.wxs

FOR /L %%i IN (1,1,%count%) DO (
  echo              ^<ComponentGroupRef Id="ComponentGroup%%i" /^> >> Components.wxs
)

(
echo          ^</ComponentGroup^>
echo     ^</Fragment^>
echo ^</Wix^>
) >> Components.wxs

Thanks for the responses guys. @TomBlodget I took inspiration from your first answer. Thanks for your time


问:
winforms window too large
I think the images say enough...
The grey part of the window overlaps the blue side.

I can fix the problem with the normal window by making it a little bit larger or if I change scaling to DPI. My laptop is set to 125% scaling, I think that is the problem? But how do I fix the messagebox?

I am using Visual studio 2017 15.2 it's an C# Winforms app with .net framework 4.6.2

MessageBox window too large:

Window too large:

答:
This should resolve itself just by adding DpiAware setting to your application.  To do this right click on your project, Add, New Item and then look for Application Manifest File in Visual C# Items.

Once added open this and uncomment the section containing dpiAware (in Windows settings)

HTH

Title: winforms window too large


问:
How to send mail via outlook using spring boot?
My application.properties file contains following configuration :-

```<code>spring.mail.properties.mail.smtp.connecttimeout=5000
  spring.mail.properties.mail.smtp.timeout=3000
  spring.mail.properties.mail.smtp.writetimeout=5000
  spring.mail.host=smtp.office365.com
  spring.mail.password=password
  spring.mail.port=587
  spring.mail.username=test@outlook.com
  spring.mail.properties.mail.smtp.starttls.enable=true
  security.require-ssl=true
  spring.mail.properties.mail.smpt.auth=true
</code>```

Java classes for implemting the mail servers are :

```<code>@Component
public class SmtpMailSender {
@Autowired
private JavaMailSender javaMailSender;

public void sendMail(String to, String subject, String body) throws MessagingException {
    MimeMessage message = javaMailSender.createMimeMessage();
    MimeMessageHelper helper;
    helper = new MimeMessageHelper(message, true);//true indicates multipart message
    helper.setSubject(subject);
    helper.setTo(to);
    helper.setText(body, true);//true indicates body is html
    javaMailSender.send(message);
}
}
</code>```

My controller class is :

```<code>@RestController
public class MailController {

@Autowired
SmtpMailSender smtpMailSender;

@RequestMapping(path = "/api/mail/send")
public void sendMail() throws MessagingException {
    smtpMailSender.sendMail("test123@outlook.com", "testmail", "hello!");
}
}
</code>```

when I send get request (/api/mail/send) following error occurs:

```<code>{
"timestamp": 1496815958863,
"status": 500,
"error": "Internal Server Error",
"exception": "org.springframework.mail.MailAuthenticationException",
"message": "Authentication failed; nested exception is
javax.mail.AuthenticationFailedException: ;\n  nested exception
is:\n\tjavax.mail.MessagingException: Exception reading response;\n  nested
exception is:\n\tjava.net.SocketTimeoutException: Read timed out",
"path": "/api/mail/send"
}
</code>```

Any help would be heartily appreciated.

答:
You must specify the sender using setFrom method to perform authentication on outlook.com:

```<code>@Component
public class SmtpMailSender {

    @Value("${spring.mail.username}")
    private String from;

    @Autowired
    private JavaMailSender javaMailSender;

    public void sendMail(String to, String subject, String body) throws MessagingException {
        MimeMessage message = javaMailSender.createMimeMessage();
        MimeMessageHelper helper;
        helper = new MimeMessageHelper(message, true);//true indicates multipart message

        helper.setFrom(from) // <--- THIS IS IMPORTANT

        helper.setSubject(subject);
        helper.setTo(to);
        helper.setText(body, true);//true indicates body is html
        javaMailSender.send(message);
    }
}
</code>```

outlook.com checks that you're not trying to pretend you're somebody else.

Body:
My application.properties file contains following configuration :-

spring.mail.properties.mail.smtp.connecttimeout=5000
  spring.mail.properties.mail.smtp.timeout=3000
  spring.mail.properties.mail.smtp.writetimeout=5000
  spring.mail.host=smtp.office365.com
  spring.mail.password=password
  spring.mail.port=587
  spring.mail.username=test@outlook.com
  spring.mail.properties.mail.smtp.starttls.enable=true
  security.require-ssl=true
  spring.mail.properties.mail.smpt.auth=true

Java classes for implemting the mail servers are :

@Component
public class SmtpMailSender {
@Autowired
private JavaMailSender javaMailSender;

public void sendMail(String to, String subject, String body) throws MessagingException {
    MimeMessage message = javaMailSender.createMimeMessage();
    MimeMessageHelper helper;
    helper = new MimeMessageHelper(message, true);//true indicates multipart message
    helper.setSubject(subject);
    helper.setTo(to);
    helper.setText(body, true);//true indicates body is html
    javaMailSender.send(message);
}
}

My controller class is :

@RestController
public class MailController {

@Autowired
SmtpMailSender smtpMailSender;

@RequestMapping(path = "/api/mail/send")
public void sendMail() throws MessagingException {
    smtpMailSender.sendMail("test123@outlook.com", "testmail", "hello!");
}
}

when I send get request (/api/mail/send) following error occurs:

{
"timestamp": 1496815958863,
"status": 500,
"error": "Internal Server Error",
"exception": "org.springframework.mail.MailAuthenticationException",
"message": "Authentication failed; nested exception is
javax.mail.AuthenticationFailedException: ;\n  nested exception
is:\n\tjavax.mail.MessagingException: Exception reading response;\n  nested
exception is:\n\tjava.net.SocketTimeoutException: Read timed out",
"path": "/api/mail/send"
}

Any help would be heartily appreciated.

Body:
You must specify the sender using setFrom method to perform authentication on outlook.com:

@Component
public class SmtpMailSender {

    @Value("${spring.mail.username}")
    private String from;

    @Autowired
    private JavaMailSender javaMailSender;

    public void sendMail(String to, String subject, String body) throws MessagingException {
        MimeMessage message = javaMailSender.createMimeMessage();
        MimeMessageHelper helper;
        helper = new MimeMessageHelper(message, true);//true indicates multipart message

        helper.setFrom(from) // <--- THIS IS IMPORTANT

        helper.setSubject(subject);
        helper.setTo(to);
        helper.setText(body, true);//true indicates body is html
        javaMailSender.send(message);
    }
}

outlook.com checks that you're not trying to pretend you're somebody else.