问:
R-processing on a UTF-8 encoded Japanese corpus
I am trying to process a UTF8 encoded file in Japanese.

I did the preprocessing in python, everything went OK (tokenization/collocations/stopwords) and I obtained the following kind of string:

```<code>リカーショップ 寄っ たら サントリー 山崎 響が 入荷_し て た
</code>```

However, when I am trying to read the preprocessed file (a UTF-8 encoded csv) in R to run a  STM, I am getting this format :

```<code><U+30AB><U+30F4><U+30A1> <U+4E00><U+676F> <U+767D> <U+8D64> <U+4E00><U+676F> <U+89D2>_<U+30CF><U+30A4><U+30DC><U+30FC><U+30EB> <U+5C71><U+5D0E> <U+30CF><U+30A4><U+30DC><U+30FC><U+30EB> <U+591A><U+304B><U+3063> <U+305F> <U+304B>
</code>```

I first tried different import functions but with the same result :

```<code>df <- read.xlsx2(corpus_filename,sheetIndex=1,header=TRUE)
df <-read_csv(corpus_filename,locale = locale(encoding = "UTF-8"))
</code>```

I then thought I could run the stm and go back to python to re-encode the resulting files but after half a day of trying the encode/decode functions, I have to admit that I am completely stuck.

Can anyone help me with this ?
Thanks a lot.

EDIT:
Here are the first 20 lines of the csv output of my python preprocessing (encoded in utf8) => it is the file I'm giving to my R program

```<code>865781289361604609;コークハイ 山崎 年 酔っ払い なう
856448528331161600;リカーショップ 寄っ たら サントリー 山崎 響が 入荷_し て た
815926577556897792;おと なしく 山崎 んどき ます w まあ 竹鶴 結局 手 にいれ まし_た しよし ます w
769384649143361536;再 来週 山崎_蒸留 所 行く アド しか_ない
860119818296414208;非売 品 山崎 仕込_み 水 水割り 最高 です_ね
759768684457975809;ゴースト 観 た 面白 かっ_た ラスト 個人_的 驚い た 最高 だろ_う こういう 時期っ て 絶対 ある よね ラスト 切り 口 俺 好き 山崎 ハイボール うまし
807576715203444736;山崎 ロック う まいわぁ
833936664938500098;ある お店 飲み_放題 ウイスキー 以前 山崎 白州 ブラックニッカ 角 変わっ てる 大人 事情っ て やつ か
744757755177664512;父 日 サントリー 山崎 プレゼント しよ_う として 円 しか なかっ_た 竹鶴 あげ た
744850084580384768;今度 山崎 か 響買 おう
742576211759628288;i サントリー 山崎_蒸溜 所 島本_町 大阪府
862666125909278720;山崎 年 だねー 杯 ご_馳走 する_よ
865932271169159172;山崎 年 神々しい
788394825494175745;山崎 年 よき て
833282834412376064;山崎_蒸留 所見 学ツアー 千円 部 大阪 ダメダメ 団 向け テイスティング
823471399289253888;おと とい 山崎 年 ごち そう なっ たん_だけ どめっっっちゃ 美味_しく て 家 帰っ_て 調べ たら 定価 でも く らい する 知っ て ヒェッ て なっ た いつも 穏やか な 愛する あまり 相手 薬漬け 快楽 漬け て 全裸 首輪 つけ て 自室 監禁 て 泣き ながら 犯す 攻め 見 た 時 よう
775381740160299008;次買う ウイスキー 山崎 しよ_う とり_あえ ず 山崎 美味い だ
862137645895262209;山崎 シェリーカスク 一 回 飲ん_でみ たいけど 値段 ぶっ 飛ん て ヤヴァイ 年 万く らい とか な
741984119035334660;山崎 ハイボール なう
768400284754190337;久々_に 自覚 する くらい 酔っ ぱらっちゃっ た ぬ 山崎 ボトル 一本 飲ませ て 頂い た よ あり たい ね
839372940374237184;ウイスキー ある_けど 家 やつ 美味_しく ない ー 山崎 響き 好き
744138456025042944;山崎 ロック 飲み_ながら 妹ちょ 見る
779968612224217089;無駄 いい ホテル 笑知っ てる と_思う けど 山崎 響飲ん だ 翌日 体臭 おじ_さん なる ね 気 をつけ て
822126367584043008;山崎 でも いい ウイスキー 蒸留_所行 き たい
753358847352246272;山崎 年 のうえ 年
</code>```

I work under Windows 7 directly on a Rconsole by copy/pasting lines from SublimeText.

EDIT 2 :

I tried Mark's suggestion :

```<code>> rm(list=ls(all=TRUE))
> library(readr)
> parselmouth.windows <-
+   read_delim(
+     parselmouth.csv,
+     ";",
+     escape_double = FALSE,
+     col_names = FALSE,
+     trim_ws = TRUE
+   )
Parsed with column specification:
cols(
  X1 = col_double(),
  X2 = col_character()
)
> names(parselmouth.windows) <- c('document', 'content')
> parselmouth.windows$document <- as.character(parselmouth.windows$document)
>
> print.listof(head(parselmouth.windows))
document :
[1] "865781289361604608" "856448528331161600" "815926577556897792"
[4] "769384649143361536" "860119818296414208" "759768684457975808"

content :
[1] "<U+30B3><U+30FC><U+30AF><U+30CF><U+30A4> <U+5C71><U+5D0E> <U+5E74> <U+9154>
<U+3063><U+6255><U+3044> <U+306A><U+3046>"
[2] "<U+30EA><U+30AB><U+30FC><U+30B7><U+30E7><U+30C3><U+30D7> <U+5BC4><U+3063> <
U+305F><U+3089> <U+30B5><U+30F3><U+30C8><U+30EA><U+30FC> <U+5C71><U+5D0E> <U+97F
F><U+304C> <U+5165><U+8377>_<U+3057> <U+3066> <U+305F>"
[3] "<U+304A><U+3068> <U+306A><U+3057><U+304F> <U+5C71><U+5D0E> <U+3093><U+3069>
<U+304D> <U+307E><U+3059> w <U+307E><U+3042> <U+7AF9><U+9DB4> <U+7D50><U+5C40> <
U+624B> <U+306B><U+3044><U+308C> <U+307E><U+3057>_<U+305F> <U+3057><U+3088><U+30
57> <U+307E><U+3059> w"
[4] "<U+518D> <U+6765><U+9031> <U+5C71><U+5D0E>_<U+84B8><U+7559> <U+6240> <U+884
C><U+304F> <U+30A2><U+30C9> <U+3057><U+304B>_<U+306A><U+3044>"
[5] "<U+975E><U+58F2> <U+54C1> <U+5C71><U+5D0E> <U+4ED5><U+8FBC>_<U+307F> <U+6C3
4> <U+6C34><U+5272><U+308A> <U+6700><U+9AD8> <U+3067><U+3059>_<U+306D>"
[6] "<U+30B4><U+30FC><U+30B9><U+30C8> <U+89B3> <U+305F> <U+9762><U+767D> <U+304B
><U+3063>_<U+305F> <U+30E9><U+30B9><U+30C8> <U+500B><U+4EBA>_<U+7684> <U+9A5A><U
+3044> <U+305F> <U+6700><U+9AD8> <U+3060><U+308D>_<U+3046> <U+3053><U+3046><U+30
44><U+3046> <U+6642><U+671F><U+3063> <U+3066> <U+7D76><U+5BFE> <U+3042><U+308B>
<U+3088><U+306D> <U+30E9><U+30B9><U+30C8> <U+5207><U+308A> <U+53E3> <U+4FFA> <U+
597D><U+304D> <U+5C71><U+5D0E> <U+30CF><U+30A4><U+30DC><U+30FC><U+30EB> <U+3046>
<U+307E><U+3057>"
</code>```

答:
Right, I suspected you were using Windows.  In Linux (Ubuntu 16.04.2, RStudio 0.99.879, R 3.3.2), reading and printing just works.

```<code>parselmouth.ubuntu <-
  read.csv('parselmouth.csv', header = FALSE, sep = ";")

> head(parselmouth.ubuntu)
            V1
1 8.657813e+17
2 8.564485e+17
3 8.159266e+17
4 7.693846e+17
5 8.601198e+17
6 7.597687e+17
                                                                                V2
1                                                                                コークハイ 山崎 年 酔っ払い なう
2                                                                                リカーショップ 寄っ たら サントリー 山崎 響が 入荷_し て た
3                                                                   おと なしく 山崎 んどき ます w まあ 竹鶴 結局 手 にいれ まし_た しよし ます w
4                                                                                再 来週 山崎_蒸留 所 行く アド しか_ない
5                                                                                非売 品 山崎 仕込_み 水 水割り 最高 です_ね
6 ゴースト 観 た 面白 かっ_た ラスト 個人_的 驚い た 最高 だろ_う こういう 時期っ て 絶対 ある よね ラスト 切り 口 俺 好き 山崎 ハイボール うまし
>
</code>```

I think you'll find that internally, R for Windows does "know" the correct encoding of your data.  It's just not being printed in a way we would expect or hope for.

I recommend reading http://people.fas.harvard.edu/~izahn/posts/reading-data-with-non-native-encoding-in-r/

Try saving your example data as parselmouth.csv, installing the readr library, and then running

```<code>library(readr)
parselmouth.windows <-
  read_delim(
    "parselmouth.csv",
    ";",
    escape_double = FALSE,
    col_names = FALSE,
    trim_ws = TRUE
  )

names(parselmouth.windows) <- c('document', 'content')
parselmouth.windows$document <- as.character(parselmouth.windows$document)

print.listof(head(parselmouth.windows))
</code>```

And you will see:

```<code>document :
[1] "865781289361604608" "856448528331161600" "815926577556897792"
[4] "769384649143361536" "860119818296414208" "759768684457975808"

content :
[1] "コークハイ 山崎 年 酔っ払い なう"
[2] "リカーショップ 寄っ たら サントリー 山崎 響が 入荷_し て た"
[3] "おと なしく 山崎 んどき ます w まあ 竹鶴 結局 手 にいれ まし_た しよし ます w"
[4] "再 来週 山崎_蒸留 所 行く アド しか_ない"
[5] "非売 品 山崎 仕込_み 水 水割り 最高 です_ね"
[6] "ゴースト 観 た 面白 かっ_た ラスト 個人_的 驚い た 最高 だろ_う こういう 時期っ て 絶対 ある よね ラスト 切り 口 俺 好き 山崎 ハイボール うまし"
</code>```

If there's still no joy, it may be helpful to determine or set the current locale.  In my Windows example, I'm using the default windows codepage:

```<code>Sys.getlocale(category = "LC_ALL")
[1] "LC_COLLATE=English_United States.1252;LC_CTYPE=English_United States.1252;LC_MONETARY=English_United States.1252;LC_NUMERIC=C;LC_TIME=English_United States.1252"
</code>```

But I could change it

```<code>Sys.setlocale(category = "LC_ALL", locale = "English_United States.932")
[1] "LC_COLLATE=English_United States.932;LC_CTYPE=English_United States.932;LC_MONETARY=English_United States.932;LC_NUMERIC=C;LC_TIME=English_United States.932"
</code>```

You could also use a hex editor to verify that your input is the same as mine:

Body:
I am trying to process a UTF8 encoded file in Japanese.

I did the preprocessing in python, everything went OK (tokenization/collocations/stopwords) and I obtained the following kind of string:

リカーショップ 寄っ たら サントリー 山崎 響が 入荷_し て た

However, when I am trying to read the preprocessed file (a UTF-8 encoded csv) in R to run a  STM, I am getting this format :

     _

I first tried different import functions but with the same result :

df <- read.xlsx2(corpus_filename,sheetIndex=1,header=TRUE)
df <-read_csv(corpus_filename,locale = locale(encoding = "UTF-8"))

I then thought I could run the stm and go back to python to re-encode the resulting files but after half a day of trying the encode/decode functions, I have to admit that I am completely stuck.

Can anyone help me with this ?
Thanks a lot.

EDIT:
Here are the first 20 lines of the csv output of my python preprocessing (encoded in utf8) => it is the file I'm giving to my R program

865781289361604609;コークハイ 山崎 年 酔っ払い なう
856448528331161600;リカーショップ 寄っ たら サントリー 山崎 響が 入荷_し て た
815926577556897792;おと なしく 山崎 んどき ます w まあ 竹鶴 結局 手 にいれ まし_た しよし ます w
769384649143361536;再 来週 山崎_蒸留 所 行く アド しか_ない
860119818296414208;非売 品 山崎 仕込_み 水 水割り 最高 です_ね
759768684457975809;ゴースト 観 た 面白 かっ_た ラスト 個人_的 驚い た 最高 だろ_う こういう 時期っ て 絶対 ある よね ラスト 切り 口 俺 好き 山崎 ハイボール うまし
807576715203444736;山崎 ロック う まいわぁ
833936664938500098;ある お店 飲み_放題 ウイスキー 以前 山崎 白州 ブラックニッカ 角 変わっ てる 大人 事情っ て やつ か
744757755177664512;父 日 サントリー 山崎 プレゼント しよ_う として 円 しか なかっ_た 竹鶴 あげ た
744850084580384768;今度 山崎 か 響買 おう
742576211759628288;i サントリー 山崎_蒸溜 所 島本_町 大阪府
862666125909278720;山崎 年 だねー 杯 ご_馳走 する_よ
865932271169159172;山崎 年 神々しい
788394825494175745;山崎 年 よき て
833282834412376064;山崎_蒸留 所見 学ツアー 千円 部 大阪 ダメダメ 団 向け テイスティング
823471399289253888;おと とい 山崎 年 ごち そう なっ たん_だけ どめっっっちゃ 美味_しく て 家 帰っ_て 調べ たら 定価 でも く らい する 知っ て ヒェッ て なっ た いつも 穏やか な 愛する あまり 相手 薬漬け 快楽 漬け て 全裸 首輪 つけ て 自室 監禁 て 泣き ながら 犯す 攻め 見 た 時 よう
775381740160299008;次買う ウイスキー 山崎 しよ_う とり_あえ ず 山崎 美味い だ
862137645895262209;山崎 シェリーカスク 一 回 飲ん_でみ たいけど 値段 ぶっ 飛ん て ヤヴァイ 年 万く らい とか な
741984119035334660;山崎 ハイボール なう
768400284754190337;久々_に 自覚 する くらい 酔っ ぱらっちゃっ た ぬ 山崎 ボトル 一本 飲ませ て 頂い た よ あり たい ね
839372940374237184;ウイスキー ある_けど 家 やつ 美味_しく ない ー 山崎 響き 好き
744138456025042944;山崎 ロック 飲み_ながら 妹ちょ 見る
779968612224217089;無駄 いい ホテル 笑知っ てる と_思う けど 山崎 響飲ん だ 翌日 体臭 おじ_さん なる ね 気 をつけ て
822126367584043008;山崎 でも いい ウイスキー 蒸留_所行 き たい
753358847352246272;山崎 年 のうえ 年

I work under Windows 7 directly on a Rconsole by copy/pasting lines from SublimeText.

EDIT 2 :

I tried Mark's suggestion :

> rm(list=ls(all=TRUE))
> library(readr)
> parselmouth.windows <-
+   read_delim(
+     parselmouth.csv,
+     ";",
+     escape_double = FALSE,
+     col_names = FALSE,
+     trim_ws = TRUE
+   )
Parsed with column specification:
cols(
  X1 = col_double(),
  X2 = col_character()
)
> names(parselmouth.windows) <- c('document', 'content')
> parselmouth.windows$document <- as.character(parselmouth.windows$document)
>
> print.listof(head(parselmouth.windows))
document :
[1] "865781289361604608" "856448528331161600" "815926577556897792"
[4] "769384649143361536" "860119818296414208" "759768684457975808"

content :
[1] "
 "
[2] "      _  "
[3] "
  w      _   w"
[4] "  _    _"
[5] "   _    _"
[6] "    _  _    _

"

Body:
Right, I suspected you were using Windows.  In Linux (Ubuntu 16.04.2, RStudio 0.99.879, R 3.3.2), reading and printing just works.

parselmouth.ubuntu <-
  read.csv('parselmouth.csv', header = FALSE, sep = ";")

> head(parselmouth.ubuntu)
            V1
1 8.657813e+17
2 8.564485e+17
3 8.159266e+17
4 7.693846e+17
5 8.601198e+17
6 7.597687e+17
                                                                                V2
1                                                                                コークハイ 山崎 年 酔っ払い なう
2                                                                                リカーショップ 寄っ たら サントリー 山崎 響が 入荷_し て た
3                                                                   おと なしく 山崎 んどき ます w まあ 竹鶴 結局 手 にいれ まし_た しよし ます w
4                                                                                再 来週 山崎_蒸留 所 行く アド しか_ない
5                                                                                非売 品 山崎 仕込_み 水 水割り 最高 です_ね
6 ゴースト 観 た 面白 かっ_た ラスト 個人_的 驚い た 最高 だろ_う こういう 時期っ て 絶対 ある よね ラスト 切り 口 俺 好き 山崎 ハイボール うまし
>

I think you'll find that internally, R for Windows does "know" the correct encoding of your data.  It's just not being printed in a way we would expect or hope for.

I recommend reading http://people.fas.harvard.edu/~izahn/posts/reading-data-with-non-native-encoding-in-r/

Try saving your example data as parselmouth.csv, installing the readr library, and then running

library(readr)
parselmouth.windows <-
  read_delim(
    "parselmouth.csv",
    ";",
    escape_double = FALSE,
    col_names = FALSE,
    trim_ws = TRUE
  )

names(parselmouth.windows) <- c('document', 'content')
parselmouth.windows$document <- as.character(parselmouth.windows$document)

print.listof(head(parselmouth.windows))

And you will see:

document :
[1] "865781289361604608" "856448528331161600" "815926577556897792"
[4] "769384649143361536" "860119818296414208" "759768684457975808"

content :
[1] "コークハイ 山崎 年 酔っ払い なう"
[2] "リカーショップ 寄っ たら サントリー 山崎 響が 入荷_し て た"
[3] "おと なしく 山崎 んどき ます w まあ 竹鶴 結局 手 にいれ まし_た しよし ます w"
[4] "再 来週 山崎_蒸留 所 行く アド しか_ない"
[5] "非売 品 山崎 仕込_み 水 水割り 最高 です_ね"
[6] "ゴースト 観 た 面白 かっ_た ラスト 個人_的 驚い た 最高 だろ_う こういう 時期っ て 絶対 ある よね ラスト 切り 口 俺 好き 山崎 ハイボール うまし"

If there's still no joy, it may be helpful to determine or set the current locale.  In my Windows example, I'm using the default windows codepage:

Sys.getlocale(category = "LC_ALL")
[1] "LC_COLLATE=English_United States.1252;LC_CTYPE=English_United States.1252;LC_MONETARY=English_United States.1252;LC_NUMERIC=C;LC_TIME=English_United States.1252"

But I could change it

Sys.setlocale(category = "LC_ALL", locale = "English_United States.932")
[1] "LC_COLLATE=English_United States.932;LC_CTYPE=English_United States.932;LC_MONETARY=English_United States.932;LC_NUMERIC=C;LC_TIME=English_United States.932"

You could also use a hex editor to verify that your input is the same as mine:


来源: stackexchange

问:
Using context parameter with django-simple-menu
I want to make a menu in my django app that is changing depending on the page that is being viewed. I'm trying to use Django-simple-menu for this.
I'm struggeling to get the URL parameters to be accesible in my menus.py.
This is the code I have so far and want to replace the 'company' string with a parameter coming from my URL parameters. Is this possible or is it better to create a menu in my views and assign it to the context?  </p>

```<code>hier = Hierachy.get_root_nodes().filter(company__slug= 'company')
for site in hier:
children = list()
for plant in site.get_children():
    children.append(MenuItem(plant.name,
             reverse('pha:companyHierarchy', args=[plant.company.slug, plant.slug,]),
             weight=10,
             icon="user"))
Menu.add_item("study", MenuItem(site.name, reverse('pha:companyHierarchy', args=[site.company.slug, site.slug,]),
                                       weight=10,
                                       icon="tools",
                                       children=children))
</code>```

答:
After some messing around I found the following solution in writing some middleware.

```<code>class SimpleMiddleware(object):

    def process_view(self, request, func, args, kwargs):
        Menu.items.clear()
        hier = Hierachy.get_root_nodes().filter(company__slug= kwargs['slug'])
        for site in hier:
            children = list()
            for plant in site.get_children():
                children.append(MenuItem(plant.name,
                 reverse('pha:companyHierarchy', args=[plant.company.slug, plant.slug,]),
                 weight=10,
                 icon="user"))
            Menu.add_item("study", MenuItem(site.name, reverse('pha:companyHierarchy', args=[site.company.slug, site.slug,]),
                                           weight=10,
                                           icon="tools",
                                           children=children))

    return None
</code>```

This is the code for the template
menu.html

```<code>                    {% if menus.study %}
                    <li class="dropdown">
                        <a href="javascript:void(0);" class="dropdown-toggle" data-toggle="dropdown">
                            Studies
                        </a>

                    <ul class="dropdown-menu">
                    {% for nodeMenu in menus.study %}
                        {% if nodeMenu.children %}
                            <li class="dropdown-submenu">
                                <a href="{{nodeMenu.url}}">{{nodeMenu.title}}</a>
                                <!-- Get plants and studies -->

                                <ul class="dropdown-menu">
                                    {% for child in nodeMenu.children %}
                                    <li><a href="{{child.url}}">{{child.title}}</a></li>
                                    {% endfor %}
                                </ul>
                            </li>

                        {% else %}
                            <li class="">
                                <a href="{{nodeMenu.url}}">{{nodeMenu.title}}</a>

                            </li>
                        {% endif %}
                    {% endfor %}
                    </ul>

                    </li>
                    {% endif %}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to make a menu in my django app that is changing depending on the page that is being viewed. I'm trying to use Django-simple-menu for this.
I'm struggeling to get the URL parameters to be accesible in my menus.py.
This is the code I have so far and want to replace the 'company' string with a parameter coming from my URL parameters. Is this possible or is it better to create a menu in my views and assign it to the context?

hier = Hierachy.get_root_nodes().filter(company__slug= 'company')
for site in hier:
children = list()
for plant in site.get_children():
    children.append(MenuItem(plant.name,
             reverse('pha:companyHierarchy', args=[plant.company.slug, plant.slug,]),
             weight=10,
             icon="user"))
Menu.add_item("study", MenuItem(site.name, reverse('pha:companyHierarchy', args=[site.company.slug, site.slug,]),
                                       weight=10,
                                       icon="tools",
                                       children=children))

Body:
After some messing around I found the following solution in writing some middleware.

class SimpleMiddleware(object):

    def process_view(self, request, func, args, kwargs):
        Menu.items.clear()
        hier = Hierachy.get_root_nodes().filter(company__slug= kwargs['slug'])
        for site in hier:
            children = list()
            for plant in site.get_children():
                children.append(MenuItem(plant.name,
                 reverse('pha:companyHierarchy', args=[plant.company.slug, plant.slug,]),
                 weight=10,
                 icon="user"))
            Menu.add_item("study", MenuItem(site.name, reverse('pha:companyHierarchy', args=[site.company.slug, site.slug,]),
                                           weight=10,
                                           icon="tools",
                                           children=children))

    return None

This is the code for the template
menu.html

                    {% if menus.study %}
                    <li class="dropdown">
                        <a href="javascript:void(0);" class="dropdown-toggle" data-toggle="dropdown">
                            Studies
                        </a>

                    <ul class="dropdown-menu">
                    {% for nodeMenu in menus.study %}
                        {% if nodeMenu.children %}
                            <li class="dropdown-submenu">
                                <a href="{{nodeMenu.url}}">{{nodeMenu.title}}</a>
                                <!-- Get plants and studies -->

                                <ul class="dropdown-menu">
                                    {% for child in nodeMenu.children %}
                                    <li><a href="{{child.url}}">{{child.title}}</a></li>
                                    {% endfor %}
                                </ul>
                            </li>

                        {% else %}
                            <li class="">
                                <a href="{{nodeMenu.url}}">{{nodeMenu.title}}</a>

                            </li>
                        {% endif %}
                    {% endfor %}
                    </ul>

                    </li>
                    {% endif %}

ContentLicense: CC BY-SA 4.0


问:
ssh run script in background and get its pid

Hi

I need to get the pid of the script run through ssh.
```

ssh some.host './script &' #get the pid of it

```

Some code I was trying so far:
```

ssh some.host './script & ; echo $!'

```
```

nohup ssh some.host '( ./script  & ); echo $! > thePID'; ssh some.host 'cat thePID'

```

Any sugestion?

答:
```<code>ssh some.host './script & echo $!'
</code>```

Body:
Hi

I need to get the pid of the script run through ssh.

ssh some.host './script &' #get the pid of it

Some code I was trying so far:

ssh some.host './script & ; echo $!'

nohup ssh some.host '( ./script  & ); echo $! > thePID'; ssh some.host 'cat thePID'

Any sugestion?

Body: ssh some.host './script & echo $!'


问:
How can I drop the first level from a multi level column by chaining?
How can I drop the first level from a multi level column?

For a data frame:

```<code>tmp.head(1000).groupby(['user_id', 'aisle_id']).agg({'aisle_id': ['count']})
</code>```

giving

```<code>                 aisle_id
                    count
user_id aisle_id
382     38              1
        84              2
        115             1
3107    43              1
3321    37              1
        69              2
</code>```

I want to drop the aisle_id in my columns. How can I do this by chaining commands without having to start another statement?

答:
Use reset_index at level 0 with drop set to True.

```<code>tmp.head(1000).groupby(['user_id', 'aisle_id']) \
    .agg({'aisle_id': ['count']}).T.reset_index(level=0, drop=True).T
</code>```

Body:
How can I drop the first level from a multi level column?

For a data frame:

tmp.head(1000).groupby(['user_id', 'aisle_id']).agg({'aisle_id': ['count']})

giving

                 aisle_id
                    count
user_id aisle_id
382     38              1
        84              2
        115             1
3107    43              1
3321    37              1
        69              2

I want to drop the aisle_id in my columns. How can I do this by chaining commands without having to start another statement?

Body:
Use reset_index at level 0 with drop set to True.

tmp.head(1000).groupby(['user_id', 'aisle_id']) \
    .agg({'aisle_id': ['count']}).T.reset_index(level=0, drop=True).T


问:
error trying to set up basic chat app with node.js
I am trying to set up a basic chat app with node.js/express/socket.io but for some reason when the client sends message (this works, another client will get the message) it also refreshes the client and the url goes from localhost:3000 to localhost:3000/? (adds /? to end, i don't know what this means). I cant find anything wrong in my code after looking at it for hours. I have:

server.js:

```<code>let app = require('express')();
let http = require('http').Server(app);
let io = require('socket.io')(http);
let port = process.env.PORT || 3000;

app.get('/', (req, res) => { res.sendFile(__dirname + '/index.html') });

http.listen(port,() => { console.log('listening on *:' + port) });

    io.on('connection', socket => {
        socket.on('chat', text => {
        io.sockets.emit('chat', `<p>${text}</p>`);
    });

});
</code>```

index.html:

```<code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="/socket.io/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<style>
    .chat_view{
        height: 300px;
        width: 200px;
        border: 5px ridge black;
        overflow-y: scroll;
    }
</style>
</head>
<body>
<div class="chat" id="chat">
    <div class="chat_view" id="chat_view">
    </div>
    <form id="chat_form">
        <input type="text" title="chat_input" id="chat_input" style="width: 206px">
    </form>
</div>
<script>
let socket = io();

$('#chat_form').submit( () => {
    let text = $('#chat_input').val();
    socket.emit('chat', text);
});

socket.on('chat', text => {
    let chat_view = document.getElementById('chat_view');
        chat_view.innerHTML += text;
        chat_view.scrollTop = chat_view.scrollHeight;
});

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

and package.json:

```<code>{
  "name": "RatScrew",
  "version": "0.0.1",
  "dependencies": {
    "express": "^4.15.3",
    "socket.io": "^2.0.2"
  }
}
</code>```

答: If you're listening to the submit event, that means the form will actually try and POST to the server (which will in your case refresh the screen).  If you're using JavaScript to communicate with the server and don't need the form data to get posted by the browser directly, just return false from your callback. Some browsers also want you to call e.preventDefault() as well.  </p>

Body:
I am trying to set up a basic chat app with node.js/express/socket.io but for some reason when the client sends message (this works, another client will get the message) it also refreshes the client and the url goes from localhost:3000 to localhost:3000/? (adds /? to end, i don't know what this means). I cant find anything wrong in my code after looking at it for hours. I have:

server.js:

let app = require('express')();
let http = require('http').Server(app);
let io = require('socket.io')(http);
let port = process.env.PORT || 3000;

app.get('/', (req, res) => { res.sendFile(__dirname + '/index.html') });

http.listen(port,() => { console.log('listening on *:' + port) });

    io.on('connection', socket => {
        socket.on('chat', text => {
        io.sockets.emit('chat', `<p>${text}</p>`);
    });

});

index.html:

<!DOCTYPE html>

<meta charset="UTF-8">

    <form id="chat_form">
        <input type="text" title="chat_input" id="chat_input" style="width: 206px">
    </form>

and package.json:

{
  "name": "RatScrew",
  "version": "0.0.1",
  "dependencies": {
    "express": "^4.15.3",
    "socket.io": "^2.0.2"
  }
}


答:
Change your groupby statement.</p>

```<code>tmp.head(1000).groupby(['user_id', 'aisle_id'])['aisle_id'].agg(['count'])
</code>```

Title: How can I drop the first level from a multi level column by chaining?

Body:
Change your groupby statement.

tmp.head(1000).groupby(['user_id', 'aisle_id'])['aisle_id'].agg(['count'])


问:
Algorithm to determine quality of an article
I am working on a project that requires me to parse news articles and determine the best among them. I figured out that to determine the quality of an article, I would need three main parameters: Length of an article, facebook shares/ retweets and the time since the article was posted.

The problem I am facing now is how do I put together all three parameters in a mathematical function and come-up with a score for each of the articles? The score assigned to each one of them would help me rank the articles and show it to the users.

Also let me know if there is any other parameter that I need to consider in determining the quality.

答:
What you desire is stunning easy to achieve. You have to kinds of data, that your are interested in: increasing and decreasing data. Increasing data is considered as "good", well, as long as it increases. Decreasing data is considered as "better" the nearer it is to zero.

It turns out that all of the four datasets are simple integers:

increasing data

shares: positive integer s \in N_0 (every integer from zero to infinity)

retweets: positive integer r \in N_0

decreasing data

For decreasing data you want to use the absolute value as a metric:

Let t_0 be the timestamp (unix or so) of the article.

Let T be the current timestamp.

Let l_0 denote the length of an article considered as "best".

Let L denote the actual length of the article.

Then:

time: |t_0 - T| the better the nearer to zero

length: |l_0 - L| the better the nearer to zero

since the absolute value are positive integers it follows:

|l_0 - L| + |t_0 - T| is nearer to zero as |t_0 - T| and |l_0 - L| are nearer to zero.

The same is true for the increasing numbers.

So, the more likely an article is to be of the "correct" length and new, the nearer this number is to zero.

conclusion

the quotient of an increasing number over a decreasing is itself increasing. Think about it: the smaller the denominator the bigger the quotient. The bigger the numerator the bigger the quotient.

That means: If considered as "better" the quotient

(s+r) / (|l_0 - L| + |t_0 - T|)

rises.

This is not necessarily an integer anymore.

Enhancement

You can soften the rise of shares and retweets, so the score becomes little more "natural" by using ln.

ln(s+r) / (|l_0 - L| + |t_0 - T|)

You could use expto soften the denominator:

ln(s+r) / exp(-(|l_0 - L| + |t_0 - T|))


问:
How to make ASP.Net Core Web API Identity return a 401 on unauthorized
I'm trying to get ASP.net core web api JSON Web Token authentication working properly. I've got to the point where I have successfully integrated IdentityServer4 with the app, and it is successfully processing logins based on ASP.net Core Identity.

However, whenever authentication fails, the API returns a 302 result trying to redirect the client to a login page. However, this is a pure Web API, there is no user pages, or anything that a user is supposed to directly interact with.

How can I get the system to return a 401 rather than trying to redirect to a login page?

The identity part of ConfigureServices looks like this:

```<code>       // ASP.net Identity
        var identityBackingStoreConnectionString = configuration["identity:backingStore"];

        services
            .AddIdentityWithMongoStoresUsingCustomTypes<MyApplicationUser, IdentityRole>(
                identityBackingStoreConnectionString)
            .AddDefaultTokenProviders();

        services.AddSingleton<IClientStore, MyIdentityStore>();

        // IdentityServer4
        services.AddIdentityServer().AddTemporarySigningCredential()
            .AddInMemoryApiResources(MyResourceStore.GetAllResources())
            .AddAspNetIdentity<MyApplicationUser>()
            .AddTemporarySigningCredential();
</code>```

and the relevant (I think) part of Configure looks like this:

```<code>        app.UseIdentity();

        app.UseIdentityServer();
        app.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions()
        {
            Authority = "http://localhost:5000/",
            RequireHttpsMetadata = false,
            ApiName = "myapi",
            AutomaticAuthenticate = true,
            JwtBearerEvents = new JwtBearerEvents()
            {
                OnAuthenticationFailed = async context => context.Response.StatusCode = 401
            }
        });

        app.UseMvc();
</code>```

As you can see, I've tried overriding the OnAuthenticationFailed event, but to no avail.

Any suggestions as to how to get the system returning a 401 would be very much appreciated.

答:
Identity server uses cookie authentication internally which converts 401 into 302.

I don't think you can make app.UseIdentityServer() and   app.UseIdentityServerAuthentication() live together because of it.

However you can easily find a workaround.

The best is to host identity server in separate application (e.g. identity server at localhost:5000 and application at localhost:5001). It fits better the concept of open id connect and you can enjoy tons of examples at official GitHub

Alternatively you can try placing Identity server and API at different subpaths like localhost:5000/idsrv and localhost:5000/api using app.UseWhen. For example

```<code>app.UseWhen(
    c => c.Request.Path.StartsWithSegments(new PathString("/api")),
    branch => {
       branch.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions()
       {
           Authority = "http://localhost:5000/idsrv",
           RequireHttpsMetadata = false,
           ApiName = "myapi",
           AutomaticAuthenticate = true,
       } );
       branch.UseMvc();
   });

app.UseWhen(
    c => c.Request.Path.StartsWithSegments(new PathString("/idsrv")),
    branch => {
       branch.UseIdentityServer();
       branch.UseMvc();
    } );
</code>```

Again, this approach is more error-prone and I would rather consider separate applications.

Body:
I'm trying to get ASP.net core web api JSON Web Token authentication working properly. I've got to the point where I have successfully integrated IdentityServer4 with the app, and it is successfully processing logins based on ASP.net Core Identity.

However, whenever authentication fails, the API returns a 302 result trying to redirect the client to a login page. However, this is a pure Web API, there is no user pages, or anything that a user is supposed to directly interact with.

How can I get the system to return a 401 rather than trying to redirect to a login page?

The identity part of ConfigureServices looks like this:

       // ASP.net Identity
        var identityBackingStoreConnectionString = configuration["identity:backingStore"];

        services
            .AddIdentityWithMongoStoresUsingCustomTypes<MyApplicationUser, IdentityRole>(
                identityBackingStoreConnectionString)
            .AddDefaultTokenProviders();

        services.AddSingleton<IClientStore, MyIdentityStore>();

        // IdentityServer4
        services.AddIdentityServer().AddTemporarySigningCredential()
            .AddInMemoryApiResources(MyResourceStore.GetAllResources())
            .AddAspNetIdentity<MyApplicationUser>()
            .AddTemporarySigningCredential();

and the relevant (I think) part of Configure looks like this:

        app.UseIdentity();

        app.UseIdentityServer();
        app.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions()
        {
            Authority = "http://localhost:5000/",
            RequireHttpsMetadata = false,
            ApiName = "myapi",
            AutomaticAuthenticate = true,
            JwtBearerEvents = new JwtBearerEvents()
            {
                OnAuthenticationFailed = async context => context.Response.StatusCode = 401
            }
        });

        app.UseMvc();

As you can see, I've tried overriding the OnAuthenticationFailed event, but to no avail.

Any suggestions as to how to get the system returning a 401 would be very much appreciated.

Body:
Identity server uses cookie authentication internally which converts 401 into 302.

I don't think you can make app.UseIdentityServer() and   app.UseIdentityServerAuthentication() live together because of it.

However you can easily find a workaround.

The best is to host identity server in separate application (e.g. identity server at localhost:5000 and application at localhost:5001). It fits better the concept of open id connect and you can enjoy tons of examples at official GitHub

Alternatively you can try placing Identity server and API at different subpaths like localhost:5000/idsrv and localhost:5000/api using app.UseWhen. For example

app.UseWhen(
    c => c.Request.Path.StartsWithSegments(new PathString("/api")),
    branch => {
       branch.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions()
       {
           Authority = "http://localhost:5000/idsrv",
           RequireHttpsMetadata = false,
           ApiName = "myapi",
           AutomaticAuthenticate = true,
       } );
       branch.UseMvc();
   });

app.UseWhen(
    c => c.Request.Path.StartsWithSegments(new PathString("/idsrv")),
    branch => {
       branch.UseIdentityServer();
       branch.UseMvc();
    } );

Again, this approach is more error-prone and I would rather consider separate applications.


问:
Having issues using proper syntax for multidimensional arrays in PHP?
There are a multitude of similar questions like this one -- I've read nearly all of them on Stack and haven't been able to wrap my head around it.

I'm decoding a json file using CURL. The URL I'm retrieving contents from is https://api.mojang.com/user/profiles/e6e37a93864f496383ba362df30f4792/names.

After I convert the array to a PHP array correctly, I'm attempting to return the last item in the PHP array.

I've attempted to use array_pop but I couldn't get it to work. I resorted to counting the total rows in the array, and referencing that last row using the count.

```<code>    $data = json_decode($output);

    $count = count($data);

    return $data[$count]['name'];`
</code>```

I've even attempted to do

```<code>    return $data[$count]['name']->name; // OR...

    return $data[$count]->name;
</code>```

This is because

```<code>    return $data[0]->name;
</code>```

returns "Eli_Silveraxe", a value from the array, but not the last value. None of these options have worked for me, and it's only become more frustrating because I can return Eli_Silveraxe, but not "Malfunction", which is what SHOULD be returning.

Can you please help?

答:
The last item in the array has index of count - 1, therefore you need this:

```<code>$data = json_decode($output);
$count = count($data);
return $data[$count - 1]->name;
</code>```

Note that you don't need to pass the second parameter to the json_decode (or pass false) to get objects in your $data.  Alternatively, pass true and use associative array syntax:

```<code>$data = json_decode($output, true);
$count = count($data);
return $data[$count - 1]['name'];
</code>```

Body:
There are a multitude of similar questions like this one -- I've read nearly all of them on Stack and haven't been able to wrap my head around it.

I'm decoding a json file using CURL. The URL I'm retrieving contents from is https://api.mojang.com/user/profiles/e6e37a93864f496383ba362df30f4792/names.

After I convert the array to a PHP array correctly, I'm attempting to return the last item in the PHP array.

I've attempted to use array_pop but I couldn't get it to work. I resorted to counting the total rows in the array, and referencing that last row using the count.

    $data = json_decode($output);

    $count = count($data);

    return $data[$count]['name'];`

I've even attempted to do

    return $data[$count]['name']->name; // OR...

    return $data[$count]->name;

This is because

    return $data[0]->name;

returns "Eli_Silveraxe", a value from the array, but not the last value. None of these options have worked for me, and it's only become more frustrating because I can return Eli_Silveraxe, but not "Malfunction", which is what SHOULD be returning.

Can you please help?

Body:
The last item in the array has index of count - 1, therefore you need this:

$data = json_decode($output);
$count = count($data);
return $data[$count - 1]->name;

Note that you don't need to pass the second parameter to the json_decode (or pass false) to get objects in your $data.  Alternatively, pass true and use associative array syntax:

$data = json_decode($output, true);
$count = count($data);
return $data[$count - 1]['name'];


问:
Launch Pycharm from command line (terminal)
I want to try out PyCharm for sage mathematics development.  Normally I run eclipse to do sage development, but now I want to try it with PyCharm.

To launch eclipse with sage environment variables, in command line I normally do the following:

```<code>sage -sh
cd /path/to/eclipse
./eclipse
</code>```

The first line loads the sage environment variables, the remainder launches eclipse.  How can I do the same thing for pyCharm?  (note I am using a Mac and Ubuntu for sage development; the commands above are agnostic to both OSes)

Link 1 is close to the solution I am looking for, however I cannot find a pyCharm.sh anywhere.

Link 2: Jetbrains does not give clear instructions either.

答:
The included utility that installs to /usr/local/bin/charm did not work for me on OS X, so I hacked together this utility instead. It actually works!

```<code>#!/usr/bin/env bash

if [ -z "$1" ]
then
  echo ""
  echo "Usage: charm <filename>"
  exit
fi
FILENAME=$1

function myreadlink() {
  (
  cd $(dirname $1)         # or  cd ${1%/*}
  echo $PWD/$(basename $1) # or  echo $PWD/${1##*/}
  )
}

FULL_FILE=`myreadlink $FILENAME`;

/Applications/PyCharm\ CE.app/Contents/MacOS/pycharm $FULL_FILE
</code>```

Body:
I want to try out PyCharm for sage mathematics development.  Normally I run eclipse to do sage development, but now I want to try it with PyCharm.

To launch eclipse with sage environment variables, in command line I normally do the following:

sage -sh
cd /path/to/eclipse
./eclipse

The first line loads the sage environment variables, the remainder launches eclipse.  How can I do the same thing for pyCharm?  (note I am using a Mac and Ubuntu for sage development; the commands above are agnostic to both OSes)

Link 1 is close to the solution I am looking for, however I cannot find a pyCharm.sh anywhere.

Link 2: Jetbrains does not give clear instructions either.

Body:
The included utility that installs to /usr/local/bin/charm did not work for me on OS X, so I hacked together this utility instead. It actually works!

#!/usr/bin/env bash

if [ -z "$1" ]
then
  echo ""
  echo "Usage: charm <filename>"
  exit
fi
FILENAME=$1

function myreadlink() {
  (
  cd $(dirname $1)         # or  cd ${1%/*}
  echo $PWD/$(basename $1) # or  echo $PWD/${1##*/}
  )
}

FULL_FILE=`myreadlink $FILENAME`;

/Applications/PyCharm\ CE.app/Contents/MacOS/pycharm $FULL_FILE


问:
How do you put a restriction on a variable?
I am trying to make an add and remove button that has an input that has a text type and it show numbers. The add and remove button work and it will show positive numbers and negative also. I don't want it to show negative numbers. How do I make it so it can't go lower than 0? Also I do not want the input to have a number type.

Here is my code:

```<code><button onclick="add();">ADD</button>
<button onclick="remove();">REMOVE</button>
<input type="text" id="inc">

<script>
var i = 0;
    function add() {
        if(i >= 0) {
            i++;
            document.getElementById('inc').value = i;
        } else {
            i = 0;
            document.getElementById('inc').value = i;
        }

    }
        function remove() {
        i--;
        document.getElementById('inc').value = i;
    }
        </script>
</code>```

答:
Apart from the answers already suggested, you can also use Math.max() to ensure the value never goes below 0.

Replace i-- with i = Math.max(i - 1, 0)

Body:
I am trying to make an add and remove button that has an input that has a text type and it show numbers. The add and remove button work and it will show positive numbers and negative also. I don't want it to show negative numbers. How do I make it so it can't go lower than 0? Also I do not want the input to have a number type.

Here is my code:

<button onclick="add();">ADD</button>
<button onclick="remove();">REMOVE</button>
<input type="text" id="inc">


问:
How to configure MongoDB and nodejs to use two different servers
I want to do the following structure for a website.

The idea is put web app on one server, and put MongoDB on another server. They are different machines.

In nodejs code, the only configuration for db is the following code:

```<code>var connectString = 'mongodb://localhost/myDataBase';
</code>```

Replace 'localhost' with '111.222.111.2', the ip address of the machine where MongoDB is running on, then it should work. Is this correct?

Will this make data retrieval slower comparing with putting the on one physical machine?

How the two machines communicate with each other to get the data? Through what protocol?

答:
You can have NodeJS at one server and MongoDB database at another server. You can test it with mlab.com Mongo Database http://docs.mlab.com/ (free for 500MB).
The easiest way to connect with that DB is to use mongoose:

```<code>const mongoose = require('mongoose');
mongoose.connect("mongodb://<login>:<password>@ds140361.mlab.com:45242/mydb");
</code>```

The database is protected with login and password. However, API of nodeJS should be protected independently.

IMO if one server isn't at the one side of the planet and second on the other side, you shouldn't see the differences in speed of the connection.

About protocol:

https://docs.mongodb.com/manual/reference/mongodb-wire-protocol/

Body:
I want to do the following structure for a website.

The idea is put web app on one server, and put MongoDB on another server. They are different machines.

In nodejs code, the only configuration for db is the following code:

var connectString = 'mongodb://localhost/myDataBase';

Replace 'localhost' with '111.222.111.2', the ip address of the machine where MongoDB is running on, then it should work. Is this correct?

Will this make data retrieval slower comparing with putting the on one physical machine?

How the two machines communicate with each other to get the data? Through what protocol?

Body:
You can have NodeJS at one server and MongoDB database at another server. You can test it with mlab.com Mongo Database http://docs.mlab.com/ (free for 500MB).
The easiest way to connect with that DB is to use mongoose:

const mongoose = require('mongoose');
mongoose.connect("mongodb://<login>:<password>@ds140361.mlab.com:45242/mydb");

The database is protected with login and password. However, API of nodeJS should be protected independently.

IMO if one server isn't at the one side of the planet and second on the other side, you shouldn't see the differences in speed of the connection.

About protocol:

https://docs.mongodb.com/manual/reference/mongodb-wire-protocol/


问:
read Json data in android studio
I am building an app in android studio that uses JSON to acess to my postgresql where is my data and I am receiving the data this way:

```<code>[
{"id":"1","title":"12 May to 30 Jun"},
{"id":"2","title":"3 Jun to 20 Jun"}
]
</code>```

I tried to find every where how to use JSONObject or JSONArray for "unlock" the data for pass it to other variables

答:
After sometime trying and trying I found a way to

```<code>                            String finalJson = buffer.toString();

            try {
                JSONArray parentArray = new JSONArray(finalJson);

                int count = 0;
                int[] id = new int[parentArray.length()];
                String[] title = new String[parentArray.length()];
                StringBuffer finalBufferedData = new StringBuffer();
                while (count < parentArray.length())
                {

                    JSONObject finalObject = parentArray.getJSONObject(count);
                    id[count] = finalObject.getInt("id");
                    title[count] = finalObject.getString("title");
                    finalBufferedData.append(id[count] + " - " + title[count] + "\n");
                    count++;

                }
                return finalBufferedData.toString();

            } catch (JSONException e) {
                e.printStackTrace();
            }
</code>```

this way I was able to get the 2 rows from postgresql and show it (later will add it the app sqlite so it doesn't require always to check in my postgresql)

Title: read Json data in android studio

Body:
I am building an app in android studio that uses JSON to acess to my postgresql where is my data and I am receiving the data this way:

[
{"id":"1","title":"12 May to 30 Jun"},
{"id":"2","title":"3 Jun to 20 Jun"}
]

I tried to find every where how to use JSONObject or JSONArray for "unlock" the data for pass it to other variables

Body:
After sometime trying and trying I found a way to

                            String finalJson = buffer.toString();

            try {
                JSONArray parentArray = new JSONArray(finalJson);

                int count = 0;
                int[] id = new int[parentArray.length()];
                String[] title = new String[parentArray.length()];
                StringBuffer finalBufferedData = new StringBuffer();
                while (count < parentArray.length())
                {

                    JSONObject finalObject = parentArray.getJSONObject(count);
                    id[count] = finalObject.getInt("id");
                    title[count] = finalObject.getString("title");
                    finalBufferedData.append(id[count] + " - " + title[count] + "\n");
                    count++;

                }
                return finalBufferedData.toString();

            } catch (JSONException e) {
                e.printStackTrace();
            }

this way I was able to get the 2 rows from postgresql and show it (later will add it the app sqlite so it doesn't require always to check in my postgresql)


问:
Knockout JS - list items without the parent
 element
I have a simple demo application with a foreach binding of "li" elements inside an "ul" element.

```<code><ul data-bind="foreach: sortedItems">
    <li>
        <div>
            <span data-bind="text: name">

        </div>

    </li>
</ul>
</code>```

Is there a way to create the same binding without a parent element?

答:
Yes, you can use knockout's virtual element syntax for this purpose. See the first example on this page.</p>

```<code><!-- ko foreach: sortedItems -->
    <li> ... </li>
<!-- /ko -->
</code>```

Title: Knockout JS - list items without the parent <ul> element

Body:
I have a simple demo application with a foreach binding of "li" elements inside an "ul" element.

Is there a way to create the same binding without a parent element?

Body:
Yes, you can use knockout's virtual element syntax for this purpose. See the first example on this page.

<!-- ko foreach: sortedItems -->
    <li> ... </li>
<!-- /ko -->


问:
Insert row in table for each id in another table
I tried searching here for a similar solution but didn't see one so I was wondering what is the best way to accomplish the following.

I have a table with 17 million + rows all have a unique ID.  We have recently created a new table that will be used in conjunction with the previous table where the foreign key of the new table is the unique id of the old table.

For ex.

Table 1 - id, field1, field2, field3...
table 2 - table1.id, field1 ...

The problem is since we are migrating this into a live environment, we need to back fill table 2 with a row containing the id from table 1 for each row in table 1.
ex, table 1 - 1, test, null
table 2 now needs to have: 1, null, ...  and so on for each row that is in table1.  The main issue is that the ids are not all sequential in table 1 so we will have to read from table 1 and then insert based of the id of found into table 2.

Is there any easier way to go about this?

Also to clarify, table 2 will be new data and the only thing that it will contain from table 1 is the id to keep the foreign key relationship

Also this is sql server 2000

答:
If I understand correctly, you want one record in table2 for each record in table1.
Also I believe that apart from the reference to table1, table2 should initially contain blank rows.

So assuming

```<code>table1 (ID, field1, field2, ...)
table2 (ID, table1_ID, fieldA, fieldB,...)
-- where table1_ID is a reference to ID of table1
</code>```

After creating table2 you can simply run this insert statement

```<code>insert into table2(table1_ID)
select ID from table1
</code>```

Body:
If I understand correctly, you want one record in table2 for each record in table1.
Also I believe that apart from the reference to table1, table2 should initially contain blank rows.

So assuming

table1 (ID, field1, field2, ...)
table2 (ID, table1_ID, fieldA, fieldB,...)
-- where table1_ID is a reference to ID of table1

After creating table2 you can simply run this insert statement

insert into table2(table1_ID)
select ID from table1

OwnerDisplayName: kristof

ContentLicense: CC BY-SA 2.5


问:
Why did Asp.net MVC team choose "../../Content/Site.css" rather than "~/Content/Site.css" in Site.Master page?
```<code><link href="../../Content/Site.css" rel="stylesheet" type="text/css" />
</code>```

The above code shows an external css inclusion tag declared in  Site.Master template.

My question: why did the Asp.net MVC team choose that way rather than using "~/Content/Site.css" ?

Is it the best practice? I am sorry, I am a newbie and still learning to improve my skill.

EDIT 1: I want to make it clearer that "~/" must be passed in to url-resolving method first. Thus, I can rewrite my question as follows:

Why did the team choose "../.." rather than "~/" resolved by url resolver?

答: Refer to what @Pauli Østerø said. But, since you asked for a best practice, here it is .. get rid of those hardcoded strings. Use T4MVC for those paths</p>

Body:
<link href="../../Content/Site.css" rel="stylesheet" type="text/css" />

The above code shows an external css inclusion tag declared in  Site.Master template.

My question: why did the Asp.net MVC team choose that way rather than using "~/Content/Site.css" ?

Is it the best practice? I am sorry, I am a newbie and still learning to improve my skill.

EDIT 1: I want to make it clearer that "~/" must be passed in to url-resolving method first. Thus, I can rewrite my question as follows:

Why did the team choose "../.." rather than "~/" resolved by url resolver?


问:
Wordpress replace args in function within a plugin
I am trying to modify the arguments of a function that is called in a plugin.
The original code within the plugin

```<code>orplugin_load_template( 'templatefile.php', array(
        'post_type' => $post_type,
        'userdata' => wp_get_current_user(),
        'dashboard_query' => $dashboard_query,
        'post_type_obj' => $post_type_obj,
        'post' => $post,
        'pagenum' => $pagenum
    ) );
</code>```

My try out version that I placed in functions.php in my child theme

```<code>function my_orplugin_load_template( 'mytemplatefile.php', array(
        'post_type' => $post_type,
        'userdata' => wp_get_current_user(),
        'dashboard_query' => $dashboard_query,
        'post_type_obj' => $post_type_obj,
        'post' => $post,
        'pagenum' => $pagenum
    ) );
</code>```

add_filter('orplugin_load_template','my_orplugin_load_template', 10);

I created my own templatefile.php called mytemplatefile.php. I don't knwo where to store this file outside the plugin. And how to call it to replace it in the original plugin. I want to load mytemplatefile.php in place of templatefile.php. How to achieve this?

答:
Good point. You sent me the right direction. I found out that WP has a standard function for plugins :

```<code><?php load_template( $_template_file, $require_once ) ?>
</code>```

[https://codex.wordpress.org/Function_Reference/load_template] .  And indeed the plugin has a subfolder templates in which the template.php file is stored.I tried then following code to use my adapted template.php file but got some error messages

```<code>if ( $overridden_template = locate_template( 'some-template.php' ) ) {
// locate_template() returns path to file
// if either the child theme or the parent theme have overridden the template
load_template( $overridden_template );
 } else {
   // If neither the child nor parent theme have overridden the template,
// we load the template from the 'templates' sub-directory of the directory this file is in
   load_template( dirname( __FILE__ ) . '/templates/some-template.php' );
}
</code>```

Any suggestions?

Body:
I am trying to modify the arguments of a function that is called in a plugin.
The original code within the plugin

orplugin_load_template( 'templatefile.php', array(
        'post_type' => $post_type,
        'userdata' => wp_get_current_user(),
        'dashboard_query' => $dashboard_query,
        'post_type_obj' => $post_type_obj,
        'post' => $post,
        'pagenum' => $pagenum
    ) );

My try out version that I placed in functions.php in my child theme

function my_orplugin_load_template( 'mytemplatefile.php', array(
        'post_type' => $post_type,
        'userdata' => wp_get_current_user(),
        'dashboard_query' => $dashboard_query,
        'post_type_obj' => $post_type_obj,
        'post' => $post,
        'pagenum' => $pagenum
    ) );

add_filter('orplugin_load_template','my_orplugin_load_template', 10);

I created my own templatefile.php called mytemplatefile.php. I don't knwo where to store this file outside the plugin. And how to call it to replace it in the original plugin. I want to load mytemplatefile.php in place of templatefile.php. How to achieve this?

Body:
Good point. You sent me the right direction. I found out that WP has a standard function for plugins :

<?php load_template( $_template_file, $require_once ) ?>

[https://codex.wordpress.org/Function_Reference/load_template] .  And indeed the plugin has a subfolder templates in which the template.php file is stored.I tried then following code to use my adapted template.php file but got some error messages

if ( $overridden_template = locate_template( 'some-template.php' ) ) {
// locate_template() returns path to file
// if either the child theme or the parent theme have overridden the template
load_template( $overridden_template );
 } else {
   // If neither the child nor parent theme have overridden the template,
// we load the template from the 'templates' sub-directory of the directory this file is in
   load_template( dirname( __FILE__ ) . '/templates/some-template.php' );
}

Any suggestions?


问:
JSON data access
I have a JSON file that looks like this (see below), my question is how would I go about accessing the Salary and also the jobTitle? I have no issues accessing the first and last name within my loop by using data[i].first etc.. but when I do the same for salary the console tells me that its not defined.

```<code>[
{
  "name":{
     "first":"Lola",
     "last":"Ewing"
  },
  "salary":"47586.03",
  "jobTitle":"Database Analyst"
},
{
  "name":{
     "first":"Durham",
     "last":"Sharpe"
  },
  "salary":"67658.3",
  "jobTitle":"Database Analyst"
},
{
  "name":{
     "first":"Hines",
     "last":"Moore"
  },
  "salary":"39317.83",
  "jobTitle":"Web Developer"
},
{
  "name":{
     "first":"Fitzgerald",
     "last":"Rivers"
  },
  "salary":"70657.89",
  "jobTitle":"Software Developer"
}
]
</code>```

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

    var url = "example.json";

    $.ajax({
        type: "GET",
        dataType: 'json',
        cache: false,
        url: url,
        success: function (data) {

        $.each(data, function (i, data) {
            for (i in data) {

                $("#database-analyst-area .first").append(data[i].first);
            }
        });
        }
    });
});
</code>```

答:
data[i] here is key of your object, they are : name, salary, jobTitle, so salary is data[1]. I reccommend to you do next loop after success:</p>

```<code>data.forEach(function(human) {
  // and here is human.name.first
  // human.salary
}
</code>```

Title: JSON data access

Body:
I have a JSON file that looks like this (see below), my question is how would I go about accessing the Salary and also the jobTitle? I have no issues accessing the first and last name within my loop by using data[i].first etc.. but when I do the same for salary the console tells me that its not defined.

[
{
  "name":{
     "first":"Lola",
     "last":"Ewing"
  },
  "salary":"47586.03",
  "jobTitle":"Database Analyst"
},
{
  "name":{
     "first":"Durham",
     "last":"Sharpe"
  },
  "salary":"67658.3",
  "jobTitle":"Database Analyst"
},
{
  "name":{
     "first":"Hines",
     "last":"Moore"
  },
  "salary":"39317.83",
  "jobTitle":"Web Developer"
},
{
  "name":{
     "first":"Fitzgerald",
     "last":"Rivers"
  },
  "salary":"70657.89",
  "jobTitle":"Software Developer"
}
]

$("document").ready(function(){

    var url = "example.json";

    $.ajax({
        type: "GET",
        dataType: 'json',
        cache: false,
        url: url,
        success: function (data) {

        $.each(data, function (i, data) {
            for (i in data) {

                $("#database-analyst-area .first").append(data[i].first);
            }
        });
        }
    });
});

Body:
data[i] here is key of your object, they are : name, salary, jobTitle, so salary is data[1]. I reccommend to you do next loop after success:

data.forEach(function(human) {
  // and here is human.name.first
  // human.salary
}


问:
Remove specific object from array in swift 3

I have a problem trying to remove a specific object from an array in Swift 3. I want to remove item from an array as in the screenshot but I don't know the solution.

If you have any solutions please share with me.

答:
I used the solutions provided here: Remove Specific Array Element, Equal to String - Swift Ask Question

this is one of the solutions there (in case the object was a string):

```<code>myArrayOfStrings = ["Hello","Playground","World"]
myArrayOfStrings = myArrayOfStrings.filter{$0 != "Hello"}
print(myArrayOfStrings)   // "[Playground, World]"
</code>```

Body:
I used the solutions provided here: Remove Specific Array Element, Equal to String - Swift Ask Question

this is one of the solutions there (in case the object was a string):

myArrayOfStrings = ["Hello","Playground","World"]
myArrayOfStrings = myArrayOfStrings.filter{$0 != "Hello"}
print(myArrayOfStrings)   // "[Playground, World]"


问:
How to save a sentence in a text file in c++?
This is what I have, this program runs ok as it stands, the only problem I am having is that it will not save the approriate sentence in File3.txt. I included the entire program for understanding, what is it that I am not doing correctly that is preventing the sentence under the case option 'r' to not save? Thanks.</p>

```<code>void ascii (int number);
bool raffle (int number);
const int cArray=5;

int main ()
{

    int value;

    char option;

while (1)
{

    cout <<"Enter a positive integer number: " <<endl;
    cin >>value;
    cout <<endl;

    cout <<"A[scii]" "\t\tR[affle]" "\t\tE[xit]" <<endl;
    cout <<"Please select an option: " <<endl;
    cin >>option;
    cout<<endl;

    switch (option)
    {
        case 'a':
        case 'A':

            ascii(value);
            break;

        case 'r':
        case 'R':
            ofstream outfile("G:/File3.txt", ios::out);
            if(!outfile)
            {
                cout<<"File could not be opened"<<endl;
                exit(1);
            }
            if (raffle(value)==1)
            {
                outfile<<"The number "<<value<<"is present in the array."<<endl;
            }
            else
            {
                outfile<<"The number "<<value<<"is not present in the array."<<endl;
            }
            outfile.close();
            break;

        case 'e':
        case 'E':

            return 0;
            break;

    }
}
}

void ascii (int value)
{

    if (48 <= value && value <= 57)
    {
        cout <<"The number you have entered corresponds to a digit in the ASCII table." <<endl;
    }
    else if(65 <= value && value <= 90)
    {
        cout <<"The number you have entered corresponds to an uppercase letter in the ASCII table." <<endl;
    }
    else if (97 <= value && value <= 122)
    {
        cout <<"The number you have entered corresponds to a lowercase letter in the ASCII table." <<endl;
    }
    else
    {
        cout <<"The number you have entered corresponds to none of the above." << endl;
    }

}

bool raffle (int value)
{
    int random[cArray];
    srand(time(NULL));
    for (int i=0; i<5; i++)
    {
        random[i]= 0+rand()%(100+1-0);
        cout<<random[i]<<" "<<endl;
    }

    for (int j=0; j<5; j++)
    {
        if (value == random[j])
        {
            cout << "\n" <<j<<endl;

            return true;
        }
    }
            cout << "Number not present."<<endl;
            return false;

}
</code>```

答:
Hello to all who have helped me try to solve this problem. I found out that the switch and fstream were incompatible, so I changed my cases to if() and else if() statements, and instead of having my (raffle(value==1) i changed it to (raffle(value==true) and it works! So once again, thank you all for your replies, esp you Hoang Long!
-Maria :D</p>

Body:
This is what I have, this program runs ok as it stands, the only problem I am having is that it will not save the approriate sentence in File3.txt. I included the entire program for understanding, what is it that I am not doing correctly that is preventing the sentence under the case option 'r' to not save? Thanks.

void ascii (int number);
bool raffle (int number);
const int cArray=5;

int main ()
{

    int value;

    char option;

while (1)
{

    cout <<"Enter a positive integer number: " <<endl;
    cin >>value;
    cout <<endl;

    cout <<"A[scii]" "\t\tR[affle]" "\t\tE[xit]" <<endl;
    cout <<"Please select an option: " <<endl;
    cin >>option;
    cout<<endl;

    switch (option)
    {
        case 'a':
        case 'A':

            ascii(value);
            break;

        case 'r':
        case 'R':
            ofstream outfile("G:/File3.txt", ios::out);
            if(!outfile)
            {
                cout<<"File could not be opened"<<endl;
                exit(1);
            }
            if (raffle(value)==1)
            {
                outfile<<"The number "<<value<<"is present in the array."<<endl;
            }
            else
            {
                outfile<<"The number "<<value<<"is not present in the array."<<endl;
            }
            outfile.close();
            break;

        case 'e':
        case 'E':

            return 0;
            break;

    }
}
}

void ascii (int value)
{

    if (48 <= value && value <= 57)
    {
        cout <<"The number you have entered corresponds to a digit in the ASCII table." <<endl;
    }
    else if(65 <= value && value <= 90)
    {
        cout <<"The number you have entered corresponds to an uppercase letter in the ASCII table." <<endl;
    }
    else if (97 <= value && value <= 122)
    {
        cout <<"The number you have entered corresponds to a lowercase letter in the ASCII table." <<endl;
    }
    else
    {
        cout <<"The number you have entered corresponds to none of the above." << endl;
    }

}

bool raffle (int value)
{
    int random[cArray];
    srand(time(NULL));
    for (int i=0; i<5; i++)
    {
        random[i]= 0+rand()%(100+1-0);
        cout<<random[i]<<" "<<endl;
    }

    for (int j=0; j<5; j++)
    {
        if (value == random[j])
        {
            cout << "\n" <<j<<endl;

            return true;
        }
    }
            cout << "Number not present."<<endl;
            return false;

}


问:
How to add folder of property files in eclipse
I shifted my project from tomcat to eclipse. All files are working fine but the folder containing property files are not working.

What I did so far:

Added folder in project -> build

created a source folder in project/src root and moved all

Set the classpath environment variables

Changed path with //, first folder without / etc.

but nothing worked for me. Here is screen shot:

Please advise where I am making mistake?
My OS is windows 8 but I have to deploy on CentOS
IDE: eclipse neon 3.0

thanks in anticipation

答:
Thanks all who tried to helped me. I appreciate their efforts.

After spending many hours I found the solution from this post

Copying solution here:

```<code>URL url = ConfigReader.class.getClassLoader().getResource("lang/global/settings.properties");
String filename = url.getPath();
</code>```

Thanks

Body:
Thanks all who tried to helped me. I appreciate their efforts.

After spending many hours I found the solution from this post

Copying solution here:

URL url = ConfigReader.class.getClassLoader().getResource("lang/global/settings.properties");
String filename = url.getPath();

Thanks


问:
Longest sequence of consecutive letters
Suppose I have a string of lower case letters, e.g.

```<code>'ablccmdnneofffpg'
</code>```

And my aim is to find the longest sequence of the consecutive numbers inside this string which in this case is:

```<code>'abcdefg'
</code>```

The intuitive attempt is to find loop around each letter and obtain the longest sequence starting from that letter. One possible solution is

```<code>longest_length = 0
start = None
current_start = 0
while current_start < len(word) - longest_length:
    current_length = 1
    last_in_sequence = ord(word[current_start])
    for i in range(current_start + 1, len(word)):
        if ord(word[i]) - last_in_sequence == 1:
            current_length += 1
            last_in_sequence = ord(word[i])
    if current_length > longest_length:
        longest_length = current_length
        start = current_start
    while (current_start < len(word) - 1 and
           ord(word[current_start + 1]) - ord(word[current_start]) == 1):
        current_start += 1
    current_start += 1
</code>```

Are there any other ways of solving the problem with fewer lines, or even using some pythonic methods?

答:
Similar to MosesKoledoye's solution, but only stores the lengthes for the ordinals of the chars and only builts the solution string in the end. This should therefore be a little more space-efficient:</p>

```<code>def longest_seq(s):
  d = {}
  for c in s:
    c, prev_c = ord(c), ord(c) - 1
    d[c] = max(d.get(c, 0), d.pop(prev_c, 0) + 1)
  c, l = max(d.items(), key=lambda i: i[1])
  return ''.join(map(chr, range(c-l+1, c+1)))
</code>```

Title: Longest sequence of consecutive letters

Body:
Suppose I have a string of lower case letters, e.g.

'ablccmdnneofffpg'

And my aim is to find the longest sequence of the consecutive numbers inside this string which in this case is:

'abcdefg'

The intuitive attempt is to find loop around each letter and obtain the longest sequence starting from that letter. One possible solution is

longest_length = 0
start = None
current_start = 0
while current_start < len(word) - longest_length:
    current_length = 1
    last_in_sequence = ord(word[current_start])
    for i in range(current_start + 1, len(word)):
        if ord(word[i]) - last_in_sequence == 1:
            current_length += 1
            last_in_sequence = ord(word[i])
    if current_length > longest_length:
        longest_length = current_length
        start = current_start
    while (current_start < len(word) - 1 and
           ord(word[current_start + 1]) - ord(word[current_start]) == 1):
        current_start += 1
    current_start += 1

Are there any other ways of solving the problem with fewer lines, or even using some pythonic methods?

Body:
Similar to MosesKoledoye's solution, but only stores the lengthes for the ordinals of the chars and only builts the solution string in the end. This should therefore be a little more space-efficient:

def longest_seq(s):
  d = {}
  for c in s:
    c, prev_c = ord(c), ord(c) - 1
    d[c] = max(d.get(c, 0), d.pop(prev_c, 0) + 1)
  c, l = max(d.items(), key=lambda i: i[1])
  return ''.join(map(chr, range(c-l+1, c+1)))


问:
composer custom install directory - root
We are trying to use composer to deal with dependencies for a wordpress site. I would like to include wordpress itself in these dependencies. I am trying to install wordpress to the root of the project. all the other plugins etc are installing correctly based on the installer-paths..

I have tried using fancyguy/webroot-installer, but that wipes the directory that the package is installed to
also tried mnsami/composer-custom-directory-installer, but that also wipes the directory.

I have a number of files in the root which i do not want to delete - such as the composer.json for one, .tfignore and suchlike.

is the only option I have to let it install to /vendor and then run a post-install script to move it where I want it? or is there another option I am missing

here is the one i tried for webroot-installer

```<code>{
  "name": "the/name",
  "description": "description",
  "repositories": [
    {
      "type": "composer",
      "url": "https://wpackagist.org"
    },
    {
      "type": "package",
      "package": {
        "name": "wordpress",
        "type": "webroot",
        "version": "4.7.5",
        "dist": {
          "type": "zip",
          "url": "https://github.com/WordPress/WordPress/archive/4.7.5.zip"
        },
        "require": {
          "fancyguy/webroot-installer": "1.0.0"
        }
      }
    }
  ],
  "require-dev": {
    "wpackagist-plugin/query-monitor": "2.13.4",
    "wordpress": "4.7.5",
    "fancyguy/webroot-installer": "1.0.0"
  },
  "require": {
    "wpackagist-plugin/advanced-custom-fields": "4.4.11",
    ...etc
  },
  "extra": {
    "webroot-dir": ".",
    "webroot-package": "wordpress",
    "installer-paths": {
      "library/plugins/{$name}": [ "type:wordpress-plugin" ]
    }
  },
  "scripts": { ...}
}
</code>```

here is the composer.json using composer-custom-directory-installer.

```<code>{
  "name": "the/name",
  "description": "description",
  "repositories": [
    {
      "type": "composer",
      "url": "https://wpackagist.org"
    },
    {
      "type": "package",
      "package": {
        "name": "wordpress",
        "type": "library",
        "version": "4.7.5",
        "dist": {
          "type": "zip",
          "url": "https://github.com/WordPress/WordPress/archive/4.7.5.zip"
        }
      }
    }
  ],
  "require-dev": {
    "mnsami/composer-custom-directory-installer": "1.1.*",
    "wordpress": "4.7.5"
  },
  "require": {
    "wpackagist-plugin/advanced-custom-fields": "4.4.11",
    ...etc
  },
  "extra": {
    "installer-paths": {
      "library/plugins/{$name}": [ "type:wordpress-plugin" ],
      "./": [ "wordpress" ]
    }

  },
  "scripts": { ... }
}
</code>```

答:
I believe that thats how composer installers are intended to work. From the reading I've done it erases the old files to ensure that there isn't any cross contamination of versions. Its not like a git checkout/merge that would handle the differences, but instead a clean install if needed (caching aside type thing).

I would recommend the approach of not keeping any files you are authoring inside the same folder you are installing things and instead take the approach of having everything install and compile into a distribution folder.

Leverage tools like web pack or gulp, plus NPM and composer to handle all your compiling, and keep your distribution folder as something that can be blown away and replicated. It adds some overhead, but allows for all the tools to interact without causing file loss.

For example my typical repos look as follows. With all the different tools in place, the dist is entirely gitignored, but composer and build tools compile into it. From there if I want to FTP or use CI/CD I can, but I have a clean folder that is never stored and contains the entire project once I run the tools.

```<code>/dist
/src (where any files I'm authoring reside)
composer.json
package.json
gulpfile.js
etc...
</code>```

QUICK UPDATE TO THIS. Been doing more playing around myself. It appears that the extended versions of composer installers won't install overtop of other directories. I've ended up doing the following which seems to work every time (still need to test with a deployment though)

```<code>"extra": {
    "installer-types": ["cms-core"],
    "installer-paths": {
        "public/wp": ["type:cms-core"],
        "public/wp-content/plugins/{$name}/": ["type:wordpress-plugin"],
        "public/wp-content/themes/{$name}/": ["type:wordpress-theme"]
    }
},
"repositories":[
    {
        "type": "composer",
        "url": "https://wpackagist.org"
    },
    {
        "type": "package",
        "package": {
            "name": "wordpress",
            "type": "cms-core",
            "version": "4.7.5",
            "dist": {
                "type": "zip",
                "url": "https://github.com/WordPress/WordPress/archive/4.7.5.zip"
            }
        }
    }
],
"require": {
    "composer/installers": "^1.3",
    "oomphinc/composer-installers-extender": "^1.1",
    "wpackagist-plugin/wordpress-seo": "^4.8",
    "wordpress": "^4.7"
},
"scripts": {
    "post-update-cmd": [
        "cp -R public/wp/ public && rm -rf public/wp"
    ]
}`
</code>```

Body:
We are trying to use composer to deal with dependencies for a wordpress site. I would like to include wordpress itself in these dependencies. I am trying to install wordpress to the root of the project. all the other plugins etc are installing correctly based on the installer-paths..

I have tried using fancyguy/webroot-installer, but that wipes the directory that the package is installed to
also tried mnsami/composer-custom-directory-installer, but that also wipes the directory.

I have a number of files in the root which i do not want to delete - such as the composer.json for one, .tfignore and suchlike.

is the only option I have to let it install to /vendor and then run a post-install script to move it where I want it? or is there another option I am missing

here is the one i tried for webroot-installer

{
  "name": "the/name",
  "description": "description",
  "repositories": [
    {
      "type": "composer",
      "url": "https://wpackagist.org"
    },
    {
      "type": "package",
      "package": {
        "name": "wordpress",
        "type": "webroot",
        "version": "4.7.5",
        "dist": {
          "type": "zip",
          "url": "https://github.com/WordPress/WordPress/archive/4.7.5.zip"
        },
        "require": {
          "fancyguy/webroot-installer": "1.0.0"
        }
      }
    }
  ],
  "require-dev": {
    "wpackagist-plugin/query-monitor": "2.13.4",
    "wordpress": "4.7.5",
    "fancyguy/webroot-installer": "1.0.0"
  },
  "require": {
    "wpackagist-plugin/advanced-custom-fields": "4.4.11",
    ...etc
  },
  "extra": {
    "webroot-dir": ".",
    "webroot-package": "wordpress",
    "installer-paths": {
      "library/plugins/{$name}": [ "type:wordpress-plugin" ]
    }
  },
  "scripts": { ...}
}

here is the composer.json using composer-custom-directory-installer.

{
  "name": "the/name",
  "description": "description",
  "repositories": [
    {
      "type": "composer",
      "url": "https://wpackagist.org"
    },
    {
      "type": "package",
      "package": {
        "name": "wordpress",
        "type": "library",
        "version": "4.7.5",
        "dist": {
          "type": "zip",
          "url": "https://github.com/WordPress/WordPress/archive/4.7.5.zip"
        }
      }
    }
  ],
  "require-dev": {
    "mnsami/composer-custom-directory-installer": "1.1.*",
    "wordpress": "4.7.5"
  },
  "require": {
    "wpackagist-plugin/advanced-custom-fields": "4.4.11",
    ...etc
  },
  "extra": {
    "installer-paths": {
      "library/plugins/{$name}": [ "type:wordpress-plugin" ],
      "./": [ "wordpress" ]
    }

  },
  "scripts": { ... }
}

Body:
I believe that thats how composer installers are intended to work. From the reading I've done it erases the old files to ensure that there isn't any cross contamination of versions. Its not like a git checkout/merge that would handle the differences, but instead a clean install if needed (caching aside type thing).

I would recommend the approach of not keeping any files you are authoring inside the same folder you are installing things and instead take the approach of having everything install and compile into a distribution folder.

Leverage tools like web pack or gulp, plus NPM and composer to handle all your compiling, and keep your distribution folder as something that can be blown away and replicated. It adds some overhead, but allows for all the tools to interact without causing file loss.

For example my typical repos look as follows. With all the different tools in place, the dist is entirely gitignored, but composer and build tools compile into it. From there if I want to FTP or use CI/CD I can, but I have a clean folder that is never stored and contains the entire project once I run the tools.

/dist
/src (where any files I'm authoring reside)
composer.json
package.json
gulpfile.js
etc...

QUICK UPDATE TO THIS. Been doing more playing around myself. It appears that the extended versions of composer installers won't install overtop of other directories. I've ended up doing the following which seems to work every time (still need to test with a deployment though)

"extra": {
    "installer-types": ["cms-core"],
    "installer-paths": {
        "public/wp": ["type:cms-core"],
        "public/wp-content/plugins/{$name}/": ["type:wordpress-plugin"],
        "public/wp-content/themes/{$name}/": ["type:wordpress-theme"]
    }
},
"repositories":[
    {
        "type": "composer",
        "url": "https://wpackagist.org"
    },
    {
        "type": "package",
        "package": {
            "name": "wordpress",
            "type": "cms-core",
            "version": "4.7.5",
            "dist": {
                "type": "zip",
                "url": "https://github.com/WordPress/WordPress/archive/4.7.5.zip"
            }
        }
    }
],
"require": {
    "composer/installers": "^1.3",
    "oomphinc/composer-installers-extender": "^1.1",
    "wpackagist-plugin/wordpress-seo": "^4.8",
    "wordpress": "^4.7"
},
"scripts": {
    "post-update-cmd": [
        "cp -R public/wp/ public && rm -rf public/wp"
    ]
}`


问:
Getting div width and height from jquery if that div used percentage itself
I need to get the div size in px while itself it set to 100% as width & height.

But CDT output gives:
Width = 437px and Height=439
But when I try to inspect that div tag CDT display width = 420 and height = 422px (as seen in image)

Why is that happen when I used

```<code>var divWidth = $('.divhandler').width();
var divHeight = $('.divhandler').height();
</code>```

  function getImageDimensions(path, callback) {
    var img = new Image();
    img.onload = function() {
      callback({
        width: img.width,
        height: img.height
      });
    }
    img.src = path;
  }
  var imgWidth;
  var imgHeight;

  function DoReset(_width, _height) {
    imgWidth = _width;
    imgHeight = _height;
    console.log("IMG Width:" + imgWidth);
    console.log("IMG Height:" + imgHeight);
    //get div
    var divWidth = $('.divhandler').width();
    var divHeight = $('.divhandler').height();
    console.log("DIV Width:" + divWidth);
    console.log("DIV Height:" + divHeight);
    var ratioCalc;
    var newImageHeight;
    var newImageWidth;
    if (imgWidth > imgHeight) {
      if (divWidth > imgWidth) {
        ratioCalc = imgWidth / imgHeight;
        newImageHeight = divHeight * ratioCalc;
        newImageWidth = (imgWidth / imgHeight) * newImageHeight;
        $('.imghandler').css('width', newImageHeight + 'px');
        console.log("1");
      } else {
        ratioCalc = imgHeight / imgWidth;
        newImageHeight = divWidth * ratioCalc;
        $('.imghandler').css('height', newImageHeight + 'px');
        console.log("2");
      }
    } else {
      console.log("2");
    }
  }
  getImageDimensions("http://www.dailymobile.net/wp-content/uploads/wallpapers/landscape-wallpapers-320x240/landscape-wallpapers-320x240-03.jpg", function(data) {
    imgWidth = data.width;
    imgHeight = data.height;
    DoReset(data.width, data.height);
  });
  $(window).resize(function() {
    getImageDimensions("cgihandle.jpg", function(data) {
      imgWidth = data.width;
      imgHeight = data.height;
      DoReset(imgWidth, imgHeight);
    });
  });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="divhandler" style="width:100%;height:100%;background:#ccc"> <img src="http://www.dailymobile.net/wp-content/uploads/wallpapers/landscape-wallpapers-320x240/landscape-wallpapers-320x240-03.jpg" class="imghandler" /> </div></code>```

答: During the mouse hover , the total size of the div is shown to you in CDT , along with the padding and border as shown in the image. Your actual div size is 437x439 but the increase is due to the padding around it.

Body:
I need to get the div size in px while itself it set to 100% as width & height.

But CDT output gives:
Width = 437px and Height=439
But when I try to inspect that div tag CDT display width = 420 and height = 422px (as seen in image)

Why is that happen when I used

var divWidth = $('.divhandler').width();
var divHeight = $('.divhandler').height();

  function getImageDimensions(path, callback) {
    var img = new Image();
    img.onload = function() {
      callback({
        width: img.width,
        height: img.height
      });
    }
    img.src = path;
  }
  var imgWidth;
  var imgHeight;

  function DoReset(_width, _height) {
    imgWidth = _width;
    imgHeight = _height;
    console.log("IMG Width:" + imgWidth);
    console.log("IMG Height:" + imgHeight);
    //get div
    var divWidth = $('.divhandler').width();
    var divHeight = $('.divhandler').height();
    console.log("DIV Width:" + divWidth);
    console.log("DIV Height:" + divHeight);
    var ratioCalc;
    var newImageHeight;
    var newImageWidth;
    if (imgWidth > imgHeight) {
      if (divWidth > imgWidth) {
        ratioCalc = imgWidth / imgHeight;
        newImageHeight = divHeight * ratioCalc;
        newImageWidth = (imgWidth / imgHeight) * newImageHeight;
        $('.imghandler').css('width', newImageHeight + 'px');
        console.log("1");
      } else {
        ratioCalc = imgHeight / imgWidth;
        newImageHeight = divWidth * ratioCalc;
        $('.imghandler').css('height', newImageHeight + 'px');
        console.log("2");
      }
    } else {
      console.log("2");
    }
  }
  getImageDimensions("http://www.dailymobile.net/wp-content/uploads/wallpapers/landscape-wallpapers-320x240/landscape-wallpapers-320x240-03.jpg", function(data) {
    imgWidth = data.width;
    imgHeight = data.height;
    DoReset(data.width, data.height);
  });
  $(window).resize(function() {
    getImageDimensions("cgihandle.jpg", function(data) {
      imgWidth = data.width;
      imgHeight = data.height;
      DoReset(imgWidth, imgHeight);
    });
  });


问:
mongoDB, express, webpack-dev-middleware, console.log db collection won't work
I try to setting up together mongoDB, express and webpack-dev-middleware. I want to do it the simplest way as it's possible, using as little adding modules as it's possible. I'm basing on several tutorials (I haven't found one simply). Everything worked to moment when I tred console log collection from mongoDB. I have nothing print in my consola.

I'm sure that connection to mongoDB is ok. I think it's something with webpac-dev-middleware and routing, but I can't find some helpfull information or tutorial.

server.js

```<code>const path = require('path');
const express = require('express');
const webpack = require('webpack');
const bodyParser = require('body-parser');
const config = require('./webpack.config.js');

const app = express();

const compiler = webpack(config);

app.use(bodyParser.urlencoded({extended: true}));

const MongoClient = require('mongodb').MongoClient;

var db;

MongoClient.connect('mongodb://USER:PASSWORD@HOST:PORT/testit' (err, database) => {
  if (err) return console.log('Connection error: ',err);
  db = database;
  app.listen(3000, () => {
    console.log('MongoDB listening on 3000');
 });
});

const webpackDevMiddleware = require('webpack-dev-middleware')(compiler, {
  noInfo: true,
      stats: {
        colors: true,
      }
  });
const webpackHotMiddleware = require('webpack-hot-middleware')(compiler, {
     log: console.log
});

app.use(webpackDevMiddleware);
app.use(webpackHotMiddleware);

app.use(express.static(__dirname + '/'));
app.get('/', (req, res) =>{
    db.collection('quotes').find().toArray(function(err, results) {
      console.log(results);  //according to tutorial this line should to display console log, but I have nothing, even if I try console log error. Or whatever...
    });
});

app.post('/quotes', (req, res) => {
  console.log(req.body);
  db.collection('quotes').save(req.body, (err, result) => {
    if (err) return console.log(err);

    console.log('saved to database');
    res.redirect('/');
  });
});

var listener = app.listen(8888, function(){
    console.log('Listening on port ' + listener.address().port + ' mode: ' +
app.settings.env);
});
</code>```

webpack.confing.js

```<code>'use strict';

var Webpack = require('webpack');
var path = require('path');

var config = {
    entry: [
        'webpack-hot-middleware/client',
        './public/index.js'
    ],
    output: {
        path: __dirname + "/dist",
        filename: "bundle.js"
        },
    devServer: {
        headers: {
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Credentials": "true",
            "Access-Control-Allow-Headers": "Content-Type, Authorization, x-id, Content-Length, X-Requested-With",
            "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS"
        },
        inline: true
    },
    module: {
        loaders: [
            {
                test: /\.js$/,
                loader: 'babel-loader',
                exclude: /node_modules/,
                query: {
                    presets: ['es2015','react']
                }
            }
        ]
    },
    plugins: [new Webpack.HotModuleReplacementPlugin()]
};

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

Please, help me find where exactly problem is. I'm sure I missunderstand something, but I don't know what.

答:
The problem is that express.static will find the index.html file and serve it, and the request for / will therefore never reach your route handler.

If you want it to get called, you need to declare it before express.static:

```<code>app.get('/', (req, res) =>{
    db.collection('quotes').find().toArray(function(err, results) {
      console.log(results);
      res.sendFile(__dirname + '/index.html'); // respond with the `index.html` file
    });
});
app.use(express.static(__dirname + '/'));
</code>```

Body:
I try to setting up together mongoDB, express and webpack-dev-middleware. I want to do it the simplest way as it's possible, using as little adding modules as it's possible. I'm basing on several tutorials (I haven't found one simply). Everything worked to moment when I tred console log collection from mongoDB. I have nothing print in my consola.

I'm sure that connection to mongoDB is ok. I think it's something with webpac-dev-middleware and routing, but I can't find some helpfull information or tutorial.

server.js

const path = require('path');
const express = require('express');
const webpack = require('webpack');
const bodyParser = require('body-parser');
const config = require('./webpack.config.js');

const app = express();

const compiler = webpack(config);

app.use(bodyParser.urlencoded({extended: true}));

const MongoClient = require('mongodb').MongoClient;

var db;

MongoClient.connect('mongodb://USER:PASSWORD@HOST:PORT/testit' (err, database) => {
  if (err) return console.log('Connection error: ',err);
  db = database;
  app.listen(3000, () => {
    console.log('MongoDB listening on 3000');
 });
});

const webpackDevMiddleware = require('webpack-dev-middleware')(compiler, {
  noInfo: true,
      stats: {
        colors: true,
      }
  });
const webpackHotMiddleware = require('webpack-hot-middleware')(compiler, {
     log: console.log
});

app.use(webpackDevMiddleware);
app.use(webpackHotMiddleware);

app.use(express.static(__dirname + '/'));
app.get('/', (req, res) =>{
    db.collection('quotes').find().toArray(function(err, results) {
      console.log(results);  //according to tutorial this line should to display console log, but I have nothing, even if I try console log error. Or whatever...
    });
});

app.post('/quotes', (req, res) => {
  console.log(req.body);
  db.collection('quotes').save(req.body, (err, result) => {
    if (err) return console.log(err);

    console.log('saved to database');
    res.redirect('/');
  });
});

var listener = app.listen(8888, function(){
    console.log('Listening on port ' + listener.address().port + ' mode: ' +
app.settings.env);
});

webpack.confing.js

'use strict';

var Webpack = require('webpack');
var path = require('path');

var config = {
    entry: [
        'webpack-hot-middleware/client',
        './public/index.js'
    ],
    output: {
        path: __dirname + "/dist",
        filename: "bundle.js"
        },
    devServer: {
        headers: {
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Credentials": "true",
            "Access-Control-Allow-Headers": "Content-Type, Authorization, x-id, Content-Length, X-Requested-With",
            "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS"
        },
        inline: true
    },
    module: {
        loaders: [
            {
                test: /\.js$/,
                loader: 'babel-loader',
                exclude: /node_modules/,
                query: {
                    presets: ['es2015','react']
                }
            }
        ]
    },
    plugins: [new Webpack.HotModuleReplacementPlugin()]
};

module.exports = config;

Please, help me find where exactly problem is. I'm sure I missunderstand something, but I don't know what.

Body:
The problem is that express.static will find the index.html file and serve it, and the request for / will therefore never reach your route handler.

If you want it to get called, you need to declare it before express.static:

app.get('/', (req, res) =>{
    db.collection('quotes').find().toArray(function(err, results) {
      console.log(results);
      res.sendFile(__dirname + '/index.html'); // respond with the `index.html` file
    });
});
app.use(express.static(__dirname + '/'));


问:
Selenium Web Driver | Find object | Python
In advance I apologize for my English, because I write with an interpreter.

There is a task to click on one of these accounts, suppose AAccount, using Selenium Web Driver (Python, Chrome).
The problem is that it's impossible to do this on XPath and CSS, because the elements are the same.
Here is part of the source code for the page. I also attached a screenshot of the page.

</style>

TeAOK

Изменить

TeAOK G9T3arz

teaokg9t3arz@gmail.com

Конфиденциальность
Мой аккаунт

TeAOK G9T3arz

teaokg9t3arz@gmail.com (по умолчанию)

Все аккаунты брендов »

Добавить аккаунт

Выйти

Выберите аккаунт

  TeAOK G9T3arz
  teaokg9t3arz@gmail.com
  Выберите

  EAccount
  Выберите

  FAccount
  Выберите

  GAccount
  Выберите

  CAccount
  Выберите

  DAccount
  Выберите

  iAccount
  Выберите

  AAccount
  Выберите

  BAccount
  Выберите

  IAccount
  Выберите

  JAccount
  Выберите

Аккаунты

  Выберите аккаунт Google

  TeAOK G9T3arz
  (teaokg9t3arz@gmail.com)

  EAccount

  FAccount

  GAccount

  CAccount

  DAccount

  iAccount

  AAccount

  BAccount

  IAccount

  JAccount

Google

  Конфиденциальность и условия

Справка

答:
You can try to locate required element by partial link text:

```<code>driver.find_element_by_partial_link_text("AAccount").click()
</code>```

If it doesn't work, you can try to add some time to wait for required element:

```<code>from selenium.webdriver.support.ui import WebDriverWait as wait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

wait(driver, 10).until(EC.element_to_be_clickable((By.PARTIAL_LINK_TEXT, "AAccount"))).click()
</code>```

Body:
In advance I apologize for my English, because I write with an interpreter.

There is a task to click on one of these accounts, suppose AAccount, using Selenium Web Driver (Python, Chrome).
The problem is that it's impossible to do this on XPath and CSS, because the elements are the same.
Here is part of the source code for the page. I also attached a screenshot of the page.

</style>

TeAOK

<a class="gb_b gb_db gb_R" href="https://accounts.google.com/SignOutOptions?hl=ru&continue=https://accounts.google.com/b/0/DelegateAccountSelector%3Fcontinue%3Dhttps%253A%252F%252Faccounts.google.com%252Fo%252Foauth2%252Fauth%253Fclient_id%253D702580890038-5fs7raaanbrl7rssnkg3e62qgprukbni.apps.googleusercontent.com%2526redirect_uri%253Dhttps%253A%252F%252Fvkmix.com%252Fmodules%252Fyoutube%252Fbot2.php%2526scope%253Dhttps%253A%252F%252Fwww.googleapis.com%252Fauth%252Fyoutube%2526response_type%253Dcode%2526access_type%253Doffline" title="Аккаунт Google: TeAOK G9T3arz
(teaokg9t3arz@gmail.com)" role="button" tabindex="0">

Изменить

TeAOK G9T3arz

teaokg9t3arz@gmail.com

Конфиденциальность
Мой аккаунт

TeAOK G9T3arz

teaokg9t3arz@gmail.com (по умолчанию)

<a class="gb_Sb gb_6a" href="https://myaccount.google.com/brandaccounts?authuser=0&continue=https://accounts.google.com/b/0/DelegateAccountSelector%3Fcontinue%3Dhttps%253A%252F%252Faccounts.google.com%252Fo%252Foauth2%252Fauth%253Fclient_id%253D702580890038-5fs7raaanbrl7rssnkg3e62qgprukbni.apps.googleusercontent.com%2526redirect_uri%253Dhttps%253A%252F%252Fvkmix.com%252Fmodules%252Fyoutube%252Fbot2.php%2526scope%253Dhttps%253A%252F%252Fwww.googleapis.com%252Fauth%252Fyoutube%2526response_type%253Dcode%2526access_type%253Doffline&service=/b/0/DelegateAccountSelector%3Fcontinue%3Dhttps%253A%252F%252Faccounts.google.com%252Fo%252Foauth2%252Fauth%253Fclient_id%253D702580890038-5fs7raaanbrl7rssnkg3e62qgprukbni.apps.googleusercontent.com%2526redirect_uri%253Dhttps%253A%252F%252Fvkmix.com%252Fmodules%252Fyoutube%252Fbot2.php%2526scope%253Dhttps%253A%252F%252Fwww.googleapis.com%252Fauth%252Fyoutube%2526response_type%253Dcode%2526access_type%253Doffline%26authuser%3D%24authuser" aria-hidden="true">
Все аккаунты брендов »

<a class="gb_Fa gb_pf gb_xb" href="https://accounts.google.com/AddSession?continue=https%3A%2F%2Faccounts.google.com%2Fb%2F0%2FDelegateAccountSelector%3Fcontinue%3Dhttps%253A%252F%252Faccounts.google.com%252Fo%252Foauth2%252Fauth%253Fclient_id%253D702580890038-5fs7raaanbrl7rssnkg3e62qgprukbni.apps.googleusercontent.com%2526redirect_uri%253Dhttps%253A%252F%252Fvkmix.com%252Fmodules%252Fyoutube%252Fbot2.php%2526scope%253Dhttps%253A%252F%252Fwww.googleapis.com%252Fauth%252Fyoutube%2526response_type%253Dcode%2526access_type%253Doffline">Добавить аккаунт

Выйти

Выберите аккаунт

  TeAOK G9T3arz
  teaokg9t3arz@gmail.com
  Выберите

  EAccount
  Выберите

  FAccount
  Выберите

  GAccount
  Выберите

  CAccount
  Выберите

  DAccount
  Выберите

  iAccount
  Выберите

  AAccount
  Выберите

  BAccount
  Выберите

  IAccount
  Выберите

  JAccount
  Выберите

Аккаунты

  Выберите аккаунт Google

  TeAOK G9T3arz
  (teaokg9t3arz@gmail.com)

  EAccount

  FAccount

  GAccount

  CAccount

  DAccount

  iAccount

  AAccount

  BAccount

  IAccount

  JAccount

Google

  Конфиденциальность и условия

Справка

Body:
You can try to locate required element by partial link text:

driver.find_element_by_partial_link_text("AAccount").click()

If it doesn't work, you can try to add some time to wait for required element:

from selenium.webdriver.support.ui import WebDriverWait as wait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

wait(driver, 10).until(EC.element_to_be_clickable((By.PARTIAL_LINK_TEXT, "AAccount"))).click()