question
dict
answers
list
id
stringlengths
2
5
accepted_answer_id
stringlengths
2
5
popular_answer_id
stringlengths
2
5
{ "accepted_answer_id": "33806", "answer_count": 2, "body": "UIWebViewからWKWebViewに移行しようと思い、コードを書き換えていたのですが、WKWebViewでのローカルに置いたHTMLファイルが読み込まれません。UIWebViewでは下記のコードでローカルファイルを読み込むことができました。\n\n```\n\n let cachePath = NSSearchPathForDirectoriesInDomains(.cachesDirectory,.userDomainMask, true)[0] + \"cacheHtml.html\"\n try! html.write(toFile: cachePath, atomically: true, encoding: String.Encoding.utf8)\n let request = URLRequest(url: URL(string: cachePath)!)\n webview.loadRequest(request)\n \n```\n\n上記ではキャッシュディレクトリのパスをとって、String型のhtml変数にwebページのソースが格納されているので、それを書き込んでいます。書き込み後、UIWebViewのloadRequestで読み込んでいます。一方、WKWebViewで下記のように実装したところ、画面が真っ白なまま読み込まれません。\n\n```\n\n let cachePath = NSSearchPathForDirectoriesInDomains(.cachesDirectory,.userDomainMask, true)[0] + \"cacheHtml.html\"\n try! html.write(toFile: cachePath, atomically: true, encoding: String.Encoding.utf8)\n let cacheUrl = URL(string: cachePath)\n let request = URLRequest(url: cacheUrl!)\n webview.load(request)\n \n```\n\nWKWebViewでは、urlをそのまま入れたときや、webview.loadHTMLStringではうまくページを読み込みます。wkwebviewでローカルHTMLファイルを読み込むようにするにはどのように実装したら良いでしょうか。", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-06T00:19:07.393", "favorite_count": 0, "id": "33800", "last_activity_date": "2017-04-06T03:07:42.920", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "21189", "post_type": "question", "score": 0, "tags": [ "swift", "ios" ], "title": "WKWebViewでのローカルHTMLの読み込みについて", "view_count": 6506 }
[ { "body": "iOS9以上なら`loadFileURL(_ URL: URL, allowingReadAccessTo readAccessURL:\nURL)`メソッドを使用できます。 \nもしもiOS8以下に対応するならhtmlをStringに読み込んで`loadHTMLString(_ string: String, baseURL:\nURL?)`メソッドで読み込むしかありません。", "comment_count": 2, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-06T01:22:48.787", "id": "33803", "last_activity_date": "2017-04-06T01:22:48.787", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "10871", "parent_id": "33800", "post_type": "answer", "score": 0 }, { "body": "下記のようにすることでローカルファイルを読むことができました。\n\n```\n\n let tmpPath = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(\"tmpHtml.html\") as URL\n try! trimHtml.write(to: tmpPath, atomically: true, encoding: String.Encoding.utf8)\n webview.loadFileURL(tmpPath, allowingReadAccessTo: tmpPath)\n \n```\n\nまた、webview.load(request(url: tmpPath))でも読み込むことができました。", "comment_count": 1, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-06T03:07:42.920", "id": "33806", "last_activity_date": "2017-04-06T03:07:42.920", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "21189", "parent_id": "33800", "post_type": "answer", "score": 0 } ]
33800
33806
33803
{ "accepted_answer_id": "33808", "answer_count": 1, "body": "PowerShellでは文字列の配列に対して String クラスのメソッド、例えば `Replace()`\nなどが呼び出せるようですが、これはどういう仕様によるものなのでしょうか?\n\n```\n\n PS C:\\> $arr = \"abc\",\"abc\"\n \n PS C:\\> $arr\n abc\n abc\n \n PS C:\\> $arr.GetType()\n \n IsPublic IsSerial Name BaseType \n -------- -------- ---- -------- \n True True Object[] System.Array \n \n PS C:\\> $arr.Replace('b', '_')\n a_c\n a_c\n \n```\n\n`GetType()` で型を取得してもただの `Object[]` ですし、Get-Member で見てもこのメソッドは存在しません。Count\nのようにエイリアスが追加されているというわけでもないようです。", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-06T05:58:44.637", "favorite_count": 0, "id": "33807", "last_activity_date": "2017-04-06T05:58:44.637", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "8000", "post_type": "question", "score": 1, "tags": [ "powershell" ], "title": "文字列の配列に対してStringクラスのメソッドが呼べるのはなぜ?", "view_count": 246 }
[ { "body": "PowerShell 3.0\n以降、コレクション自身には存在せず、その要素に存在するメソッド・プロパティを呼び出そうとすると、各要素に対する呼び出しに変換されます。\n\nForeach\nステートメントの簡略構文と同様、コレクションの要素の型が混在していても構いませんし、一部の要素にだけ存在するメソッド・プロパティを呼び出すこともできます。\n\n```\n\n PS C:\\> [System.Linq.Enumerable]::Range(32,10).ToChar($null) #配列でないコレクション\n \n !\n \"\n #\n $\n %\n &\n '\n (\n )\n \n PS C:\\> ([DateTime]::Now, [TimeSpan]::FromHours(1)).Ticks #異なる型だがどちらも実装している\n 636270872544918849\n 36000000000\n \n PS C:\\> ([DateTime]::Now, [TimeSpan]::FromHours(1)).TimeOfDay #DateTimeしか実装していない\n \n \n Days : 0\n Hours : 14\n Minutes : 38\n Seconds : 51\n Milliseconds : 953\n Ticks : 527319534503\n TotalDays : 0.610323535304398\n TotalHours : 14.6477648473056\n TotalMinutes : 878.865890838333\n TotalSeconds : 52731.9534503\n TotalMilliseconds : 52731953.4503\n \n```\n\nMSDNのドキュメントでは [about_Methods](https://technet.microsoft.com/ja-\njp/library/hh847878.aspx) の「スカラー オブジェクトおよびコレクションのメソッド」に記載があります。", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-06T05:58:44.637", "id": "33808", "last_activity_date": "2017-04-06T05:58:44.637", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "8000", "parent_id": "33807", "post_type": "answer", "score": 4 } ]
33807
33808
33808
{ "accepted_answer_id": "33812", "answer_count": 2, "body": "ブラウザの戻るボタンで戻った時、最新のページを読み込みたいのですが、可能でしょうか? \nIE10または11でできればOKです。 \n以下のコードで試してみたのですが、うまくいきませんでした。よろしくお願いします!\n\n```\n\n <script>\n <!--\n window.onunload = function(){location.reload();}\n -->\n </script>\n \n```\n\n常に強制リロードで解決は出来ましたが却下されました。やはり「戻る」限定で行いたいです。\n\n```\n\n $(function(){\n if (window.name != \"re_load\") {\n location.reload();\n window.name = \"re_load\";\n }else{\n window.name = \"\";\n }\n });\n \n```", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-06T07:40:42.953", "favorite_count": 0, "id": "33810", "last_activity_date": "2017-04-07T06:39:38.027", "last_edit_date": "2017-04-06T08:32:33.550", "last_editor_user_id": "15167", "owner_user_id": "15167", "post_type": "question", "score": 4, "tags": [ "javascript", "html", "jquery" ], "title": "ブラウザの戻るボタンで戻ったときにリロードする方法はありますか?", "view_count": 12287 }
[ { "body": "JavaScriptではなくサーバー側で戻る対象のページのHTTPヘッダーに\n\n```\n\n Cache-Control: no-store, no-cache, must-revalidate, max-age=0, post-check=0, pre-check=0\n Pragma: no-cache\n \n```\n\nのように指定してキャッシュを無効化すべきだと思います。", "comment_count": 3, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-06T08:31:51.147", "id": "33812", "last_activity_date": "2017-04-07T06:39:38.027", "last_edit_date": "2017-04-07T06:39:38.027", "last_editor_user_id": "5750", "owner_user_id": "5750", "parent_id": "33810", "post_type": "answer", "score": 3 }, { "body": "PHP側のコントローラに以下のコードを追加したら解決しました。 \nありがとうございます。\n\n```\n\n header(\"Cache-Control: no-store, no-cache, must-revalidate, max-age=0, post-check=0, pre-check=0\");\n header(\"Pragma: no-cache\");\n \n```\n\n<https://teratail.com/questions/91>", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-06T09:24:12.537", "id": "33815", "last_activity_date": "2017-04-06T09:24:12.537", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "15167", "parent_id": "33810", "post_type": "answer", "score": 1 } ]
33810
33812
33812
{ "accepted_answer_id": "33817", "answer_count": 1, "body": "`<div id=\"study_001\">`をまとまりとして、 \n`<img>`や下の`<ul>`との間に余白を作りたいのですが、 \n重なってしまいます。\n\ndivはブロック要素だと思うのですが、 \nspanのみを中身にもつdivは高さを持たないということでしょうか?\n\n[![画像の説明をここに入力](https://i.stack.imgur.com/rs2XD.png)](https://i.stack.imgur.com/rs2XD.png)\n\n**[HTML]**\n\n```\n\n <img src=\"images/001_blue.png\" alt=\"\">\n \n <div id=\"study_001\">\n <span id=\"margin\">margin</span><span id=\"border\">border</span><span id=\"padding\">padding</span>\n </div>\n \n <ul>\n <li>HTMLとCSS</li>\n <li>要素</li>\n <li>margin|border|padding</li>\n <li>float</li>\n <!--...-->\n \n```\n\n**[CSS]**\n\n```\n\n img {\n width: 500px;\n margin: 0 20px;\n float: left;\n }\n \n #study_001{\n clear: left;\n }\n \n #margin{\n padding: 10px 50px;\n margin: 10px 0px 10px 20px;\n background: #f98;\n }\n \n #border{\n border-left: 3px #fff solid;\n padding: 10px 0px 10px 2px;\n background: #988;\n margin: 0;\n }\n \n #padding{\n background: #498;\n padding: 10px 50px;\n }\n \n```", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-06T09:15:46.733", "favorite_count": 0, "id": "33814", "last_activity_date": "2017-04-06T10:46:57.977", "last_edit_date": "2017-04-06T09:21:08.523", "last_editor_user_id": "12297", "owner_user_id": "12297", "post_type": "question", "score": 1, "tags": [ "html", "css" ], "title": "HTMLで画像と文字が重なってしまう。", "view_count": 31292 }
[ { "body": "開発者ツールで見るとわかりますが、span に指定した padding が親要素 `#study_001` の高さに反映されていません。もちろん、上下\nmargin も反映されていません。\n\n[![画像の説明をここに入力](https://i.stack.imgur.com/85bat.png)](https://i.stack.imgur.com/85bat.png)\n\nインライン要素の上下位置や間隔は **行の高さ** 、つまり `line-height` を基準に計算されます。ですから padding や border\nを指定した場合、その部分が親要素からはみ出したり、前後の行と重なってしまうことになります。\n\nブロック要素のレイアウトが「高さと幅を持つ箱を並べる」のに対し、インライン要素では「中にあるテキストを流し込む」といったイメージでしょうか。\n\n```\n\n div {\r\n line-height: 1;\r\n width: 200px;\r\n border: 1px solid gray;\r\n margin: 20px;\r\n }\r\n \r\n span {\r\n padding: 3px;\r\n background: rgba(255, 128, 128, 0.5);\r\n border: 1px solid red;\r\n }\n```\n\n```\n\n <div>\r\n <span>じゅげむ じゅげむ ごこうのすりきれ</span>\r\n </div>\n```\n\n代わりの方法としては\n\n * padding ではなく line-height で高さを確保する\n * `display: inline-block`(行内に配置されるブロック要素のような感じなので、ボックスの幅や高さを持ち、折り返しで分断されることがない)\n * `display: table-cell`\n * `display: block` \\+ `float: left`\n\n等々。どれも使い方によってはデメリットがありますから、用途に合わせて選んでください。", "comment_count": 5, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-06T10:46:57.977", "id": "33817", "last_activity_date": "2017-04-06T10:46:57.977", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "8000", "parent_id": "33814", "post_type": "answer", "score": 5 } ]
33814
33817
33817
{ "accepted_answer_id": "33821", "answer_count": 4, "body": "```\n\n from sympy import *\n var('x y')\n def MYprint(h):\n print('#h=',h)   #この行をどのようになおしたらいいですか?\n f=x+1\n g=y+2\n MYprint(f)\n MYprint(g)\n #WANT f= x + 1\n #WANT g= y + 2\n \n```\n\n(参考)シンボルを文字列に変換します。 \n<http://ref.xaio.jp/ruby/classes/symbol/to_s>", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-06T13:32:19.767", "favorite_count": 0, "id": "33820", "last_activity_date": "2017-10-17T06:57:51.143", "last_edit_date": "2017-10-17T06:57:51.143", "last_editor_user_id": "754", "owner_user_id": "17199", "post_type": "question", "score": 0, "tags": [ "python", "sympy" ], "title": "sympyでシンボル名を文字列に変換にする方法を教えて下さい", "view_count": 1270 }
[ { "body": "通常、呼び出し元での引数の変数名は関数内からでは分かりません。ただ、Python には inspect\nというモジュールが用意されていますので、これを使って当該の変数名を知ることができます。\n\n**MYprint.py**\n\n```\n\n #!/usr/bin/python3\n \n def MYprint(h):\n import inspect, re\n frame = inspect.getouterframes(inspect.currentframe())[1][0]\n arg_str = inspect.getframeinfo(frame).code_context[0]\n arg = re.search('\\((.+?)\\)', arg_str).group(1)\n if arg.find('='):\n arg = arg.split('=')[0].strip()\n print('{0} = {1}'.format(arg, h))\n \n \n from sympy import *\n var('x y')\n \n f = x + 1\n g = y + 2\n \n MYprint(f)\n MYprint(g)\n MYprint(h = x ** 2 + 3 * x - 1)\n \n```\n\n**実行**\n\n```\n\n $ ./MYprint.py\n f = x + 1\n g = y + 2\n h = x**2 + 3*x - 1\n \n```\n\nしかし、\n\n```\n\n MYprint(f + 1)\n \n```\n\nなどとすると、\n\n```\n\n f + 1 = x + 2\n \n```\n\nと表示されてしまいます。\n\nまぁ、MYprint() 関数が変数名(文字列)を受け取る様にするのも考えられますが、\n\n```\n\n def MYprint(h):\n print('{0} = {1}'.format(h, eval(h)))\n \n MYprint('f')\n MYprint('g')\n \n```\n\nこれなら直接 `print('{0} = {1}'.format('f', f))` とでもする方が良いでしょうね。", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-06T16:09:01.827", "id": "33821", "last_activity_date": "2017-04-06T16:09:01.827", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": null, "parent_id": "33820", "post_type": "answer", "score": 1 }, { "body": "metropolis様 \nありがとうございました。\n\n```\n\n from sympy import *\n var('x')\n def MYprint(h):\n print('#{0} = {1}'.format(h, eval(h)),type(eval(h)))\n f = x + 1\n MYprint('x')\n MYprint('f')\n #x = x <class 'sympy.core.symbol.Symbol'>\n #f = x + 1 <class 'sympy.core.add.Add'>\n \n```", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-07T13:24:15.810", "id": "33839", "last_activity_date": "2017-04-07T13:24:15.810", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "17199", "parent_id": "33820", "post_type": "answer", "score": 0 }, { "body": "以下は,失敗したプログラムです。 \n関数syの関数prは、できませんでした。 \n\"(\"をはずしてもネストネストとなると、意味はありませんでした。\n\n```\n\n from sympy import *\n var('x')\n def symbol2str(h):\n import inspect, re\n frame = inspect.getouterframes(inspect.currentframe())[1][0]\n arg_str = inspect.getframeinfo(frame).code_context[0]\n arg = re.search('\\((.+?)\\)', arg_str).group(1)\n return arg\n f = x + 1\n c=symbol2str(f) #cに代入しています\n print(c)\n print(symbol2str(f)) #cに代入していません。残念でした。\n #結果\n #f\n #symbol2str(f\n \n```", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-07T14:27:17.793", "id": "33842", "last_activity_date": "2017-04-07T14:27:17.793", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "17199", "parent_id": "33820", "post_type": "answer", "score": 0 }, { "body": "cosで実行してみました。\n\n```\n\n from sympy import *\n var('x')\n print('#x=',x,type(x))\n f=cos(x)\n print('#f=',f,type(f))\n g=diff(cos(x), x, 2)\n print('#g=',g,type(g))\n print('#f=',f,type(cos))\n #x= x <class 'sympy.core.symbol.Symbol'>\n #f= cos(x) cos\n #g= -cos(x) <class 'sympy.core.mul.Mul'>\n #f= cos(x) <class 'sympy.core.function.FunctionClass'>\n \n```\n\n```\n\n from sympy import *\n var('x y C1 C2')\n eq = Eq(y(x).diff(x, 2) , -y(x))\n g=dsolve(eq)\n h=simplify(g.rhs)\n hh=simplify(g.rhs.diff(x, 1))\n w=solve([h.subs(x,0)-1,hh.subs(x,0)], [C1,C2])\n k=h.subs(C1,w[C1])\n l=k.subs(C2,w[C2])\n print(\"#y(x)=\",l)\n #y(x)= cos(x)\n \n```", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-10T13:24:15.500", "id": "33910", "last_activity_date": "2017-04-10T13:24:15.500", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "17199", "parent_id": "33820", "post_type": "answer", "score": 0 } ]
33820
33821
33821
{ "accepted_answer_id": null, "answer_count": 2, "body": "js初心者です。初歩的な質問かもしれませんがご容赦下さい。\n\nCSVに格納しておいた複数のGoogleCalendarのID情報を読み込んできて、 \nそこからfor分を使ってループ処理をかけて、各カレンダーの情報を取り出す処理を考えました。\n\nなぜかわからないのですが、カレンダー情報は取り出せるのですが、 \nCSVからID情報と付随して取得したランク情報がうまく反映されません。\n\nコールバック関数やdefferを関数で使う形を調べましたが、 \nいまいちしっくりと来ませんでした。\n\nお手数ですが、ご尽力お願い致します。\n\n**問題点:**\n\n実際に出力すると、irankの変数だけ挙動がおかしい。`data.items[0].summary`は特に問題なし。 \n→CSV最終行の文字列(`irank = csvListall[263][5] = b`)の値が全ての`irank`で代入されてしまう。\n\n**今回求める結果:**\n\n```\n\n a +文字列(data.items[0].summaryの結果← i=0のとき\n b +文字列(data.items[0].summaryの結果← i=1のとき\n ss+文字列(data.items[0].summaryの結果← i=2のとき\n c +文字列(data.items[0].summaryの結果← i=3のとき\n b +文字列(data.items[0].summaryの結果← i=4のとき\n ss+文字列(data.items[0].summaryの結果← i=5のとき\n s +文字列(data.items[0].summaryの結果← i=6のとき\n ↓\n 続く...\n \n```\n\n**結果:**\n\n```\n\n b+文字列(data.items[0].summaryの結果← i=0のとき\n b+文字列(data.items[0].summaryの結果← i=1のとき\n b+文字列(data.items[0].summaryの結果← i=2のとき\n b+文字列(data.items[0].summaryの結果← i=3のとき\n b+文字列(data.items[0].summaryの結果← i=4のとき\n b+文字列(data.items[0].summaryの結果← i=5のとき\n b+文字列(data.items[0].summaryの結果← i=6のとき\n ↓\n 続く...\n \n```\n\n```\n\n function Kansu(){\n \n //GOOGL CALEMDAR APIを使う時に必要なトークン\n var apikey = '個人のAPIキー';\n \n //GOOGL CALEMDARで日付関係の処理\n var now = new Date();\n var y = now.getFullYear();\n var m = now.getMonth() + 1;\n var d = now.getDate();\n var w = now.getDay();\n var wd = [\"日\", \"月\", \"火\", \"水\", \"木\", \"金\", \"土\"];\n var h = now.getHours();\n var mi = now.getMinutes();\n var s = now.getSeconds();\n var mm = (\"0\" + m).slice(-2);\n var dd = (\"0\" + d).slice(-2);\n var hh = (\"0\" + h).slice(-2);\n var mmi = (\"0\" + mi).slice(-2);\n var ss = (\"0\" + s).slice(-2);\n \n //GOOGL CALEMDAR明日の日付\n var dmax = now.getDate() + 1;\n var ddmax = (\"0\" + dmax).slice(-2);\n \n //GOOGL CALEMDAR今日~明日の日付\n var timeMin = y + \"-\" + mm + \"-\" + dd + \"T\" + hh + \":\" + mmi + \":\" + ss + \"Z\";\n var timeMax = y + \"-\" + mmmax + \"-\" + dd + \"T\" + hh + \":\" + mmi + \":\" + ss + \"Z\";\n \n \n \n //まずサーバー上のCSVからGoogle Calendarのアドレスを取得\n $.ajax({\n url: 'Google Calendarのアドレスを一覧化した.csv',\n success: function(era) {\n csvListall = $.csv()(era);\n \n //取得したGoogle Calendarのアドレスを1行ずつ総当りでチェック(\n for(var i=0;i<264;i++){\n var calendarId = '';\n var calendarId = csvListall[i][2];\n \n //取得したGoogle Calendarの各アドレスごとにあるランク情報(sss,ss,s,a,b,c)を取得\n var irank = '';\n var irank = csvListall[i][5];\n \n \n \n //$.getJSONにてグーグルカレンダーから情報を取得\n var uri = \"https://www.googleapis.com/calendar/v3/calendars/\" + calendarId + \"/events?key=\" + apikey + \"&timeMin=\" + timeMin + \"&timeMax=\" + timeMax + \"&maxResults=10&orderBy=startTime&singleEvents=true\";\n var jsinfo = uri;\n $.getJSON(jsinfo,\n function(data){\n //取得したsummaryが空じゃない時に実行\n if (data.items[0].summary != \"\"){\n //#imagesに文字列を代入\n $(\"#images\").append(irank + data.items[0].summary);\n }\n });\n }\n }\n });\n }\n \n```\n\n[![画像の説明をここに入力](https://i.stack.imgur.com/m8uFK.png)](https://i.stack.imgur.com/m8uFK.png)", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-06T18:46:53.083", "favorite_count": 0, "id": "33823", "last_activity_date": "2017-06-13T21:43:47.910", "last_edit_date": "2017-04-06T23:51:52.737", "last_editor_user_id": "2238", "owner_user_id": "21411", "post_type": "question", "score": 1, "tags": [ "javascript", "json" ], "title": "CSVから読み込んだデータを元にfor文をつかってgooglecalnedarの情報を取得する", "view_count": 620 }
[ { "body": "`$.getJSON`のコールバック関数`function(data)`で参照している`irank`は別の関数`function(era)`で定義されています。このため、`irank`の状態は`function(era)`が一回実行されるごとに1個確保されます。 \n一方`$.getJSON`はコールバック呼び出しを非同期に呼び出します。ですので`function(era)`で`$.getJSON`が264回呼び出された後に`function(data)`が264回実行され、`irank`の値はすべて264番目の状態となります。\n\n`function(data)`を例えば以下のように書き換えると各呼び出し時の`irank`が保存されるようになるかと思います。\n\n```\n\n (function(irank){\n return function(data) {\n // …\n };\n })(irank)\n \n```", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-06T23:48:50.760", "id": "33825", "last_activity_date": "2017-04-06T23:48:50.760", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "5750", "parent_id": "33823", "post_type": "answer", "score": 2 }, { "body": "原因はpgrhoさんが書かれている通りです。\n\nいつかあなたが絶対に引っかかる、ある一つのJavaScriptの罠 \n<http://qiita.com/ukiuni@github/items/463493a690265cec8bb7>\n\n別解としてfor文を使用せずに、[`jQuery.each()`](http://api.jquery.com/jQuery.each/)や[`Array.prototype.forEach()`](https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach)で配列内(csvListall)の値を1つずつ処理する方法もあります。\n\n`Array.prototype.slice(0,\n264)`で最初の要素から264個だけ処理するようにしていますが、csvListallの要素すべてに対して処理を行うのであれば、このメソッドは不要なので削除してください。\n\n**jQuery.each():**\n\n```\n\n $.ajax({\n url: 'Google Calendarのアドレスを一覧化した.csv',\n success: function (era) {\n csvListall = $.csv()(era);\n \n //取得したGoogle Calendarのアドレスを1行ずつ総当りでチェック\n $.each(csvListall.slice(0, 264), function(index, value){\n var calendarId = value[2];\n \n //取得したGoogle Calendarの各アドレスごとにあるランク情報(sss,ss,s,a,b,c)を取得\n var irank = value[5];\n \n //...\n \n });\n }\n });\n \n```\n\n**Array.prototype.forEach():**\n\n```\n\n $.ajax({\n url: 'Google Calendarのアドレスを一覧化した.csv',\n success: function (era) {\n csvListall = $.csv()(era);\n \n //取得したGoogle Calendarのアドレスを1行ずつ総当りでチェック\n csvListall\n .slice(0, 264)\n .forEach(function(value, index){\n var calendarId = value[2];\n \n //取得したGoogle Calendarの各アドレスごとにあるランク情報(sss,ss,s,a,b,c)を取得\n var irank = value[5];\n \n //...\n \n });\n }\n });\n \n```", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-07T04:12:22.287", "id": "33831", "last_activity_date": "2017-04-07T04:12:22.287", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "3068", "parent_id": "33823", "post_type": "answer", "score": 0 } ]
33823
null
33825
{ "accepted_answer_id": "33827", "answer_count": 3, "body": "掲題の質問です。まだ仕様を完全に理解したわけではないので違う場合はお手数ですが指摘願います。\n\n構造体を初期化するときの仕様として、 \n`struct S v={0};`はメンバ全部初期化されることが保証されてます。 \nまた、`NULL`は0以外でもよくて100でもいい。 \nただし他の関数や変数とぶつかってはならない。 \nただし、数値型に変換するときは0でなければならない。\n\nそのとき、初期化した構造体に含まれるポインタ変数の値と`NULL`を比較したときにどのようなコンパイラでコンパイルしたとしても、一致しますか? \nまた、他のメンバ変数はその場合、ゼロクリアされていることが保証されますか?\n\n```\n\n struct S {\n int val;\n void *ptr;\n int val2;\n }\n \n int main(int argc,char *argv[]){\n struct S v={0};\n printf(\"%d\\n%d\\n\",v.val,v.val2);\n if( v.ptr == NULL) {\n // NULLのときの処理\n }\n }\n \n```\n\nよろしくお願いします。", "comment_count": 2, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-06T23:33:33.347", "favorite_count": 0, "id": "33824", "last_activity_date": "2017-07-21T09:18:25.800", "last_edit_date": "2017-04-07T03:59:57.330", "last_editor_user_id": "13886", "owner_user_id": "13886", "post_type": "question", "score": 5, "tags": [ "c" ], "title": "C言語のポインタ変数を含む構造体初期化について", "view_count": 4365 }
[ { "body": "`0`で初期化される仕様なので、`NULL`にならないだけでは?", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-07T00:18:53.707", "id": "33826", "last_activity_date": "2017-04-07T00:18:53.707", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "4236", "parent_id": "33824", "post_type": "answer", "score": 0 }, { "body": "[c](/questions/tagged/c \"'c' のタグが付いた質問を表示\") 言語規格書 JIS X 3010:2003 6.7.8 初期化\nによると Yes \nこの章、長い上に項目分割番号が振っていないので解説しづらいのですが\n\n * 静的記憶域期間をもつオブジェクトを明示的に初期化しない場合は \na) ポインタ型の場合、空ポインタに初期化する \nb) 算術型の場合、0に初期化する\n\n * (明示的初期化であって) 初期化子が少ない場合、その集成体型の残りを、静的記憶域期間をもつオブジェクトと同じ規則で暗黙に初期化する\n\nと書かれています。\n\n提示例は、メンバ `val` に対する初期化子 `0` が明記され、それ以外のメンバに対する初期化子が無いと解釈されるので、上記のとおりとなります。\n\n> どのようなコンパイラでコンパイルしたとしても、\n\n規格に合致していないコンパイラでは No かもしれません。 \nまあいまどき規格書無視しているコンパイラはかなりレアだと思いますが皆無ではないでしょう。 \nそんな変なコンパイラをプログラマの努力で使うのは労力に引き合わないと思います。\n\nあと補足\n\n> また、NULLは0以外でもよくて100でもいい。\n\nこれは機械語になった後の内部表現の話です。 \n`memset` 等で強引に記憶域に `0` を書き込んだとき、その値が空ポインタの内部表現に一致するかどうかは規定されていません。 \n内部表現に関係なく、ソースコード上では、空ポインタは `NULL` に一致します。", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-07T00:21:27.827", "id": "33827", "last_activity_date": "2017-04-07T00:21:27.827", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "8589", "parent_id": "33824", "post_type": "answer", "score": 10 }, { "body": "C/C++ のナルポインタの仕様は(個人的な感覚では)病的なところがあります。 \nnull pointer constant\nはソース上の表現で、例えば整定数0(コンパイル時に0と定まる整数型式)があります。これがポインタがあるべき場所にあったり、ポインタに変換されると、コンパイラはそれをナルポインタと認識します。 \nnull pointer\nはナルポインタの内部表現のことで、この値がオールビット0であることは保障されていません。他のオブジェクトや関数の参照と異なった値であることが保障されているだけです。 \nNULL マクロは null pointer constant を表すマクロなので、null pointer が0でない場合も整定数 0\nに展開されることになります。 \nC言語では NULL は((void*)0) (これもCのnull pointer\nconstant)に展開されることも多いですが、C++ではこの展開は行われません。C++では(void*)型のポインタを他の型のポインタに変換するときは明示的なキャストが必要になったからです。C++ではnullptrを使うべきでしょう。\n\nで、質問の答えは \nif( v.ptr == NULL) \nは、たとえnull pointer が0でない処理系でも正しく動作します。 \nif( v.ptr == 0) \nでさえ、正しく動作することに注意してください。null pointer (内部表現)が0でなくともこれはv.ptr\nがナルポインタのときに真となるのが仕様です。 \n他のメンバーは正しく0初期化されます。\n\nただし、memsetで構造体をオールビット0にする、などの場合は逆に保証されません。\n\nとはいえ、null pointer が0でない処理系などお目にかかったことがないので、これを理解してもなかなか使い所がないのですが。", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-07-21T09:18:25.800", "id": "36564", "last_activity_date": "2017-07-21T09:18:25.800", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "24517", "parent_id": "33824", "post_type": "answer", "score": 2 } ]
33824
33827
33827
{ "accepted_answer_id": "33832", "answer_count": 3, "body": "TLSで暗号化された通信経路上を流すデータに対して、アプレイケーションのレイヤで更に暗号化を独自にかける場合、それによってかえって保護のレベルがTLS単体よりも低下する可能性はありますか? \nそれとも、少なくともTLSによる保護のレベルまでは保証されますか?\n\nもしTLS単体よりも低下する場合、例えばどのような理由により起こり得るでしょうか?\n\n「SSL/TLSだけだとよく脆弱性問題も起きてて心配だから、自分たちでも暗号化してセキュリティを高めよう」という話が身近にあったのですが、セキュリティ素人のアレンジが本当に有効なのかどうか気になっています。 \n車輪の再発明程度の問題で済むならまだしも、逆効果になってしまっては大変なので・・・", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-07T00:34:16.977", "favorite_count": 0, "id": "33828", "last_activity_date": "2017-04-09T08:56:03.433", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "8078", "post_type": "question", "score": 8, "tags": [ "security", "ssl" ], "title": "暗号化技術の重ねがけが逆効果になるケースは無いか?", "view_count": 443 }
[ { "body": "ネットワークプロトコルスタックと言う言葉があります。ネットワーク的に下の層をそっくり入れ替えても、ネットワーク的に上の層はそのまま動かすことができる、といった意味ですね。\n\nTLS はトランスポート層とアプリケーション層の中間に当たるレイヤにいます。一方で我々、一般的開発者が作るのはアプリケーション層です。 TLS\nはアプリケーションが平文を転送しようが暗号文を転送しようが気にしませんから、その意味で暗号ロジックは独立していると考えてよいでしょう。なので「故意に TLS\nを阻害する」ようなことをしない限り保護レベルが低下することは無いとオイラは考えます。 \n#証明書が不完全です、の警告を無視して継続させるような運用をするとか・・・\n\n効果があるかは別問題ってことで。攻撃者がいるとして、 \n\\- セキュリティ専門家の考えた暗号を解くのに10000の手間がかかるとして、 \n\\- セキュリティ素人の考えた暗号を解くには1の手間しかかからない、 \nかもしれません。逆に \n\\- 広く使われているセキュリティプロトコルの脆弱性が見つかったら多くの攻撃者が興味を持ち \n誰でも簡単に使える攻撃手法が広く公開されるかもしれない \n\\- 1アプリケーションが使っているオレオレ暗号に興味を持つ攻撃者は少ないかもしれない \nなんてこともありそうです。\n\n素人流オレオレ暗号を開発コストかけて実装して、どの程度役に立つかは要検討ですね。 \n最終的には営業的、戦略的判断とかそういうことになりそう。", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-07T02:31:41.727", "id": "33829", "last_activity_date": "2017-04-07T02:31:41.727", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "8589", "parent_id": "33828", "post_type": "answer", "score": 3 }, { "body": "たとえば暗号に対する中間一致攻撃と言うのがあります。\n\n平文→(1段目の暗号化)→1段目の暗号文→(2段目の暗号化)→暗号文、暗号文→(2段目の暗号化の復号)→1段目の暗号分→(1段目の暗号化の復号)→平文、という処理をしてるとして、暗号と復号のプロセスから\n\n * 平文→(1段目の暗号化)→1段目の暗号文\n * 暗号文→(2段目の暗号化の復号)→1段目の暗号文\n\nを取り出します。これを全てのパターンの鍵で試行して、「1段目の暗号文」が一致すればその鍵が正解です。素直に全件探索すると「1段目の試行×2段目の試行」の回数がいるところ、「1段目+2段目」の回数で済むことになります。\n\nともに128bit鍵だとすると、256bit分の強度になるかと思いきや129bit分にしかならない、と言う話です。\n\nまた、暗号の強度はアルゴリズムそのものだけではなく運用にも関わります。\n\n1段目の暗号の運用をきちんと考えないと、2段目が破られたら結局1段目も破られるので意味なし、ということが考えられます。(極端な例を出すと、1段目の鍵をTLSのみで暗号化して送っているとか)\n\nということで「セキュリティを強化したつもりが全然意味なかった」ということは容易に発生しうることになります。\n\nここからは自信が無いのですが、1段目を加えたせいで2段目(TLS)の強度が落ちるようなことがあるかというと、1段目でヘッダなどとして構造化データを付加するとその部分が既知となり攻撃の助けになる、と言う可能性はあるかと思います。とはいっても、普通にTLSを使っていても上位レイヤのヘッダや構造化されたデータはあるので、増えると言っても微々たる物ではないでしょうか。\n\nなんにせよ、本当にこういうことを必要とされているのであれば、専門家に支援してもらうほうが良いです。", "comment_count": 1, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-07T04:59:18.043", "id": "33832", "last_activity_date": "2017-04-07T04:59:18.043", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "5793", "parent_id": "33828", "post_type": "answer", "score": 6 }, { "body": "例えば暗号文を復号するための情報として、固定のヘッダ、あるいは容易に予測できる内容のヘッダを儲けてしまったとする。その固定のヘッダのおかげで既知平文攻撃が可能になるって事はあるかもしれない。", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-09T08:56:03.433", "id": "33882", "last_activity_date": "2017-04-09T08:56:03.433", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "12774", "parent_id": "33828", "post_type": "answer", "score": 2 } ]
33828
33832
33832
{ "accepted_answer_id": "34003", "answer_count": 1, "body": "初心者なので、すごく簡単な質問をしているのかもしてませんが、、、 \n困って質問してみました。\n\nrails でブログを作成中です。 \narticle CRUD処理などの設定はできたのですがリンクの設定に困っています。\n\n例えば、 \n【 localhost---/articles/1 】 \nの記事(url)に直接アクセスできるリンクを作りたい時はどのようにすれば上手くいくでしょうか??", "comment_count": 1, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-07T03:44:49.043", "favorite_count": 0, "id": "33830", "last_activity_date": "2017-04-14T06:29:27.340", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "21416", "post_type": "question", "score": 0, "tags": [ "ruby-on-rails", "ruby" ], "title": "Ruby on Rails-- リンクの設定について", "view_count": 77 }
[ { "body": "現状の実装などがよくわかりませんが、 `localhost:3000/articles/:id` のリンクであれば以下のように `link_to`\nで実現できると思います。\n\n`<%= link_to '詳細', articles_path(@article) %>`", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-14T06:29:27.340", "id": "34003", "last_activity_date": "2017-04-14T06:29:27.340", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "22531", "parent_id": "33830", "post_type": "answer", "score": 0 } ]
33830
34003
34003
{ "accepted_answer_id": "33835", "answer_count": 2, "body": "お世話になります。\n\nタイトルのとおりですが、gemのeventmachineをinstallしようとするとErrorが出てきてInstallができません... \nいろいろ調べたのですが、結局解決できなかったので、ここに質問させていただきます。\n\nなお、rubyのバージョンは2.4.0 \n開発環境はMacBookAirになります。\n\nつぎに下記が実施ログとなります。\n\n```\n\n YourMacBookAir:slackTest userName$ gem install eventmachine\n Building native extensions. This could take a while...\n ERROR: Error installing eventmachine:\n ERROR: Failed to build gem native extension.\n \n current directory: /Users/userName/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/eventmachine-1.2.3/ext\n /Users/userName/.rbenv/versions/2.4.0/bin/ruby -r ./siteconf20170407-37771-1h8lzrd.rb extconf.rb\n checking for -lcrypto... yes\n checking for -lssl... yes\n checking for openssl/ssl.h... yes\n checking for openssl/err.h... yes\n checking for rb_trap_immediate in ruby.h,rubysig.h... no\n checking for rb_thread_blocking_region()... no\n checking for rb_thread_call_without_gvl() in ruby/thread.h... yes\n \n checking for rb_thread_fd_select()... yes\n checking for rb_fdset_t in ruby/intern.h... yes\n checking for rb_wait_for_single_fd()... yes\n checking for rb_enable_interrupt()... no\n checking for rb_time_new()... yes\n checking for inotify_init() in sys/inotify.h... no\n checking for __NR_inotify_init in sys/syscall.h... no\n checking for writev() in sys/uio.h... yes\n checking for pipe2() in unistd.h... no\n checking for accept4() in sys/socket.h... no\n checking for SOCK_CLOEXEC in sys/socket.h... no\n checking for sys/event.h... yes\n checking for sys/queue.h... yes\n checking for clock_gettime()... no\n checking for gethrtime()... no\n CXXFLAGS=$(cxxflags)\n creating Makefile\n \n To see why this extension failed to compile, please check the mkmf.log which can be found here:\n \n /Users/userName/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/extensions/x86_64-darwin-14/2.4.0-static/eventmachine-1.2.3/mkmf.log\n \n current directory: /Users/userName/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/eventmachine-1.2.3/ext\n make \"DESTDIR=\" clean\n \n current directory: /Users/userName/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/eventmachine-1.2.3/ext\n make \"DESTDIR=\"\n compiling binder.cpp\n make: g++-4.2: No such file or directory\n make: *** [binder.o] Error 1\n \n make failed, exit code 2\n \n Gem files will remain installed in /Users/userName/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/eventmachine-1.2.3 for inspection.\n Results logged to /Users/userName/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/extensions/x86_64-darwin-14/2.4.0-static/eventmachine-1.2.3\n /gem_make.out\n \n```\n\n次にg++とgccのバージョンをコマンドにて確認した結果になります。\n\n```\n\n YourMacBookAir:slackTest userName$ gcc -v\n Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/usr/include/c++/4.2.1\n Apple LLVM version 7.0.2 (clang-700.1.81)\n Target: x86_64-apple-darwin14.5.0\n Thread model: posix\n \n \n YourMacBookAir:slackTest userName$ g++ -v\n Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/usr/include/c++/4.2.1\n Apple LLVM version 7.0.2 (clang-700.1.81)\n Target: x86_64-apple-darwin14.5.0\n Thread model: posix\n \n```\n\nエラーメッセージに`make: g++-4.2: No such file or\ndirectory`とありましたので、g++あたりに問題があるのかと思いますが、具体的な解決方法がわからず困っております。\n\n他に必要な情報や実行結果などありましたら、連絡いただければ記載いたします。\n\nお手数ですが、解決策のわかる方ご教授いただければ助かります。\n\n追記、質問に対してコマンドの実施結果になります。\n\n```\n\n YourMacBookAir:slackTest userName$ type g++-4.2\n -bash: type: g++-4.2: not found\n YourMacBookAir:slackTest userName$ type ruby\n ruby is /Users/takatakentarou/.rbenv/shims/ruby\n \n```", "comment_count": 2, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-07T05:03:23.033", "favorite_count": 0, "id": "33833", "last_activity_date": "2017-04-07T17:43:15.047", "last_edit_date": "2017-04-07T17:43:15.047", "last_editor_user_id": "20774", "owner_user_id": "20774", "post_type": "question", "score": 1, "tags": [ "ruby", "rubygems" ], "title": "gem install eventmachineで失敗する", "view_count": 1354 }
[ { "body": "Tone0929さんのMacにインストールされている`g++`はバージョン4.2.1のようなので、無理やり`g++-4.2`というファイルを`g++`への[シンボリックリンク](https://ja.wikipedia.org/wiki/%E3%82%BD%E3%83%95%E3%83%88%E3%83%AA%E3%83%B3%E3%82%AF)として作成してやれば解決しそうです。\n\n```\n\n $ sudo ln -s /usr/bin/g++ /usr/bin/g++-4.2\n \n```\n\nただし`g++`のバージョンが上がってしまうとこれは正しくないので、注意してください。その場合はたとえば`g++-4.2`を独立したバイナリとして用意すると解決するでしょう(そのためにはg++の特定のバージョンをインストールする必要があるはずです)。\n\n * 参考 \n * [\"getting eventmachine gem to compile on OSX Lion 10.8.2 with xcode 4.5.1\"](https://stackoverflow.com/questions/12908484/getting-eventmachine-gem-to-compile-on-osx-lion-10-8-2-with-xcode-4-5-1) \\-- Stack Overflow\n * [「普段どうやってエラーメッセージから問題を解決しているか?」](http://nilfs.hatenablog.jp/entry/2015/06/17/175246) …… 記事中で解説されているエラーが今回のものと同一です。", "comment_count": 1, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-07T07:33:13.190", "id": "33835", "last_activity_date": "2017-04-07T07:33:13.190", "last_edit_date": "2017-05-23T12:38:56.083", "last_editor_user_id": "-1", "owner_user_id": "19110", "parent_id": "33833", "post_type": "answer", "score": 1 }, { "body": "(Tone0929さんの解決にはならないかもしれませんが、回答の集積を意識し、ここに書き残しておきます)\n\neventmachineのGitHub上のレポジトリで、OS X 10.11上で同じエラー`make: /usr/bin/g++-4.2: No such\nfile or directory`を出しているissueを見つけました。\n\nこれによると、「古いOS\nXの際にrbenv経由でインストールしたRubyが`g++-4.2`に依存していた。`.rbenv/`を消してRubyとgemを再インストールすると問題が解決した」そうです。\n\n参考: [\"Can't install on OS X\n10.11\"](https://github.com/eventmachine/eventmachine/issues/677) \\-- GitHub", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-07T07:35:29.553", "id": "33836", "last_activity_date": "2017-04-07T07:35:29.553", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "19110", "parent_id": "33833", "post_type": "answer", "score": 1 } ]
33833
33835
33835
{ "accepted_answer_id": null, "answer_count": 1, "body": "現在は写真を撮ってimageviewに表示するに止まっています。この写真をiCloudにアップして、imageCopyにダウンロードしたいのですが、写真のアップ/ダウンの方法がわかりません。 \n宜しくお願いいたします。\n\n```\n\n //\n // AppDelegate.swift\n //\n import UIKit\n \n @UIApplicationMain\n class AppDelegate: UIResponder, UIApplicationDelegate {\n var window: UIWindow? //ウィンドウ\n \n //アプリ起動完了時に呼ばれる\n func application(_ application: UIApplication,\n didFinishLaunchingWithOptions\n launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {\n return true\n }\n }\n \n \n \n コードをここに入力\n //\n // ViewController.swift\n //\n \n \n import UIKit\n \n //iCloud\n class ViewController: UIViewController, UITextFieldDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {\n //定数\n let BTN_WRITE1 = 2 //書き込み1\n let BTN_READ1 = 3 //読み込み1\n \n //変数\n var _textField1: UITextField! //テキストフィールド1\n var _textField3: UITextField! //テキストフィールド2\n \n @IBOutlet weak var imageView: UIImageView!\n \n @IBOutlet weak var imageCopy: UIImageView!\n \n @IBAction func launchCamera(_ sender: UIBarButtonItem) {\n let camera = UIImagePickerControllerSourceType.camera\n \n if UIImagePickerController.isSourceTypeAvailable(camera) {\n let picker = UIImagePickerController()\n picker.sourceType = camera\n picker.delegate = self\n self.present(picker,animated: true)\n }\n }\n \n func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {\n let image = info[UIImagePickerControllerOriginalImage] as! UIImage\n self.imageView.image = image\n UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)\n self.dismiss(animated: true)\n }\n \n \n //====================\n //UI\n //====================\n //ロード完了時に呼ばれる\n override func viewDidLoad() {\n super.viewDidLoad()\n \n let dx: CGFloat = (UIScreen.main.bounds.size.width-320)/2\n \n \n //ドキュメントのUIの生成\n _textField1 = makeTextField(CGRect(x: dx+10, y: 140, width: 200, height: 32), text: \"\")\n self.view.addSubview(_textField1)\n let btnWrite1 = makeButton(CGRect(x: dx+10, y: 190, width: 190, height: 40),\n text: \"ドキュメントの書き込み\", tag: BTN_WRITE1)\n self.view.addSubview(btnWrite1)\n let btnRead1 = makeButton(CGRect(x: dx+210, y: 190, width: 90, height: 40),\n text: \"読み込み\", tag: BTN_READ1)\n self.view.addSubview(btnRead1)\n }\n \n //ボタンクリック時に呼ばれる\n func onClick(_ sender: UIButton) {\n if sender.tag == BTN_WRITE1 {\n DispatchQueue.global().async(execute: {\n let icloudURL = self.makeICloudURL(\"img_test\")\n DispatchQueue.main.async(execute: {\n if icloudURL != nil {\n self.writeICloud1(icloudURL!)\n } else {\n self.showAlert(\"エラー\", text: \"iCloudのURLの取得に失敗\")\n }\n })\n })\n } else if sender.tag == BTN_READ1 {\n DispatchQueue.global().async(execute: {\n let icloudURL = self.makeICloudURL(\"img_test\")\n DispatchQueue.main.async(execute: {\n if icloudURL != nil {\n self.readICloud1(icloudURL!)\n } else {\n self.showAlert(\"エラー\", text: \"iCloudのURLの取得に失敗\")\n }\n })\n })\n }\n }\n \n //テキストフィールドの初期化\n func makeTextField(_ frame: CGRect, text: String) -> UITextField {\n let textField = UITextField()\n textField.frame = frame\n textField.text = text\n textField.borderStyle = UITextBorderStyle.roundedRect\n textField.keyboardType = UIKeyboardType.default\n textField.returnKeyType = UIReturnKeyType.done\n textField.delegate = self\n return textField\n }\n \n //テキストボタンの初期化\n func makeButton(_ frame: CGRect, text: String, tag: Int) -> UIButton {\n let button = UIButton(type: UIButtonType.system)\n button.frame = frame\n button.setTitle(text, for: UIControlState())\n button.tag = tag\n button.addTarget(self, action: #selector(onClick(_:)),\n for: UIControlEvents.touchUpInside)\n return button\n }\n \n //アラートの表示\n func showAlert(_ title: String?, text: String?) {\n let alert = UIAlertController(title: title, message: text,\n preferredStyle: UIAlertControllerStyle.alert)\n alert.addAction(UIAlertAction(title: \"OK\",\n style: UIAlertActionStyle.default, handler: nil))\n self.present(alert, animated: true, completion: nil)\n }\n \n //====================\n //iCloud\n //====================\n \n //iCloudのドキュメントのURLの生成(3)\n func makeICloudURL(_ fileName: String) -> URL? {\n //iCloudのディレクトリのURLの生成\n let fileManager = FileManager.default\n let icloudURL = fileManager.url(forUbiquityContainerIdentifier: nil)\n if let docURL = icloudURL?.appendingPathComponent(\"Documents\") {\n //ディレクトリがない時は生成\n if fileManager.fileExists(atPath: docURL.path) == false {\n do {\n try fileManager.createDirectory(at: docURL,\n withIntermediateDirectories: true,\n attributes: nil)\n } catch _ {\n }\n }\n \n //iCloudのドキュメントのURLを返す\n return docURL.appendingPathComponent(fileName)\n }\n return nil\n }\n \n //iCloudへのドキュメントの書き込み(4)\n func writeICloud1(_ icloudURL: URL) {\n let document = ICloudDocument(fileURL: icloudURL)\n \n document.text = _textField1.text!\n document.save(to: icloudURL,\n for: UIDocumentSaveOperation.forCreating,\n completionHandler: {(success: Bool) in\n print(\"write document>\\(success)\")\n })\n }\n \n //iCloudからのドキュメントの読み込み(5)\n func readICloud1(_ icloudURL: URL) {\n let document = ICloudDocument(fileURL: icloudURL)\n document.open(completionHandler: {(success: Bool) in\n print(\"read document>\\(success)\")\n self._textField1.text = document.text\n })\n }\n \n //====================\n //UITextFieldDelegate\n //====================\n //改行ボタン押下時に呼ばれる\n func textFieldShouldReturn(_ sender: UITextField) -> Bool {\n //キーボードを閉じる\n self.view.endEditing(true)\n return true\n }\n }\n \n \n コードをここに入力\n //\n // ICloudDocument.swift\n //\n \n import UIKit\n \n //ドキュメント\n class ICloudDocument: UIDocument {\n var text = \"\" //テキスト\n \n //ドキュメント読み込み時に呼ばれる(6)\n override func load(fromContents contents: Any, ofType: String?) throws {\n self.text = (NSString(data: contents as! Data,\n encoding: String.Encoding.utf8.rawValue) as String?)!\n }\n \n //ドキュメント書き込み時に呼ばれる(7)\n override func contents(forType typeName: String) throws -> Any {\n if let value = self.text.data(using: String.Encoding.utf8) {\n return value\n }\n return Data()\n }\n }\n \n```\n\n[![iCloudの設定](https://i.stack.imgur.com/YVN2t.png)](https://i.stack.imgur.com/YVN2t.png)\n\n[![cameraの設定](https://i.stack.imgur.com/3zhtK.png)](https://i.stack.imgur.com/3zhtK.png)", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-07T05:52:22.847", "favorite_count": 0, "id": "33834", "last_activity_date": "2022-12-27T12:01:15.143", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "9173", "post_type": "question", "score": 2, "tags": [ "swift", "ios", "xcode" ], "title": "あるアプリで撮った写真をiCloudにアップロード/ダウンロードしたい", "view_count": 480 }
[ { "body": "WebAPIのようなものはないか?というご質問でしょうか?\n\n当方iCloudは使用したことがないので、単なるWebCrawlの結果となりますがCloudKitというライブラリがあるようです。 \n<https://developer.apple.com/reference/cloudkit>", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-09T14:11:47.993", "id": "33888", "last_activity_date": "2017-04-09T14:11:47.993", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "19716", "parent_id": "33834", "post_type": "answer", "score": 0 } ]
33834
null
33888
{ "accepted_answer_id": null, "answer_count": 0, "body": "UIWebViewからWkWebViewでの移行で、それまではUIWebViewではURLProtocolを用いて、Webページの広告をブロックしていましたが、WkWebViewではそれが動きません。そこで、WkWebViewの設定で下記のようにJavaScript自体をoffにして、広告ブロックすることが出来ました。しかしながら、広告をブロックするためにJavaScript自体をoffにするのは、少し乱暴な気がします。\n\n```\n\n let preferences = WKPreferences()\n preferences.javaScriptEnabled = false // javascriptをoffにする。\n let configuration = WKWebViewConfiguration()\n configuration.preferences = preferences\n \n```\n\nそこで、調べた結果下記のユーザースクリプトを使って、JavaScriptを実行して広告をoffにすることができることがわかりました。\n\n```\n\n let userScript1 = WKUserScript(source: \"\", injectionTime: .atDocumentEnd, forMainFrameOnly: true)\n \n let controller = WKUserContentController()\n controller.addUserScript(userScript1)\n \n let configuration = WKWebViewConfiguration()\n configuration.userContentController = controller\n \n```\n\nWKUserScriptのsource部分にどのようなJavaScriptを書けば広告をブロックすることが出来るかを教えて下さい。また、これらの方法以外に良い広告ブロック方法を教えて頂けると助かります。", "comment_count": 2, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-07T08:19:16.780", "favorite_count": 0, "id": "33837", "last_activity_date": "2017-04-07T08:19:16.780", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "21189", "post_type": "question", "score": 0, "tags": [ "javascript", "swift", "ios" ], "title": "WkWebViewの広告ブロックについて", "view_count": 598 }
[]
33837
null
null
{ "accepted_answer_id": "56227", "answer_count": 1, "body": "[ikesyo/Himotoki: A type-safe JSON decoding library purely written in\nSwift](https://github.com/ikesyo/Himotoki)\n\n引用:\n\n```\n\n static func decode(_ e: Extractor) throws -> Group {\n return try Group(\n name: e <| \"name\",\n floor: e <| \"floor\",\n locationName: e <| [ \"location\", \"name\" ], // Parse nested objects\n optional: e <||? \"optional\" // Parse optional arrays of values\n )\n \n```\n\nに出てくる `<|` は、なんでしょうか? 上手く検索にひっかりません。", "comment_count": 3, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-07T14:28:41.490", "favorite_count": 0, "id": "33843", "last_activity_date": "2019-06-29T09:14:59.713", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "9008", "post_type": "question", "score": 0, "tags": [ "swift" ], "title": "swiftの <| 記法", "view_count": 133 }
[ { "body": "[swiftの <|\n記法](https://ja.stackoverflow.com/questions/33843/swift%E3%81%AE-%E8%A8%98%E6%B3%95#comment33322_33843)\n\nコメントに頂いた通り、自前で定義したものです。\n\n<https://github.com/ikesyo/Himotoki/blob/master/Sources/Operators.swift#L9>", "comment_count": 0, "content_license": "CC BY-SA 4.0", "creation_date": "2019-06-29T09:14:59.713", "id": "56227", "last_activity_date": "2019-06-29T09:14:59.713", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "9008", "parent_id": "33843", "post_type": "answer", "score": 1 } ]
33843
56227
56227
{ "accepted_answer_id": null, "answer_count": 1, "body": "Ruby on Rails4でアプリ開発しています。\n\n今回、画像アップロード機能を実装するためcarriewaveを導入しました。\n\n画像アップロードはブログ機能につけて、ブログ記事と画像(任意)で投稿できるようにしました。\n\n投稿の際はnew→confirm→cretaeと遷移して確認画面を経由して投稿できるようにしました。\n\n**問題点** \n画像は任意で登録できるようにしたいのですが、画像をアップロードしない場合にエラーになってしまいます。\n\n```\n\n # エラーメッセージ\n CarrierWave::InvalidParameter at /topics\n invalid cache id\n \n```\n\n画像をアップロードする際は正常に動きます。\n\n現在コードはこのように記述しています。\n\n`_form.html.erb`\n\n```\n\n #省略\n <%= f.label :アップロード写真 %>\n <%= f.file_field :photo %>\n <%= f.hidden_field :photo_cache %>\n #省略\n \n```\n\n`confirm.html.erb`\n\n```\n\n #省略\n <%= image_tag (@topic.photo.url) if @topic.photo.present? %>\n <%= hidden_field_tag :\"cache[photo]\", @topic.photo.cache_name %>\n #省略\n \n```\n\n`topics_controller`\n\n```\n\n class TopicsController < ApplicationController\n \n def new\n if params[:back]\n @topic = Topic.new(topics_params)\n else\n @topic = Topic.new\n end\n end\n \n def create\n @topic = Topic.new(topics_params)\n @topic.photo.retrieve_from_cache! params[:cache][:photo]\n @topic.save!\n @topic.user_id = current_user.id\n \n respond_to do |format|\n if @topic.save\n format.html { redirect_to @topic, notice: '投稿しました!' }\n format.json { render :show, status: :created, location: @topic }\n else\n format.html { render :new }\n format.json { render json: @topic.errors, status: :unprocessable_entity }\n end\n end\n end\n \n \n def confirm\n @topic = Topic.new(topics_params)\n render :new if @topic.invalid?\n end\n \n # 一部省略\n \n \n private\n def topics_params\n params.require(:topic).permit(:title, :content, :photo_cache, :photo, :tag_list)\n end\n \n def set_topic\n @topic = Topic.find(params[:id])\n end\n end\n \n```\n\nどのように修正すればいいかご教授お願いします。\n\n・追記 \nエラー時のログはこのようになっています。\n\n```\n\n Started POST \"/topics\" for ::1 at 2017-04-09 14:16:58 +0900\n Processing by TopicsController#create as HTML\n Parameters: {\"utf8\"=>\"✓\", \"authenticity_token\"=>\"3YIrH2Y/s/011pnlah8L6LFvGGdDzUmIFhxw28WvHDHG04r8DLH4taSgS+WIhUPAFapQrDZP1YzWcGWQgXv95Q==\", \"topic\"=>{\"title\"=>\"hoge\", \"content\"=>\"hoge\", \"tag_list\"=>\"huga\"}, \"cache\"=>{\"photo\"=>\"\"}, \"commit\"=>\"投稿する\"}\n User Load (0.3ms) SELECT \"users\".* FROM \"users\" WHERE \"users\".\"id\" = $1 ORDER BY \"users\".\"id\" ASC LIMIT 1 [[\"id\", 3]]\n (0.2ms) SELECT COUNT(*) FROM \"notifications\" WHERE \"notifications\".\"user_id\" = $1 AND \"notifications\".\"read\" = $2 [[\"user_id\", 3], [\"read\", \"f\"]]\n Completed 500 Internal Server Error in 7ms (ActiveRecord: 0.5ms)\n \n CarrierWave::InvalidParameter - invalid cache id:\n carrierwave (1.0.0) lib/carrierwave/uploader/cache.rb:193:in `cache_id='\n carrierwave (1.0.0) lib/carrierwave/uploader/cache.rb:158:in `block in retrieve_from_cache!'\n carrierwave (1.0.0) lib/carrierwave/uploader/callbacks.rb:15:in `with_callbacks'\n carrierwave (1.0.0) lib/carrierwave/uploader/cache.rb:157:in `retrieve_from_cache!'\n app/controllers/topics_controller.rb:31:in `create'\n actionpack (4.2.3) lib/action_controller/metal/implicit_render.rb:4:in `send_action'\n ・・・\n # 省略\n \n```", "comment_count": 3, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-07T14:40:19.527", "favorite_count": 0, "id": "33844", "last_activity_date": "2020-03-18T04:04:35.630", "last_edit_date": "2017-04-09T05:24:44.243", "last_editor_user_id": "21311", "owner_user_id": "21311", "post_type": "question", "score": -1, "tags": [ "ruby-on-rails", "ruby", "rubygems" ], "title": "Railsでcarriewaveを使用して画像をアップロードする", "view_count": 1361 }
[ { "body": "下記のような形で画像がある時だけ処理を加えてやるのではダメなのでしょうか?\n\n`@topic.photo.retrieve_from_cache! params[:cache][:photo] if\nparams[:cache][:photo].present?`", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-11-09T05:00:38.577", "id": "39442", "last_activity_date": "2017-11-09T05:00:38.577", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "26116", "parent_id": "33844", "post_type": "answer", "score": 0 } ]
33844
null
39442
{ "accepted_answer_id": "33846", "answer_count": 1, "body": "Vagrant + VirtualBox で、 ubuntu (`ubuntu/trusty64`) をインストールしました。\n\nこの box を `vagrant up` した際に作成される VM のルートボリュームのサイズは 40G\nです。これはいろいろと物足りないので、拡張したいと考えました。\n\nこれを実現する方法はありますか?", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-07T15:00:00.387", "favorite_count": 0, "id": "33845", "last_activity_date": "2017-07-13T07:56:39.163", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "754", "post_type": "question", "score": 0, "tags": [ "ubuntu", "vagrant", "virtualbox" ], "title": "ubuntu/trusty64 から立ち上げた VM の容量を拡張するには?", "view_count": 203 }
[ { "body": "以下の手順でできます。\n\n※はじめにバックアップ (`vagrant package`) をとっておくことを推奨します。\n\n### VM の場所などを特定する\n\n以下で特定できます。\n\n```\n\n # vm の一覧を表示\n VBoxManage list vms\n \n # 上で表示された vm のうち、詳細を見たい vm を指定。\n # SATAControler: みたいなものが、下記で使う仮想ディスクへのパス\n VBoxManage showvminfo ubuntu64_default_1491551785012_65723\n \n```\n\n### vmdk を vdi に変換し、サイズを変更する。\n\nvmdk はボリュームのリサイズが (少なくとも VirtualBox からでは)できないので、まず vdi 形式に変換します。\n\n```\n\n # 上で特定した VM のディレクトリに移動する。\n cd ${vm_dir} # e.g. ~/VirtualBox VMs/ubuntu64_default_1491551785012_65723/\n \n # ディスク情報を確認\n VBoxManage showhdinfo ./box-disk1.vmdk\n # ディスクフォーマットを変換しながら clone\n VBoxManage clonehd ./box-disk1.vmdk clone-disk1.vdi --format vdi\n # ディスクをリサイズ (81920MB == 80G)\n VBoxManage modifyhd ./clone-disk1.vdi --resize 81920\n \n```\n\n### ディスクをアタッチする\n\nここの作業は、VM のストレージ設定がどのような構成になっているかに依存します。 \nポイントは、もともとのボリュームファイルを新しいボリュームファイル置き換えるように、設定すること。\n\n基本的に GUI から操作してこの設定は達成できる様子です。\n\n```\n\n # 今回作業していた VM では、 SATA コントローラーからルートボリュームだけがアタッチされている構成であった。\n # この場合は以下のコマンドで実行可能。\n # vm_name: e.g. ubuntu64_default_1491551785012_65723\n VBoxManage storageattach ${vm_name} --storagectl \"SATAController\" --port 0 --device 0 --type hdd --medium clone-disk1.vdi\n \n # 確認\n VBoxManage showhdinfo ./clone-disk1.vdi\n \n```\n\n### VM を再起動する\n\n```\n\n cd ${vagrantfile_folder}\n vagrant up\n \n```", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-07T15:00:00.387", "id": "33846", "last_activity_date": "2017-07-13T07:56:39.163", "last_edit_date": "2017-07-13T07:56:39.163", "last_editor_user_id": "754", "owner_user_id": "754", "parent_id": "33845", "post_type": "answer", "score": 1 } ]
33845
33846
33846
{ "accepted_answer_id": null, "answer_count": 1, "body": "下記のコードは、誕生日が来たらメッセージが表示され、誕生日が過ぎたら次の誕生日まで \nデジタル時計が表示されるように設定されています。 \nこれを、誕生日が来たら1分ごとにメッセージをa)とb)に切り替えるようにするには、 \nどうすればいいでしょうか。 \n偶数の分(〇%2==0)と奇数の分(〇%2==0+1)をうまく入れられません。\n\na) 偶数の分のメッセージ: 金さん銀さん 〇歳の誕生日おめでとう!!!!! \nb) 奇数の分のメッセージ: 後で、プレゼントを送ります☆\n\n```\n\n <!DOCTYPE html>\n <html lang=\"ja\">\n <head>\n <meta http-equiv=\"Content-type\" content=\"text/html; charset=Shift_JIS\">\n <meta http-equiv=\"Content-Script-Type\" content=\"text/javascript\">\n <meta http-equiv=\"Content-Style-Type\" content=\"text/css\">\n <title></title>\n \n \n <style type=\"text/css\">\n \n /* Circle Text Styles */\n #myText {\n font-style: italic;\n font-weight: bold;\n font-family: 'comic sans ms', verdana, arial;\n color: gold;\n \n position: absolute;top: 0;left: 0;z-index: 3000;cursor: default;}\n #myText div {position: relative;}\n #myText div div {position: absolute;top: 0;left: 0;text-align: center;}\n /* End Required */\n /* End Circle Text Styles */\n </style>\n \n <script type=\"text/javascript\">\n <!--\n \n ;(function(){\n \n var birthday = new Date(1917, 3, 8);\n var isBirthDay = false;\n \n if((new Date().getMonth() == birthday.getMonth()) && (new Date().getDate() == birthday.getDate())) {\n var age = new Date().getYear()- birthday.getYear();\n var msg=\"金さん銀さん\"+\" \"+age+\"歳\"+\"の誕生日\"+\" \"+\"おめでとう!!!!!\";\n isBirthDay = true;\n \n } else {\n var ti = new Date;\n \n var Hour = ti.getHours();\n var Min = ti.getMinutes();\n var Sec = ti.getSeconds();\n \n if(Hour <= 9) { \n Hour = \"\\u0020\\u0020\" + Hour; \n } \n     if(Min <= 9) { \n Min = \"0\" + Min; \n }\n if(Sec <= 9) { \n Sec = \"0\" + Sec; \n }\n \n var msg = Hour + \":\" + Min + \":\" + Sec ;\n }\n \n var size = 24;\n \n var circleY = 0.75; var circleX = 2;\n \n var letter_spacing = 5;\n \n var diameter = 10;\n \n var rotation = 0.4;\n var speed = 0.3;\n \n \n if (!window.addEventListener && !window.attachEvent || !document.createElement) return;\n \n msg = msg.split('');\n var n = msg.length - 1, a = Math.round(size * diameter * 0.208333), currStep = 20,\n ymouse = a * circleY + 20, xmouse = a * circleX + 20, y = [], x = [], Y = [], X = [],\n o = document.createElement('div'), oi = document.createElement('div'),\n b = document.compatMode && document.compatMode != \"BackCompat\"? document.documentElement : document.body,\n \n mouse = function(e){\n e = e || window.event;\n ymouse = !isNaN(e.pageY)? e.pageY : e.clientY; // y-position\n xmouse = !isNaN(e.pageX)? e.pageX : e.clientX; // x-position\n },\n \n makecircle = function(){ // rotation/positioning\n if(init.nopy){\n o.style.top = (b || document.body).scrollTop + 'px';\n o.style.left = (b || document.body).scrollLeft + 'px';\n };\n currStep -= rotation;\n for (var d, i = n; i > -1; --i){ // makes the circle\n d = document.getElementById('iemsg' + i).style;\n d.top = Math.round(y[i] + a * Math.sin((currStep + i) / letter_spacing) * circleY - 15) + 'px';\n d.left = Math.round(x[i] + a * Math.cos((currStep + i) / letter_spacing) * circleX) + 'px';\n };\n },\n \n drag = function(){ // makes the resistance\n \n var birthday = new Date(1917, 3, 8);\n var isBirthDay = false;\n \n if((new Date().getMonth() == birthday.getMonth()) && (new Date().getDate() == birthday.getDate())) {\n var age = new Date().getYear()- birthday.getYear();\n var msg=\"金さん銀さん\"+\" \"+age+\"歳\"+\"の誕生日\"+\" \"+\"おめでとう!!!!!\";\n isBirthDay = true;\n \n } else {\n \n var ti = new Date;\n \n var Hour = ti.getHours();\n var Min = ti.getMinutes();\n var Sec = ti.getSeconds();\n \n if(Hour <= 9) { \n Hour = \"\\u0020\\u0020\" + Hour; \n } \n     if(Min <= 9) { \n Min = \"0\" + Min; \n }\n if(Sec <= 9) { \n Sec = \"0\" + Sec; \n }\n \n var msg = Hour + \":\" + Min + \":\" + Sec ;\n }\n \n msg = msg.split('');\n var n = msg.length - 1;\n for (var d, i = n; i > -1; --i)\n {\n var elm = document.getElementById('iemsg' + i);\n elm.innerHTML = msg[i];\n };\n \n y[0] = Y[0] += (ymouse - Y[0]) * speed;\n x[0] = X[0] += (xmouse - 20 - X[0]) * speed;\n for (var i = n; i > 0; --i){\n y[i] = Y[i] += (y[i-1] - Y[i]) * speed;\n x[i] = X[i] += (x[i-1] - X[i]) * speed;\n };\n makecircle();\n },\n \n init = function(){ // appends message divs, & sets initial values for positioning arrays\n if(!isNaN(window.pageYOffset)){\n ymouse += window.pageYOffset;\n xmouse += window.pageXOffset;\n } else init.nopy = true;\n for (var d, i = n; i > -1; --i){\n d = document.createElement('div'); d.id = 'iemsg' + i;\n d.style.height = d.style.width = a + 'px';\n d.appendChild(document.createTextNode(msg[i]));\n oi.appendChild(d); y[i] = x[i] = Y[i] = X[i] = 0;\n };\n o.appendChild(oi); document.body.appendChild(o);\n setInterval(drag, 25);\n },\n \n ascroll = function(){\n ymouse += window.pageYOffset;\n xmouse += window.pageXOffset;\n window.removeEventListener('scroll', ascroll, false);\n };\n \n o.id = 'myText'; o.style.fontSize = size + 'px';\n \n if (window.addEventListener){\n window.addEventListener('load', init, false);\n document.addEventListener('mouseover', mouse, false);\n document.addEventListener('mousemove', mouse, false);\n if (/Apple/.test(navigator.vendor))\n window.addEventListener('scroll', ascroll, false);\n }\n else if (window.attachEvent){\n window.attachEvent('onload', init);\n document.attachEvent('onmousemove', mouse);\n };\n \n })();\n \n // -->\n </script>\n \n </head>\n \n <body bgcolor=\"black\">\n \n </body>\n </html>\n \n```\n\n追記)以下のコードできちんと分離されるはずですが、elseの表示(奇数の分の場合)のとき、 \nifの表示と合併されて表示されます。理由が分かる方は、教えていただけませんか。\n\n```\n\n ~中略~\n var birthday = new Date(1917, 3, 8);\n var isBirthDay = false;\n \n if((new Date().getMonth() == birthday.getMonth()) && (new Date().getDate() == birthday.getDate())){\n \n var date = new Date;\n var minutes = date.getMinutes();\n var isBirthDay = true;\n \n if(minutes%2==0){\n \n var age = new Date().getYear()- birthday.getYear();\n var msg=\"金さん銀さん\"+\" \"+age+\"歳\"+\"の誕生日\"+\" \"+\"おめでとう!!!!!\"+\" \";\n \n } else {\n \n var ti = new Date;\n \n var Hour = ti.getHours();\n var Min = ti.getMinutes();\n var Sec = ti.getSeconds();\n \n if(Hour <= 9) { \n Hour = \"\\u0020\\u0020\" + Hour; \n } \n     if(Min <= 9) { \n Min = \"0\" + Min; \n }\n if(Sec <= 9) { \n Sec = \"0\" + Sec; \n }\n \n var msg = Hour + \":\" + Min + \":\" + Sec ;\n \n }\n }\n ~中略~\n \n```", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-07T15:56:26.990", "favorite_count": 0, "id": "33847", "last_activity_date": "2017-04-08T13:54:48.333", "last_edit_date": "2017-04-08T10:27:28.913", "last_editor_user_id": "20431", "owner_user_id": "20431", "post_type": "question", "score": -2, "tags": [ "javascript" ], "title": "誕生日が来たら、1分ごとにメッセージを切り替える記述の仕方", "view_count": 153 }
[ { "body": "いずれのIFも既に質問者様内のコードにて使用されているので、回答のポイントがずれているかもしれませんが。\n\n```\n\n var date = dt.getDate();\n var minutes = dt.getMinutes();\n \n```\n\nで分が取得できますので \nminutes%2==0で判定すればよいかと思います。\n\nページアクセス時の初期メッセージを切り替えるということではなく、 \nユーザーがページに1分以上とどまった際にメッセージを切り替えるということであれば\n\n```\n\n var handler = function(){\n //メッセージ切り替え処理\n } \n setInterval(handler, 60000);\n \n```\n\nで定期実行されます。\n\n* * *\n\n殴り書きコードですが、下記で試したらば動作いたしました。 \n「きちんと機能しませんでした」とは具体的にどういう症状になっているのでしょうか? \n各ブラウザには検証ツールがついておりますので、Consoleのエラーログ等でご教示頂けると皆さん回答しやすいかと思います。\n\n```\n\n <script type=\"text/javascript\">\n changeMsg = function () {\n var date = new Date;\n var minutes = date.getMinutes();\n var elm = document.getElementById(\"text\");\n if(minutes%2==0){\n \n //前処理省略のため一旦除外 var age = new Date().getYear()- birthday.getYear();\n var age = \"dummy\"\n var msg=\"金さん銀さん\"+\" \"+age+\"歳\"+\"の誕生日\"+\" \"+\"おめでとう!!!!!\"+\" \";\n \n } else {\n \n var ti = new Date;\n var Hour = ti.getHours();\n var Min = ti.getMinutes();\n var Sec = ti.getSeconds();\n \n if(Hour <= 9) { \n Hour = \"\\u0020\\u0020\" + Hour; \n }\n if(Min <= 9) { \n Min = \"0\" + Min; \n }\n if(Sec <= 9) { \n Sec = \"0\" + Sec; \n }\n var msg = Hour + \":\" + Min + \":\" + Sec ;\n \n }\n elm.firstChild.nodeValue =msg\n setInterval(changeMsg,1000);\n }\n window.onload = changeMsg;\n \n </script>\n <body>\n <p id=\"text\">test</p>\n </body>\n \n```", "comment_count": 5, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-08T07:14:30.317", "id": "33861", "last_activity_date": "2017-04-08T13:54:48.333", "last_edit_date": "2017-04-08T13:54:48.333", "last_editor_user_id": "19716", "owner_user_id": "19716", "parent_id": "33847", "post_type": "answer", "score": 1 } ]
33847
null
33861
{ "accepted_answer_id": null, "answer_count": 1, "body": "下記参考URLをもとに、word2vecを動かしてみたいと思いました。 \n以下train.py,similars.pyのファイル、作業手順は全てこのサイトからの転用です。\n\n# 作業手順\n\nmecabで青空文庫のファイルを分かち書きしたのち、以下のファイルで学習させました。 \n生成したmodelはdata22.modelとして保存。\n\ntrain.py\n\n```\n\n -*- coding: utf-8 -*-\n \n from gensim.models import word2vec\n import logging\n import sys\n \n logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', \n level=logging.INFO)\n \n sentences = word2vec.LineSentence(sys.argv[1])\n model = word2vec.Word2Vec(sentences,\n sg=1,\n size=100,\n min_count=1,\n window=10,\n hs=1,\n negative=0)\n model.save(sys.argv[2])\n \n```\n\npythonでtrain.pyを実行。結果のmodelにdata22.modelと名前をつけて保存。\n\n```\n\n $ python train.py data22.txt data22.model\n 2017-04-08 01:49:31,381 : INFO : collecting all words and their counts\n 2017-04-08 01:49:31,382 : INFO : PROGRESS: at sentence #0, processed 0 \n words, keeping 0 word types\n 2017-04-08 01:49:31,389 : INFO : collected 1684 word types from a \n corpus of 9554 raw words and 228 sentences\n 2017-04-08 01:49:31,389 : INFO : Loading a fresh vocabulary\n 2017-04-08 01:49:31,395 : INFO : min_count=1 retains 1684 unique words \n (100% of original 1684, drops 0)\n 2017-04-08 01:49:31,395 : INFO : min_count=1 leaves 9554 word corpus (100% of original 9554, drops 0)\n 2017-04-08 01:49:31,405 : INFO : deleting the raw counts dictionary of 1684 items\n 2017-04-08 01:49:31,406 : INFO : sample=0.001 downsamples 45 most-common words\n 2017-04-08 01:49:31,407 : INFO : downsampling leaves estimated 5687 word corpus (59.5% of prior 9554)\n 2017-04-08 01:49:31,407 : INFO : estimated required memory for 1684 words and 100 dimensions: 2526000 bytes\n 2017-04-08 01:49:31,410 : INFO : constructing a huffman tree from 1684 words\n 2017-04-08 01:49:31,496 : INFO : built huffman tree with maximum node depth 13\n 2017-04-08 01:49:31,496 : INFO : resetting layer weights\n 2017-04-08 01:49:31,544 : INFO : training model with 3 workers on 1684 vocabulary and 100 features, using sg=1 hs=1 sample=0.001 negative=0 window=10\n 2017-04-08 01:49:31,544 : INFO : expecting 228 sentences, matching count from corpus used for vocabulary survey\n 2017-04-08 01:49:31,708 : INFO : worker thread finished; awaiting finish of 2 more threads\n 2017-04-08 01:49:31,766 : INFO : worker thread finished; awaiting finish of 1 more threads\n 2017-04-08 01:49:31,767 : INFO : worker thread finished; awaiting finish of 0 more threads\n 2017-04-08 01:49:31,767 : INFO : training on 47770 raw words (28489 effective words) took 0.2s, 128642 effective words/s\n 2017-04-08 01:49:31,767 : WARNING : under 10 jobs per worker: consider setting a smaller `batch_words' for smoother alpha decay\n 2017-04-08 01:49:31,767 : INFO : saving Word2Vec object under data22.model, separately None\n 2017-04-08 01:49:31,767 : INFO : not storing attribute syn0norm\n 2017-04-08 01:49:31,767 : INFO : not storing attribute cum_table\n 2017-04-08 01:49:31,870 : INFO : saved data22.model\n \n```\n\n指定した単語と類似度の高い単語をリストアップするスクリプトsimilars.pyを用意。\n\nsimilars.py\n\n```\n\n # -*- coding: utf-8 -*-\n \n from gensim.models import word2vec\n import sys\n \n model = word2vec.Word2Vec.load(sys.argv[1])\n results = model.most_similar(positive=sys.argv[2], topn=10)\n \n for result in results:\n print(result[0], '\\t', result[1])\n \n```\n\n先ほど作成したmodelファイルでsimilars.pyを「本」という単語を引数にして実行。すると以下のエラーが出てしまいます。\n**引数に指定した「本」という単語が認識されていないようですが、原因がわかりません。**\n\n```\n\n $ python similars.py data22.model 本\n Traceback (most recent call last):\n File \"similars.py\", line 7, in <module>\n results = model.most_similar(positive=sys.argv[2], topn=10)\n File \"/usr/local/lib/python2.7/site-\n packages/gensim/models/word2vec.py\", line 1285, in most_similar\n return self.wv.most_similar(positive, negative, topn, \n restrict_vocab, indexer)\n File \"/usr/local/lib/python2.7/site-\n packages/gensim/models/keyedvectors.py\", line 97, in most_similar\n **raise KeyError(\"word '%s' not in vocabulary\" % word)**\n **KeyError: \"word '\\xe6\\x9c\\xac' not in vocabulary\"**\n \n```\n\nどなたか、解決のヒントをいただければ幸いです。よろしくお願いします。", "comment_count": 2, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-07T17:23:58.033", "favorite_count": 0, "id": "33848", "last_activity_date": "2017-08-31T01:15:43.670", "last_edit_date": "2017-04-08T01:26:21.703", "last_editor_user_id": "21434", "owner_user_id": "21434", "post_type": "question", "score": 0, "tags": [ "python", "word2vec", "mecab" ], "title": "Word2vecのKeyerror", "view_count": 1324 }
[ { "body": "同様のエラーが発生しましたが、私は以下で解決しました。 \nword = unicode(sys.argv[2], 'utf-8') \nresults = model.most_similar(positive=word, topn=10)", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-06-30T07:57:58.663", "id": "35997", "last_activity_date": "2017-06-30T07:57:58.663", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "24133", "parent_id": "33848", "post_type": "answer", "score": 1 } ]
33848
null
35997
{ "accepted_answer_id": "33853", "answer_count": 1, "body": "複数のスレッドが共有リソースにアクセスしたとき、 \nデッドロックが発生しない設計になっていることを示す \n設計資料の作り方に困っています。\n\nひとまず、共有リソースの種類と、各スレッドがどういう処理の中でリード/ライトアクセスするか \nの洗い出しまでは終わりました。\n\nリソースのロック状態、処理イベントで状態遷移図をつくってみたのですが、 \n他のスレッドが共有リソースをロックしていたら、 \n・ロック取得に失敗してリトライする(ノンブロッキングの場合) \n・またはロックが開放されるまで待ち続ける(ブロッキングの場合) \nという当たり前を記載しているだけで \nデッドロックが発生しない説明になってないと思えてきました。\n\n一般的には、どのような種類の設計書(タイミングチャート?シーケンス図?その他?)を作成してデッドロックが発生しない設計かを検証するのか教えていただけないでしょうか?\n\n特に具体的な資料が表示してるURLを教えていただければ、大変助かります。", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-07T19:36:33.987", "favorite_count": 0, "id": "33849", "last_activity_date": "2017-04-07T21:59:07.793", "last_edit_date": "2017-04-07T21:01:36.970", "last_editor_user_id": "21437", "owner_user_id": "21437", "post_type": "question", "score": 2, "tags": [ "linux", "c" ], "title": "共有リソース、デッドロック検証はどんな種類の設計資料が必要ですか?", "view_count": 201 }
[ { "body": "まず[デッドロック](https://ja.wikipedia.org/wiki/%E3%83%87%E3%83%83%E3%83%89%E3%83%AD%E3%83%83%E3%82%AF#.E5.9B.9E.E9.81.BF.E6.96.B9.E6.B3.95)は\n\n> 基本的にデッドロックは資源数が2以上の場合に発生する。資源数が1の場合、~デッドロックは発生しない。\n\nという前提があります。その上でいくつかの[回避策](https://ja.wikipedia.org/wiki/%E3%83%87%E3%83%83%E3%83%89%E3%83%AD%E3%83%83%E3%82%AF#.E5.9B.9E.E9.81.BF.E6.96.B9.E6.B3.95)がか挙げられていますので、システムに合わせて設計を行ってください。 \n一般的で確実なのは、1番目に挙げられている方法、ロックする順番を規定することです。この場合の設計資料としても、順番を記載すれば明確になります。", "comment_count": 1, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-07T21:59:07.793", "id": "33853", "last_activity_date": "2017-04-07T21:59:07.793", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "4236", "parent_id": "33849", "post_type": "answer", "score": 0 } ]
33849
33853
33853
{ "accepted_answer_id": "33852", "answer_count": 1, "body": "flock()であるファイルのロックを取得したスレッドが不測の事態で落ちてしまったとき、 \nロックを解除するにはどうしたらよいでしょうか?\n\nためしに \n・あるスレッドでロック握ったまま終了\n\n```\n\n fp = fopen(\"./temp.txt\",\"a+\");\n if(flock(fileno(fp),LOCK_EX | LOCK_NB )!=EXIT_SUCCESS){\n perror(\"Failed to flock(LOCK_EN)\");\n }else{\n printf(\"thread lock\\n\");\n }\n pthread_exit(NULL);\n \n```\n\n・別スレッドでアンロックしてロックする。\n\n```\n\n fp = fopen(\"./temp.txt\",\"a+\");\n \n if(flock(fileno(fp),LOCK_UN |LOCK_NB )!=EXIT_SUCCESS){\n perror(\"Failed to flock(LOCK_UN)\");\n }\n fclose(fp);\n fp = fopen(\"./temp.txt\",\"a+\");\n if(flock(fileno(fp),LOCK_EX |LOCK_NB )!=EXIT_SUCCESS){\n perror(\"Failed to flock(LOCK_EN)\");\n }\n \n```\n\nするプログラムを書いてみましたが、アンロックは成功しているのに \nロックは”Resource temporarily unavailable”でエラーになります。", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-07T20:31:26.593", "favorite_count": 0, "id": "33851", "last_activity_date": "2017-04-07T21:39:02.430", "last_edit_date": "2017-04-07T20:52:10.060", "last_editor_user_id": "21437", "owner_user_id": "21437", "post_type": "question", "score": 1, "tags": [ "linux", "c" ], "title": "flock()によるロックの強制解除", "view_count": 4966 }
[ { "body": "[`flock()`](https://linuxjm.osdn.jp/html/LDP_man-\npages/man2/flock.2.html)について誤解しています。ドキュメントには次の説明があります。\n\n> flock() によって作られるロックは、オープンファイル記述 (open file description) (open(2) 参照)\n> と関連付けられる。 \n> あるプロセスが open(2) (もしくは同様の方法) を使って同じファイルに対して複数のディスクリプターを取得した場合、 **flock()\n> はこれら複数のディスクリプターを各々独立のものとして扱う。**\n> これらのファイルディスクリプターの一つを使ってファイルをロックしようとした際、そのロック要求は、呼び出し元のプロセスがそのファイルの別のディスクリプター経由ですでに設定しているロックによって拒否される場合がある。\n\n`flock()`はファイルに対して関連付けられるのではなく、`fd`(オープンファイル記述)に関連付けられます。ということで、スレッドごとに`fopen()`してしまっては`flock()`は正しく機能しません。\n\n> > flock()であるファイルのロックを取得したスレッドが不測の事態で落ちてしまったとき、ロックを解除するにはどうしたらよいでしょうか?\n\n不測の事態でスレッドが停止してしまった場合、それを検出したスレッドがロック解除すればそれまでのことです。もっともスレッドが停止してしまう状況で処理を継続させることにどれほどの意義があるかは疑問です。\n\n* * *\n\nなおドキュメントには次の説明もあります。\n\n> flock() アドバイザリロックだけを適用する。したがって、ファイルに適切なアクセス権を 付与していれば、プロセスは flock()\n> の使用に無視して、ファイルへの入出力を行うことができる。\n\n`flock()`は`flock()`に対してのみ作用します。ロックを獲得できなくてもファイルアクセスは可能です。", "comment_count": 3, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-07T21:39:02.430", "id": "33852", "last_activity_date": "2017-04-07T21:39:02.430", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "4236", "parent_id": "33851", "post_type": "answer", "score": 4 } ]
33851
33852
33852
{ "accepted_answer_id": "33855", "answer_count": 1, "body": "行数、列数が99以下の配列にstdinから読み込んだファイルを配列に格納するプログラムを書いていています。\n\n無事コンパイルが通り期待どおりの結果が実効されるのですが、Abort trap 6エラーメッセージが出てしまいます。\n\n**main関数のコード**\n\n```\n\n #include <iostream>\n #include <string>\n \n using namespace std;\n \n int main(){\n const int ROW_MAX = 3;\n const int COL_MAX = 3;\n int row_count=0;\n int col_count=0;\n string line;\n \n char arr[ROW_MAX][COL_MAX];\n \n while(getline(cin,line)){ //stdinから読み込み\n int l = line.length();\n \n if(l > COL_MAX){\n cout << \"Column size is too big. Try less than \" << COL_MAX << endl;\n return 1; //lineが列の数より多きい場合はエラー\n }\n \n for(int i=0; i<l; ++i) arr[row_count][i] = line[i];\n \n ++row_count;\n col_count = l;\n \n if(row_count > ROW_MAX){ // row_countがROW_MAXより大きい場合は読み取るのをやめる\n --row_count;\n break;\n }\n \n }\n \n cout << \"row_count : \" << row_count << endl;\n cout << \"col_count : \" << col_count << endl;\n \n cout << \"Input table looks like \" << endl;\n \n for(int i=0; i<row_count; ++i){\n for(int j=0; j<col_count; ++j)\n cout << arr[i][j];\n cout << endl;\n }\n \n cout << \"It has \" << col_count << \" columns and \" << row_count << \" rows.\" << endl;\n \n return 0;\n }\n \n```\n\n**stdin するファイルの中身**\n\n```\n\n 000\n 010\n 000\n 000\n \n```\n\n**./a.out < ファイル名 の結果**\n\n```\n\n row_count : 3\n col_count : 3\n Input table looks like \n 000\n 010\n 000\n It has 3 columns and 3 rows.\n Abort trap: 6\n \n```\n\nなぜAbort trap 6が出てしまうのかどなたか教えていただけないでしょうかm(_ _)m", "comment_count": 5, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-08T00:54:42.697", "favorite_count": 0, "id": "33854", "last_activity_date": "2017-04-08T03:03:12.363", "last_edit_date": "2017-04-08T03:03:12.363", "last_editor_user_id": "18535", "owner_user_id": "18535", "post_type": "question", "score": 0, "tags": [ "c++", "array" ], "title": "C++で配列を扱うプログラムで Abort trap 6のエラーメッセージを出てしまう", "view_count": 5659 }
[ { "body": "サイズ3(=ROW_MAX)の配列(arr)に4つの要素を代入しているので、未定義動作になっているのではないでしょうか?\n\narrはローカル変数、つまりスタック上に確保した変数なので、4つ目の要素代入の際にスタック破壊が発生しており、main関数から戻る際に未定義動作していると予想します。 \n(Abortなので、それなりに純正常な動作のようですが)\n\nなお、各要素を格納する際に、文字列の終端文字(\\0)も入れるようにした方がいいです。 \n(質問例だと問題になりませんが)", "comment_count": 1, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-08T02:20:51.237", "id": "33855", "last_activity_date": "2017-04-08T02:20:51.237", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "20098", "parent_id": "33854", "post_type": "answer", "score": 1 } ]
33854
33855
33855
{ "accepted_answer_id": "33860", "answer_count": 2, "body": "仕事でLinuxを使っているのですが、使用しているライブラリがGPLライセンスであることに気づきました。\n\nGPLライブラリを静的リンクしたプログラムは、GPLが適用されるという解説サイトが複数あり、 \nこのままでは今開発しているプログラムはGPL適用になるのだろうと思っています。 \nですが、いまいち腑の落ちておりませんので質問させてください。\n\n 1. GPLライセンスのライブラリソースコードを改変してリンクした場合に、GPL適用となるのではなく、GPLライセンスのライブラリを静的リンクしたら、リンクしたプログラムはGPLライセンス適用となるという理解であってますか?\n 2. Linuxで開発しているとGPLライブラリのリンクをすべて避けて開発することはかなり難しと感じています。一般的に世の中のLinuxで開発している商用ソフトウェアは、GPLライセンスを避けて開発しているものが多いのでしょうか?GPLライセンスを適用して、ソースコードを公開しているのでしょうか?\n 3. ソースコード公開は要求されてから行えばよいのでしょうか?\n\n私の感覚だと世の中にはもっとGPL適用の商用ソフトウェアが溢れているはずなのに、ソースコードが公開されているなんて話をそれほど聞かないのでGPLライセンスの解説が納得できないのです。 \n初歩的な質問で申し訳ありません。", "comment_count": 1, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-08T04:28:06.633", "favorite_count": 0, "id": "33857", "last_activity_date": "2017-04-08T07:26:01.807", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "21437", "post_type": "question", "score": 2, "tags": [ "linux", "gpl" ], "title": "GPLライブラリをリンクしたプログラムに対する対応方法", "view_count": 8279 }
[ { "body": ">\n> GPLライセンスのライブラリソースコードを改変してリンクした場合に、GPL適用となるのではなく、GPLライセンスのライブラリを静的リンクしたら、リンクしたプログラムはGPLライセンス適用となるという理解であってますか?\n\n改変をしておらずとも静的リンクをしたソフトは開示範囲となります。 \n動的リンクの場合は開示範囲ではないという「見解があり」ます。 \n事実後述の企業はAndroidのソフト全体のソースコードを開示しているわけではなく、静的リンク範囲のみ公開しています。\n\n>\n> Linuxで開発しているとGPLライブラリのリンクをすべて避けて開発することはかなり難しと感じています。一般的に世の中のLinuxで開発している商用ソフトウェアは、GPLライセンスを避けて開発しているものが多いのでしょうか?\n\n私見が入りますが、同様機能でGPLライセンスとそうでないものがあればGPLライセンスのものは避けて開発するかと思います。 \nあるいはGPLライセンスが伝播しないような方法(動的リンクの範囲内にとどめる等)をとるかと思います。\n\n> ソースコード公開は要求されてから行えばよいのでしょうか?\n\n基本的にはソフトをPublishする上で公開は必要になります。 \nただ・・・・古めの情報になりますが、下記にまとめられている通りGPLライセンスを遵守していない企業も多くあるようです。 \n<http://www.codon.org.uk/~mjg59/android_tablets/index.html>\n\n> ソースコードが公開されているなんて話をそれほど聞かないので\n\n<http://k-tai.sharp.co.jp/support/developers/oss/> \n<http://android-dev.kyocera.co.jp/source/> \n<http://spf.fmworld.net/fujitsu/c/develop/sp/android/> \n等、基本的に公開義務のあるものは各企業公開しています。", "comment_count": 1, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-08T07:00:45.090", "id": "33860", "last_activity_date": "2017-04-08T07:00:45.090", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "19716", "parent_id": "33857", "post_type": "answer", "score": 5 }, { "body": "基本的にはH.Hさんの回答と同じ見解です。少し補足させてもらいます。\n\n * GPLと言っても、GPLv2、GPLv3、LGPLv2、LGPLv3 と何種類かあります。 \nLGPLv2、LGPLv3の場合、動的リンクを行うプログラムにはLGPLv2、LGPLv3は適用しなくてもよいです。つまりソースコード公開は不要です。 \nただし、リバースエンジニアリングの禁止ができないです。\n\n * GPLライブラリでも例外条項を含むものもあります。代表的なものですと`libgcc`(gccでビルドするプログラムのスタートアップライブラリ)があります。(リンクしてもGPLの対象外としてよい)\n * GPLプログラムのソースコード公開は、そのプログラムを入手した人に行えばよいので、入手していない人にまで公開する義務はなかったと認識してます。", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-08T07:26:01.807", "id": "33862", "last_activity_date": "2017-04-08T07:26:01.807", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "20098", "parent_id": "33857", "post_type": "answer", "score": 5 } ]
33857
33860
33860
{ "accepted_answer_id": null, "answer_count": 0, "body": "pycharmのremote機能で、dockerのコンテナに接続して作業する際の、実行ユーザーの指定方法がわからず困っております。。\n\nrootユーザーではなく、アプリケーション作成用ユーザーを指定してpycharmで作業がしたいのですが、もしご存知の方がいらっしゃいましたら、ご教授頂けませんでしょうか。\n\nprereferenceの中を全部開いてみたのですが、ちょっとわからず。。 \nどうぞ宜しくお願い致します。", "comment_count": 2, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-08T06:38:25.060", "favorite_count": 0, "id": "33858", "last_activity_date": "2017-04-08T06:38:25.060", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "19817", "post_type": "question", "score": 0, "tags": [ "python", "docker" ], "title": "pycharmでdockerにremoteで接続する際のユーザー指定について", "view_count": 207 }
[]
33858
null
null
{ "accepted_answer_id": "33885", "answer_count": 1, "body": "# 質問内容\n\nWebサイトでの個人情報入力の代用となる、下記のような形式のファイルが存在すると便利だと思います。\n\n```\n\n {\n \"address\": \"東京都新宿区○○町1-2-3\",\n \"address_kana\": \"トウキョウトシンジュククマルマルチョウ1-2-3\",\n \"last_name\": \"田中\",\n \"last_name_kana\": \"タナカ\",\n \"first_name\": \"太郎\",\n \"first_name_kana\": \"タロウ\"\n }\n \n```\n\nこういった形式、つまり\n\n・addressというキーの値として住所が記載されている \n・address_kanaというキーの値としてカナ表記の住所が記載されている\n\nというような、個人情報を表現するファイルの仕様を定義した規格などは、既に存在しますか。 \nまたはどこかで提案されたことがある(もしくは提案中)でしょうか。", "comment_count": 5, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-08T06:39:04.510", "favorite_count": 0, "id": "33859", "last_activity_date": "2017-04-09T12:29:55.750", "last_edit_date": "2017-04-09T11:08:54.217", "last_editor_user_id": "21441", "owner_user_id": "21441", "post_type": "question", "score": 1, "tags": [ "html" ], "title": "Webサイトでの個人情報入力の代用となるファイルについて", "view_count": 197 }
[ { "body": "ファイル形式としては [vCard](https://ja.wikipedia.org/wiki/VCard) があります。 \nしかし、Webサイトでのフォーム入力の代替として使われている例は知りません。\n\n* * *\n\nユーザーの負担を軽減する方策としては、フォームへの[自動入力](https://developers.google.com/web/updates/2015/06/checkout-\nfaster-with-autofill)や自動補完がありますね。 \nこれが現状うまくいっていないのは確かだと思います。 \nしかし、専用ファイルをアップロードするという新仕様が策定される余地があるかというと、私は厳しいと思います。", "comment_count": 2, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-09T12:29:55.750", "id": "33885", "last_activity_date": "2017-04-09T12:29:55.750", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "3054", "parent_id": "33859", "post_type": "answer", "score": 0 } ]
33859
33885
33885
{ "accepted_answer_id": null, "answer_count": 0, "body": "[![構成イメージ](https://i.stack.imgur.com/pYwtv.png)](https://i.stack.imgur.com/pYwtv.png) \nネットワークの勉強の為、vyosの設定を行っています。 \n上記の構成で、PCからvyosを経由してインターネットへの通信を行えるようにしたいです。\n\n■問題点 \n1.現在の設定では、PCからvyos間のPing応答はあります。 \n2.vyosからインターネットへの通信(ping 8.8.8.8)は応答はあります。 \n3.PCからインターネットへの通信(ping 8.8.8.8)が失敗します。PCのFWはOffにしています。\n\n■設定(login user情報は削除)\n\n```\n\n set interfaces ethernet eth0 address 'dhcp'\n set interfaces ethernet eth0 duplex 'auto'\n set interfaces ethernet eth0 smp-affinity 'auto'\n set interfaces ethernet eth0 speed 'auto'\n set interfaces ethernet eth1 address '10.0.2.7/24'\n set interfaces ethernet eth1 duplex 'auto'\n set interfaces ethernet eth1 smp-affinity 'auto'\n set interfaces ethernet eth1 speed 'auto'\n set interfaces loopback 'lo'\n set nat destination rule 10 destination address '10.0.2.5'\n set nat destination rule 10 inbound-interface 'eth0'\n set nat destination rule 10 source address '0.0.0.0/0'\n set nat destination rule 10 translation address '10.0.2.7'\n set nat source rule 10 outbound-interface 'eth0'\n set nat source rule 10 source address '10.0.2.0/24'\n set nat source rule 10 translation address 'masquerade'\n set protocols static route 0.0.0.0/0 next-hop 'y.y.y.y'\n set service ssh 'disable-password-authentication'\n set service ssh port '2022'\n set system config-management commit-revisions '100'\n set system console device ttyS0 speed '9600'\n set system host-name 'vyos'\n set system name-server '157.7.180.133'\n set system name-server '163.44.76.148'\n set system ntp server '0.pool.ntp.org'\n set system ntp server '1.pool.ntp.org'\n set system ntp server '2.pool.ntp.org'\n set system syslog global facility all level 'notice'\n set system syslog global facility protocols level 'debug'\n set system time-zone 'Asia/Tokyo'\n \n```\n\n最初はnatの設定が無かったので、下記ページを参照してnat sourceの設定を追記しました。 \n[vyos ユーザーガイド Source NAT](http://wiki.vyos-\nusers.jp/%E3%83%A6%E3%83%BC%E3%82%B6%E3%83%BC%E3%82%AC%E3%82%A4%E3%83%89)\n\nおそらくNAT(nat destination)あたりの設定が誤っているのではないかと思うのですが、詳しい方はいらっしゃいますでしょうか。", "comment_count": 3, "content_license": "CC BY-SA 4.0", "creation_date": "2017-04-08T08:11:17.883", "favorite_count": 0, "id": "33864", "last_activity_date": "2019-06-08T00:00:22.403", "last_edit_date": "2019-06-08T00:00:22.403", "last_editor_user_id": "32986", "owner_user_id": "21446", "post_type": "question", "score": 0, "tags": [ "network" ], "title": "vyosのNAT設定について", "view_count": 2416 }
[]
33864
null
null
{ "accepted_answer_id": null, "answer_count": 2, "body": "コミットするときなどに、たまにスペースだけ残った行が入っていることがあります。 \n一行にスペースしかない場合はスペースを消したいのですが、 \n設定がみつかりません。", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-08T12:03:57.097", "favorite_count": 0, "id": "33866", "last_activity_date": "2017-04-19T23:19:19.157", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "12896", "post_type": "question", "score": 0, "tags": [ "rubymine" ], "title": "rubymineでスペースだけの行のスペースは保存時に削除したい", "view_count": 569 }
[ { "body": "これですね \n<https://intellij-support.jetbrains.com/hc/en-\nus/community/posts/205803079-Configure-editor-to-remove-whitespaces-in-blank-\nlines>\n\n```\n\n Settings | Editor | General | Strip trailing spaces on Save\n \n```\n\nの値を変更することで実現できます", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-10T08:29:37.023", "id": "33903", "last_activity_date": "2017-04-10T08:29:37.023", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "9796", "parent_id": "33866", "post_type": "answer", "score": 1 }, { "body": "たまにということは、スペースが入っていない空行としてうまく処理されるということもあるということですよね。\n\n`RubyMine 2017.1.1` \nにアップデートしたところ私もたまにスペースが残ってしまうことがあります。\n\nRubyMineは自動でファイルを保存してくれますが、どうもこの自動保存がうまくうごいていないように感じます。`Cmd-s`で手動で保存するとスペースが消えました。", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-19T04:49:03.227", "id": "34113", "last_activity_date": "2017-04-19T23:19:19.157", "last_edit_date": "2017-04-19T23:19:19.157", "last_editor_user_id": "9008", "owner_user_id": "9008", "parent_id": "33866", "post_type": "answer", "score": 1 } ]
33866
null
33903
{ "accepted_answer_id": null, "answer_count": 7, "body": "Windows7でTera Term Version 4.92を使っています。 \nTera TermでUbuntu 14.04.3 LTSにSSH接続していますが、しばらくすると未接続になります。\n\nUbuntu側では `/etc/ssh/sshd_conf` で以下の通り設定し、Keep Alive を送っています。\n\n```\n\n ClientAliveInterval 30\n ClientAliveCountMax 5\n \n```\n\nまたTera Term側では[設定]->[TCP/IP...]で Keep-aliveを30秒に設定します。\n\nサーバ側(Ubuntu)もクライアント側(TeraTerm)もお互いにKeep\naliveパケットは定期的に飛ばしていると思いますが、なぜ未接続になるかわかりません。\n\nご存知の方、是非ご教示お願いします。", "comment_count": 1, "content_license": "CC BY-SA 4.0", "creation_date": "2017-04-08T12:42:56.017", "favorite_count": 0, "id": "33868", "last_activity_date": "2023-07-11T18:05:10.607", "last_edit_date": "2020-08-10T08:06:27.073", "last_editor_user_id": "3060", "owner_user_id": "8593", "post_type": "question", "score": 5, "tags": [ "ubuntu", "ssh", "teraterm" ], "title": "Tera TermでUbuntuにssh接続してしばらくすると未接続になる対処", "view_count": 4394 }
[ { "body": "Teratermの `設定` > `SSH` > `ハートビート(keep-alive)` を 30秒に設定するとどうでしょうか?", "comment_count": 1, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-10T04:53:29.730", "id": "33898", "last_activity_date": "2017-04-10T04:53:29.730", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "5008", "parent_id": "33868", "post_type": "answer", "score": 0 }, { "body": "ESET使っていますか? \n私も経験ありますが、これではないでしょうか?\n\n[続・CentOSにSSH接続すると1分くらいで切断される](http://gw.take-f.net/?cat=1)", "comment_count": 0, "content_license": "CC BY-SA 4.0", "creation_date": "2017-05-15T00:32:37.060", "id": "34712", "last_activity_date": "2020-08-10T08:07:15.710", "last_edit_date": "2020-08-10T08:07:15.710", "last_editor_user_id": "3060", "owner_user_id": "20931", "parent_id": "33868", "post_type": "answer", "score": 0 }, { "body": "ひょっとすると、サーバ側の環境変数 TMOUT という可能性もかすかにあるかもしれませんね。", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-06-29T01:07:09.490", "id": "35947", "last_activity_date": "2017-06-29T01:07:09.490", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "14166", "parent_id": "33868", "post_type": "answer", "score": 1 }, { "body": "「SSH 自動切断」とかでぐぐるといろいろ出てきますが、ここらへんどーでしょー", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2018-03-07T00:50:52.400", "id": "42178", "last_activity_date": "2018-03-07T00:50:52.400", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "27481", "parent_id": "33868", "post_type": "answer", "score": -9 }, { "body": "自分はクライアント側で設定しますけどね。 \n[ユーザーフォルダ]/.ssh/config の設定ファイル内で \n以下を設定すればいいと思います。 \nServerAliveInterval", "comment_count": 0, "content_license": "CC BY-SA 4.0", "creation_date": "2018-11-11T11:46:50.310", "id": "50209", "last_activity_date": "2018-11-11T11:46:50.310", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "12906", "parent_id": "33868", "post_type": "answer", "score": -1 }, { "body": "sshの設定が関係ないとしたら、ログインシェルの自動タイムアウトの設定のきがします。 \nbashならTMOUTとか、zsh なら autologout とか、 \n一定時間、何も操作がないとログアウトする機能があるかと思います。\n\nご使用しているログインシェルが不明のためわかりませんが、 \nそのへんを調べてみるとわかるかもしれません。", "comment_count": 0, "content_license": "CC BY-SA 4.0", "creation_date": "2020-08-10T07:47:10.590", "id": "69418", "last_activity_date": "2020-08-10T07:47:10.590", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "41445", "parent_id": "33868", "post_type": "answer", "score": 0 }, { "body": "イーサネットの省電力がONになっているからではないでしょうか?\n\n[Windows\n10で頻繁にインターネットが途切れる→省電力イーサネットのせいでした。](https://www.ototeku.com/entry/2019/02/04/Windows_10%E3%81%A7%E9%A0%BB%E7%B9%81%E3%81%AB%E3%82%A4%E3%83%B3%E3%82%BF%E3%83%BC%E3%83%8D%E3%83%83%E3%83%88%E3%81%8C%E9%80%94%E5%88%87%E3%82%8C%E3%82%8B%E2%86%92%E7%9C%81%E9%9B%BB%E5%8A%9B%E3%82%A4%E3%83%BC)", "comment_count": 0, "content_license": "CC BY-SA 4.0", "creation_date": "2022-04-04T14:03:11.757", "id": "88167", "last_activity_date": "2022-04-04T16:12:40.567", "last_edit_date": "2022-04-04T16:12:40.567", "last_editor_user_id": "3060", "owner_user_id": "51976", "parent_id": "33868", "post_type": "answer", "score": 0 } ]
33868
null
35947
{ "accepted_answer_id": null, "answer_count": 3, "body": "いつもお世話になっております。javascript初心者です。 \n前回、ajaxのsuccess時に、さらにjsonを呼び出す方法を学んだんですが、 \n今度はjson内でのカウントアップした値をjsonを抜けたあとに引き継ぎをしたいのですが、なぜかうまく行きません。\n\nお手数おかけしますが、ご教授お願い致します。\n\n現在の結果 → alert(j); \nalert 0 \nalert 0 \nalert 0 \nalert 0 \nalert 0 \nalert 0 \nalert 0 \nalert 0\n\n求める結果 → alert(j);\n\nalert 0 \nalert 1 \nalert 2 \nalert 3 \nalert 4 \nalert 5 \nalert 6 \nalert 7\n\n```\n\n function Henka() {\n \n $.ajax({\n url: 'CSVのアドレス',\n success: function (era) {\n \n // csvのjson\n csvListall = $.csv()(era);\n \n // 変数jの定義\n var j = 0;\n \n //for分を追加して\n for (var i = 0; i < 264; i++) {\n \n //各変数定義;\n var calendarId = '';\n var calendarId = csvListall[i][2];\n var irank = '';\n var irank = csvListall[i][5];\n var iimg = '';\n var iimg = csvListall[i][7];\n var iname = '';\n var iname = csvListall[i][0];\n var itarget = '';\n var itarget = csvListall[i][6];\n \n var tab = '[data-today=\"' + j + '\"]';\n var uri = \"https://www.googleapis.com/calendar/v3/calendars/\" + calendarId + \"/events?key=\" + apikey + \"&timeMin=\" + timeMin + \"&timeMax=\" + timeMax + \"&maxResults=10&orderBy=startTime&singleEvents=true\";\n var jsinfo = uri;\n \n //問題のポイントは下記から-------------------------------------------\n \n $.getJSON(jsinfo,\n (function (irank, iimg, iname, tab, itarget, j) {\n return function (data) {\n if (data.items[0].summary != \"\") {\n //処理回数カウント\n j = j + 1;\n //処理内容\n vivid = '<img src=\"' + iimg + '\" alt=\"empty\" style=\"height: 150px;\" class=\"app-button\" data-target=\"' + itarget + '\"><br>' + iname + '';\n $(tab).append(vivid);\n }\n };\n })(irank, iimg, iname, tab, itarget, j)\n );\n alert(j);\n \n //問題のポイントは上記まで-------------------------------------------\n \n }\n }\n });\n }\n \n```", "comment_count": 4, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-08T13:21:15.030", "favorite_count": 0, "id": "33869", "last_activity_date": "2019-12-15T17:04:43.183", "last_edit_date": "2017-04-08T17:37:06.610", "last_editor_user_id": "3068", "owner_user_id": "21411", "post_type": "question", "score": 1, "tags": [ "javascript", "json" ], "title": "JSON取得時にカウントアップした変数の値をその後の処理に引き継ぎたい", "view_count": 1056 }
[ { "body": "`j = j + 1 ;` の部分の`j`は、無名関数(関数リテラル)の引数として関数にローカルな変数なので、 \nここでの変更は関数の呼び出し側に影響しません。\n\n解決方法は色々あると思いますが、 \n1つの方法として参照型にすることで望む動作をさせることができます。 \n例えば、`var j = 0;`を次のように変更して \n`var j = { counter : 0 };`\n\n`j = j + 1 ;`を \n`j.counter += 1;`に変更します。 \nそして \n`alert(j);`は`alert(j.counter);`に変更します。", "comment_count": 2, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-08T13:55:40.080", "id": "33871", "last_activity_date": "2017-04-08T13:55:40.080", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "5044", "parent_id": "33869", "post_type": "answer", "score": 0 }, { "body": "**回答**\n\nおそらく下記のようにすれば、JSONのダウンロードが完了した順に`[data-\ntoday=\"0\"]`~`[data-t‌​oday=\"263\"]`にimgタグが追加されていくかと思います。\n\n`[data-today=\"1\"]`からスタートする場合、変数jの初期値を1にしてください。 \n(`var j = 1;`に変更する)\n\n```\n\n function Henka() {\n $.ajax({\n url: 'CSVのアドレス',\n success: function (era) {\n // csvのjson\n csvListall = $.csv()(era);\n \n // 変数jの定義\n var j = 0;\n \n //for文を追加して\n for (var i = 0; i < 264; i++) {\n \n //各変数定義\n var calendarId = csvListall[i][2];\n var irank = csvListall[i][5];\n var iimg = csvListall[i][7];\n var iname = csvListall[i][0];\n var itarget = csvListall[i][6];\n \n var uri = \"https://www.googleapis.com/calendar/v3/calendars/\" + calendarId + \"/events?key=\" + apikey + \"&timeMin=\" + timeMin + \"&timeMax=\" + timeMax + \"&maxResults=10&orderBy=startTime&singleEvents=true\";\n \n $.getJSON(uri,\n (function (iimg, iname, itarget) {\n return function (data) {\n if (data.items[0].summary !== \"\") {\n //処理内容\n var tab = '[data-today=\"' + j + '\"]';\n var vivid = '<img src=\"' + iimg + '\" alt=\"empty\" style=\"height: 150px;\" class=\"app-button\" data-target=\"' + itarget + '\"/><br/>' + iname;\n $(tab).append(vivid);\n \n //処理回数カウント\n j = j + 1;\n }\n };\n })(iimg, iname, itarget)\n );\n }\n }\n });\n }\n \n```\n\n**解説**\n\n`//処理内容`の`j`はfor文の上に定義している`var j = 0;`の値を参照します。 \nなので、JSONのダウンロードが終わるたびに`//処理回数カウント`が実行されて、数値が1ずつ大きくなっていきます。\n\n自分自身の外側に定義されている変数を参照している関数は、[クロージャ](https://developer.mozilla.org/ja/docs/Web/JavaScript/Closures)と呼ばれます。\n\n今回の例では外側に定義されている変数が`j`で、`j`を参照している`//処理内容`がある関数がクロージャです。\n\n以下は質問にあるコードで気になった点です。\n\n * `var irank`等、2回定義している箇所がありますが、1回目の直後の2回目で値を代入しているので、1回目の定義は不要です。 \n(変数の定義(`var`)は1度だけ行うようにした方がよいです)\n\n * `//処理内容`で`irank`は使用されていないので、`(function(){})()`に渡す必要はありません。\n * `vivid`はローカル変数かと思いますので、`var`を付けたほうがよいです。\n * 一般的に値の比較は`===`や`!==`を使用したほうがよいです。\n\n[比較演算子 - JavaScript |\nMDN](https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Identity)\n\n**余談**\n\n回答に書いたコードと同じような動作をする最小のコードを以下に作成しました。 \n興味があればご覧ください。\n\n```\n\n var csvListall = [\r\n [0, \"sss\", \"//dummyimage.com/101x50/\", \"one\", \"target\"],\r\n [1, \"ss\", \"//dummyimage.com/102x50/\", \"two\", \"target\"],\r\n [2, \"s\", \"//dummyimage.com/103x50/\", \"three\", \"target\"],\r\n [3, \"a\", \"//dummyimage.com/104x50/\", \"four\", \"target\"],\r\n [4, \"b\", \"//dummyimage.com/105x50/\", \"five\", \"target\"],\r\n [5, \"c\", \"//dummyimage.com/106x50/\", \"six\", \"target\"],\r\n [6, \"sss\", \"//dummyimage.com/107x50/\", \"seven\", \"target\"],\r\n [7, \"ss\", \"//dummyimage.com/108x50/\", \"eight\", \"target\"],\r\n [8, \"s\", \"//dummyimage.com/109x50/\", \"nine\", \"target\"],\r\n [9, \"a\", \"//dummyimage.com/110x50/\", \"ten\", \"target\"]\r\n ];\r\n \r\n var j = 0;\r\n \r\n for (var i = 0; i < 10; i++) {\r\n var calendarId = csvListall[i][0];\r\n var rank = csvListall[i][1];\r\n var img = csvListall[i][2];\r\n var name = csvListall[i][3];\r\n var target = csvListall[i][4];\r\n \r\n // 非同期処理 (JSONのダウンロードを想定)\r\n setTimeout((function(img, name, target) {\r\n return function(data) {\r\n if (Math.random() > 0.5) {\r\n //処理内容\r\n var vivid = '<img src=\"' + img + '\" alt=\"empty\" data-target=\"' + target + '\"/><br/>' + name;\r\n $('[data-today=\"' + j + '\"]').append(vivid);\r\n j++;\r\n }\r\n }\r\n })(img, name, target), 500);\r\n }\n```\n\n```\n\n <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js\"></script>\r\n <div data-today=\"0\"></div>\r\n <div data-today=\"1\"></div>\r\n <div data-today=\"2\"></div>\r\n <div data-today=\"3\"></div>\r\n <div data-today=\"4\"></div>\r\n <div data-today=\"5\"></div>\r\n <div data-today=\"6\"></div>\r\n <div data-today=\"7\"></div>\r\n <div data-today=\"8\"></div>\r\n <div data-today=\"9\"></div>\n```\n\n0~1の値をランダムに生成する`Math.random()`の値が0.5より大きかった場合、imgタグを追加する処理が動くようになっています。", "comment_count": 0, "content_license": "CC BY-SA 4.0", "creation_date": "2017-04-09T13:08:54.503", "id": "33886", "last_activity_date": "2019-12-15T17:04:43.183", "last_edit_date": "2019-12-15T17:04:43.183", "last_editor_user_id": "3068", "owner_user_id": "3068", "parent_id": "33869", "post_type": "answer", "score": 1 }, { "body": "$.getJSONは非同期処理なので、コールバックが完了する前にalertが実行されてカウントが増えていかない他、コールバックが$.getJSONを実行した順番に実行されるとは限りません。そのため'data-\ntoday'の順番が入れ替わってしまう可能性もあります。順番が異なってしまうのは好ましくないのではないかと考えますと、非同期の$.getJSONを直列で実行する必要があります。$.getJSONは$.Deferredのオブジェクトを返しますので、テストしてませんが以下の抜粋のようにすると直列され、問題が解決できると思います。なお、直列になるため処理は遅くなります。\n\n```\n\n // 変数jの定義\n var j = 0;\n \n // **追加** Deferredを保持する変数の定義\n var dfrd;\n \n //for分を追加して\n for (var i = 0; i < 264; i++) {\n \n //各変数定義;\n ...\n \n if (! dfrd) {\n dfrd = (function() {\n var d = new $.Deferred();\n d.resolve();\n return d.promise();\n })();\n }\n \n // **問題のポイントを以下のように変更**\n dfrd.then(\n dfrd = $.getJSON(jsinfo,\n (function (irank, iimg, iname, tab, itarget, j) {\n return function (data) {\n if (data.items[0].summary != \"\") {\n //処理回数カウント\n j = j + 1;\n //処理内容\n vivid = '<img src=\"' + iimg + '\" alt=\"empty\" style=\"height: 150px;\" class=\"app-button\" data-target=\"' + itarget + '\"><br>' + iname + '';\n $(tab).append(vivid);\n }\n };\n })(irank, iimg, iname, tab, itarget, j)\n )\n .then( // alertを消す際には、このthenも不要になります\n alert(j);\n );\n );\n }\n \n```", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-11-08T11:03:31.130", "id": "39416", "last_activity_date": "2017-11-08T11:03:31.130", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "26093", "parent_id": "33869", "post_type": "answer", "score": 0 } ]
33869
null
33886
{ "accepted_answer_id": null, "answer_count": 1, "body": "**VisualStudio** を **利用** しています。 \n**首記の件** ですが、 **Android実機ビルド時のみエラー** が **発生** します。 \nまた、 **ソース** 及び **設定** を触らずに、 **音楽ファイル** を **削除** すれば **正常** になります。\n\nエラーログは以下の通りです。\n\n```\n\n 1>------ ビルド開始: プロジェクト:BlankCordovaApp1, 構成:Debug Android ------\n Cordova 6.3.1\n ------ プラットフォーム android は既に存在しています\n ------ ネイティブ ファイルを C:\\app\\BlankCordovaApp1\\BlankCordovaApp1\\res\\native\\android から C:\\app\\BlankCordovaApp1\\BlankCordovaApp1\\platforms\\android にコピーしています\n ------ C:\\app\\BlankCordovaApp1\\BlankCordovaApp1\\platforms\\android へのネイティブ ファイルのコピーが完了しました\n ------ 準備中のプラットフォーム: android\n ____ _ \n / ___|___ _ __ __| | _____ ____ _ _ __ _ __ ___ _ __ __ _ _ __ ___ \n | | / _ \\| '__/ _` |/ _ \\ \\ / / _` | | '_ \\| '__/ _ \\ '_ \\ / _` | '__/ _ \\\n | |__| (_) | | | (_| | (_) \\ V / (_| | | |_) | | | __/ |_) | (_| | | | __/\n \\____\\___/|_| \\__,_|\\___/ \\_/ \\__,_| | .__/|_| \\___| .__/ \\__,_|_| \\___|\n |_| |_| \n -----------------------------------------------------------------------------\n プロジェクト上で Cordova を準備しています\n -----------------------------------------------------------------------------\n \n You have been opted out of telemetry. To change this, run: cordova telemetry on.\n No scripts found for hook \"before_build\".\n No scripts found for hook \"before_prepare\".\n Checking config.xml for saved platforms that haven't been added to the project\n Checking for any plugins added to the project that have not been installed in android platform\n No differences found between plugins added to project and installed in android platform. Continuing...\n Generating platform-specific config.xml from defaults for android at C:\\app\\BlankCordovaApp1\\BlankCordovaApp1\\platforms\\android\\res\\xml\\config.xml\n Merging project's config.xml into platform-specific android config.xml\n Found \"merges/android\" folder. Copying its contents into the android project.\n Merging and updating files from [www, platforms\\android\\platform_www, merges\\android] to platforms\\android\\assets\\www\n delete platforms\\android\\assets\\www\\VSBuildInfo.xml (no source)\n Wrote out android application name \"BlankCordovaApp1\" to C:\\app\\BlankCordovaApp1\\BlankCordovaApp1\\platforms\\android\\res\\values\\strings.xml\n android-versionCode not found in config.xml. Generating a code based on version in config.xml (1.0.0): 10000\n Wrote out Android package name \"io.cordova.myapp23e2b5\" to C:\\app\\BlankCordovaApp1\\BlankCordovaApp1\\platforms\\android\\src\\io\\cordova\\myapp23e2b5\\MainActivity.java\n Updating icons at platforms\\android\\res\n Updating splash screens at platforms\\android\\res\n Prepared android project successfully\n No scripts found for hook \"after_prepare\".\n Checking config.xml for saved plugins that haven't been added to the project\n ------ ビルド中のプラットフォーム: android\n ------ ビルドの構成オプション: --debug --\n \n You have been opted out of telemetry. To change this, run: cordova telemetry on.\n No scripts found for hook \"before_compile\".\n ANDROID_HOME=C:\\Program Files (x86)\\Android\\android-sdk\n JAVA_HOME=C:\\PROGRA~1\\Java\\JDK17~1.0_4\n Reading build config file: C:\\app\\BlankCordovaApp1\\BlankCordovaApp1\\build.json\n Running command: cmd \"/s /c \"C:\\app\\BlankCordovaApp1\\BlankCordovaApp1\\platforms\\android\\gradlew.bat cdvBuildDebug -b C:\\app\\BlankCordovaApp1\\BlankCordovaApp1\\platforms\\android\\build.gradle -Dorg.gradle.daemon=true -Pandroid.useDeprecatedNdk=true\"\"\n Observed package id 'add-ons;addon-unknown-unknown-19' in inconsistent location 'C:\\Program Files (x86)\\Android\\android-sdk\\add-ons\\addon-google_apis-google-19' (Expected 'C:\\Program Files (x86)\\Android\\android-sdk\\add-ons\\addon-unknown-unknown-19')\n Observed package id 'add-ons;addon-unknown-unknown-23' in inconsistent location 'C:\\Program Files (x86)\\Android\\android-sdk\\add-ons\\addon-google_apis-google-23' (Expected 'C:\\Program Files (x86)\\Android\\android-sdk\\add-ons\\addon-unknown-unknown-23')\n Incremental java compilation is an incubating feature.\n :preBuild UP-TO-DATE\n :preDebugBuild UP-TO-DATE\n :checkDebugManifest\n :CordovaLib:preBuild UP-TO-DATE\n :CordovaLib:preDebugBuild UP-TO-DATE\n :CordovaLib:compileDebugNdk UP-TO-DATE\n :CordovaLib:compileLint\n :CordovaLib:copyDebugLint UP-TO-DATE\n :CordovaLib:mergeDebugProguardFiles UP-TO-DATE\n :CordovaLib:packageDebugRenderscript UP-TO-DATE\n :CordovaLib:checkDebugManifest\n :CordovaLib:prepareDebugDependencies\n :CordovaLib:compileDebugRenderscript UP-TO-DATE\n :CordovaLib:generateDebugResValues UP-TO-DATE\n :CordovaLib:generateDebugResources UP-TO-DATE\n :CordovaLib:packageDebugResources UP-TO-DATE\n :CordovaLib:compileDebugAidl UP-TO-DATE\n :CordovaLib:generateDebugBuildConfig UP-TO-DATE\n :CordovaLib:mergeDebugShaders UP-TO-DATE\n :CordovaLib:compileDebugShaders UP-TO-DATE\n :CordovaLib:generateDebugAssets UP-TO-DATE\n :CordovaLib:mergeDebugAssets UP-TO-DATE\n :CordovaLib:processDebugManifest UP-TO-DATE\n :CordovaLib:processDebugResources UP-TO-DATE\n :CordovaLib:generateDebugSources UP-TO-DATE\n :CordovaLib:incrementalDebugJavaCompilationSafeguard UP-TO-DATE\n :CordovaLib:compileDebugJavaWithJavac UP-TO-DATE\n :CordovaLib:processDebugJavaRes UP-TO-DATE\n :CordovaLib:transformResourcesWithMergeJavaResForDebug UP-TO-DATE\n :CordovaLib:transformClassesAndResourcesWithSyncLibJarsForDebug UP-TO-DATE\n :CordovaLib:mergeDebugJniLibFolders UP-TO-DATE\n :CordovaLib:transformNative_libsWithMergeJniLibsForDebug UP-TO-DATE\n :CordovaLib:transformNative_libsWithSyncJniLibsForDebug UP-TO-DATE\n :CordovaLib:bundleDebug UP-TO-DATE\n :prepareAndroidCordovaLibUnspecifiedDebugLibrary UP-TO-DATE\n :prepareDebugDependencies\n :compileDebugAidl UP-TO-DATE\n :compileDebugRenderscript UP-TO-DATE\n :generateDebugBuildConfig UP-TO-DATE\n :mergeDebugShaders UP-TO-DATE\n :compileDebugShaders UP-TO-DATE\n :generateDebugAssets UP-TO-DATE\n :mergeDebugAssets UP-TO-DATE\n :generateDebugResValues UP-TO-DATE\n :generateDebugResources UP-TO-DATE\n :mergeDebugResources\n :processDebugManifest UP-TO-DATE\n :processDebugResources FAILED\n \n \n BUILD FAILED\n \n Total time: 4.676 secs\n 1>MSBUILD : cordova-build error : FAILURE: Build failed with an exception.\n \n \n 1>MSBUILD : cordova-build error : * What went wrong:\n 1>MSBUILD : cordova-build error : Execution failed for task ':processDebugResources'.\n 1>MSBUILD : cordova-build error : > com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command 'C:\\Program Files (x86)\\Android\\android-sdk\\build-tools\\23.0.3\\aapt.exe'' finished with non-zero exit value 1\n 1>MSBUILD : cordova-build error : * Try:\n 1>MSBUILD : cordova-build error : Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.\n Command finished with error code 1: cmd /s /c \"C:\\app\\BlankCordovaApp1\\BlankCordovaApp1\\platforms\\android\\gradlew.bat cdvBuildDebug -b C:\\app\\BlankCordovaApp1\\BlankCordovaApp1\\platforms\\android\\build.gradle -Dorg.gradle.daemon=true -Pandroid.useDeprecatedNdk=true\"\n 1>MSBUILD : cordova-build error : Error: cmd: Command failed with exit code 1 Error output:\n \n \n 1>MSBUILD : cordova-build error : FAILURE: Build failed with an exception.\n 1>MSBUILD : cordova-build error : * What went wrong:\n 1>MSBUILD : cordova-build error : Execution failed for task ':processDebugResources'.\n 1>MSBUILD : cordova-build error : > com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command 'C:\\Program Files (x86)\\Android\\android-sdk\\build-tools\\23.0.3\\aapt.exe'' finished with non-zero exit value 1\n 1>MSBUILD : cordova-build error : * Try:\n 1>MSBUILD : cordova-build error : Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.\n 1>MSBUILD : cordova-build error : Picked up _JAVA_OPTIONS: -Xmx512M\n 1>プロジェクト \"BlankCordovaApp1.jsproj\" のビルドが終了しました -- 失敗。\n ========== ビルド: 0 正常終了、1 失敗、0 更新不要、0 スキップ ==========\n ========== 配置: 0 正常終了、0 失敗、0 スキップ ==========\n \n```\n\n**Cordova** で作成したアプリに **BGM** を流したいだけなので、協力御願い致します。\n\n```\n\n 開発OS Windows10\n 開発IDE VisualStudio2017\n 動作OS Android 4.4.2 (API 19)\n \n```", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-08T16:59:02.793", "favorite_count": 0, "id": "33873", "last_activity_date": "2017-04-09T12:33:17.500", "last_edit_date": "2017-04-09T12:33:17.500", "last_editor_user_id": "76", "owner_user_id": "22456", "post_type": "question", "score": 0, "tags": [ "javascript", "visual-studio", "cordova" ], "title": "www配下に音楽ファイルを入れたらエラーになる。", "view_count": 130 }
[ { "body": "下記プラグインを用いることで、外部サーバーから音楽ファイルを端末内に保存し、端末内に保存した音楽ファイルにアクセスすることで **BGM**\nを流すことが出来ました。 \n[ファイル](https://www.tutorialspoint.com/cordova/cordova_file_system.htm),\n[ファイル転送](https://www.tutorialspoint.com/cordova/cordova_file_transfer.htm)\n\n…要するに、自己解決致しました。 \nお騒がせ致しました。", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-09T10:29:13.097", "id": "33883", "last_activity_date": "2017-04-09T10:29:13.097", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "22456", "parent_id": "33873", "post_type": "answer", "score": 1 } ]
33873
null
33883
{ "accepted_answer_id": null, "answer_count": 1, "body": "こんにちは. Perlを5年ほど学んでいましたが, この度Pythonを学び始めることにしました. 初学者です. \n現在PythonでWebアプリケーションを作ろうと思っているのですが, Perlでは`require\n\"foo.cgi\"`のように記述することで同じディレクトリにあるfoo.cgiというライブラリを読み込むことができました.\nPythonにも`import`以外にこのPerlの`require`のようなものは存在するのでしょうか?\n\n追記: つまり, コンパイル時ではなくスクリプトの実行時に評価される読み込みの関数がPythonにはあるのかなと疑問に思いました.", "comment_count": 2, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-09T05:15:54.853", "favorite_count": 0, "id": "33875", "last_activity_date": "2017-04-11T08:20:54.993", "last_edit_date": "2017-04-10T09:59:22.450", "last_editor_user_id": "19110", "owner_user_id": "22465", "post_type": "question", "score": 0, "tags": [ "python", "perl" ], "title": "PythonにおけるPerlのrequire文のようなものは?", "view_count": 2147 }
[ { "body": "perlで言う`use`に対する`require`のようなものが、pythonにあるかという意味でしょうか。 \nパッケージ名ではなくファイルパスからランタイムにインポートしたいという。\n\n# python2\n\n```\n\n import imp\n your_module = imp.load_source('your_module', './path/to/your_module.py')\n \n your_module.your_function()\n \n```\n\n# python3\n\n```\n\n import importlib.util\n spec = importlib.util.spec_from_file_location('your_module', './path/to/your_module.py')\n your_module = importlib.util.module_from_spec(spec)\n spec.loader.exec_module(your_module)\n \n your_module.your_function()\n \n```\n\n質問文にあるcgiファイルをライブラリとしてrequireという場面はちょっと考えづらいです。 \n.cgiではなく.plファイルかなと思います。", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-11T08:20:54.993", "id": "33929", "last_activity_date": "2017-04-11T08:20:54.993", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "62", "parent_id": "33875", "post_type": "answer", "score": 1 } ]
33875
null
33929
{ "accepted_answer_id": "33896", "answer_count": 2, "body": "登録フォームで戻るボタンを押した際に、警告を出す設定を行っています。 \nその際、下記条件でbeforeunloadイベントを除外しようとしたのですが、 \n知識不足の為 **2の場合** 対応できません。 恐れ入りますが、どなたかご教授いただければと存じます。\n\n▲除外条件▲ \n1:submitした場合 \n2:登録フォーム中の「フェイスブックでログイン」へのリンクを押した場合\n\nJSはrailsのcoffee scriptですが、jquery jsでご回答頂いても問題ございません。\n\n```\n\n <div class=\"entryProfile-buttonWrapper--fb flex\">\r\n <div>\r\n <a class=\"btn btn-flat-facebook w-80-percent\" href=\"/users/auth/facebook?is_business=false\">\r\n Facebookで登録・ログイン </a>\r\n </div>\r\n </div>\r\n \r\n <form accept-charset=\"UTF-8\" action=\"/registration\" class=\"new_user\" id=\"js-registrationForm\" method=\"post\">\r\n <div class=\"form-group row\">\r\n <div class=\"col-xs-3 text-left\">\r\n <span class=\"text-bold\">姓(全角漢字)</span>\r\n </div>\r\n <div class=\"col-xs-4\">\r\n <input class=\"form-control placeholder-no-fix\" id=\"user_profile_attributes_last_name\" name=\"user[profile_attributes][last_name]\" placeholder=\"内田\" type=\"text\">\r\n </div>\r\n </div>\r\n <input class=\"btn btn-blue registrationForm-submit w-90-percent track-regist-db\" data-disable-with=\"送信中...\" id=\"submit-registration\" name=\"commit\" type=\"submit\" value=\"無料会員登録する\">\r\n </form>\n```\n\n記入したJS(coffee script)\n\n```\n\n onBeforeunloadHandler = (e) ->\r\n e.returnValue = 'ページから移動しますか?'\r\n $(window).on 'beforeunload', onBeforeunloadHandler\r\n $('form').on 'submit', (e) ->\r\n $(window).off 'beforeunload', onBeforeunloadHandler\n```", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-09T06:12:43.373", "favorite_count": 0, "id": "33876", "last_activity_date": "2017-04-10T01:01:25.170", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "20360", "post_type": "question", "score": 0, "tags": [ "javascript", "jquery", "coffeescript" ], "title": "beforeunloadイベントで特定リンクの場合適用外にしたい", "view_count": 4680 }
[ { "body": "> 2:登録フォーム中の「フェイスブックでログイン」へのリンクを押した場合\n\nリンクをボタンのように使いたいのでしたらこれでどうでしょうか? \njQueryです。`.js-button-fb-login`はaタグにつけたクラス名です。\n\n```\n\n $('.js-button-fb-login').on('click', function(e) {\n e.preventDefault();\n $(window).off('beforeunload', onBeforeunloadHandler);\n });\n \n```", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-09T08:23:43.457", "id": "33881", "last_activity_date": "2017-04-09T08:23:43.457", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "14222", "parent_id": "33876", "post_type": "answer", "score": 1 }, { "body": "isirin様ご回答ありがとうございました。 \n頂いた内容を一部改変し下記で対応できました。 早急にありがとうございました\n\n```\n\n $('.js-button-fb-login').on 'click', (e) ->\r\n $(window).off 'beforeunload', onBeforeunloadHandler\n```", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-10T01:01:25.170", "id": "33896", "last_activity_date": "2017-04-10T01:01:25.170", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "20360", "parent_id": "33876", "post_type": "answer", "score": 0 } ]
33876
33896
33881
{ "accepted_answer_id": "33878", "answer_count": 1, "body": "■実現したいこと \n自作セルとStoryboard上に別で配置したCellを組み合わせて、textFiledのCellとチェックマークのCellを表示させたいと考えております。\n\n■問題点 \nIdentifierで指定した値(今回の場合、「SexCell」という値)が有効とならず、上手く対象のセルを期待どおりに表示させることができません。 \n今回の場合、性別のCellに対し、チェックマークを指定おりますが、下記の表示結果のとおり、自作セルの状態となり、テキストフィールド状態となってしまいます。\n\n■Storyboard上の設定 \n[![画像の説明をここに入力](https://i.stack.imgur.com/UtUCa.png)](https://i.stack.imgur.com/UtUCa.png)\n\n■表示結果 \n[![画像の説明をここに入力](https://i.stack.imgur.com/WusDB.png)](https://i.stack.imgur.com/WusDB.png)\n\n■現状のソースコード \n・RegisterViewController.swift\n\n```\n\n import UIKit\n \n class RegisterViewController: UIViewController,UITableViewDataSource,RegisterDelegate{\n \n @IBAction func unwindToRegister(segue: UIStoryboardSegue){\n \n }\n \n @IBOutlet weak var registerTableView: UITableView!\n \n \n //データ\n var dataList = [[\"ユーザー名\"],[\"パスワード\",\"パスワード( 確認用)\"],[\"メールアドレス\",\"メールアドレス(確認用)\"],[\"男性\",\"女性\"]]\n \n //セクション\n var sectionIndex:[String] = [\"ユーザー名\",\"パスワード\",\"メールアドレス\",\"性別\"]\n \n //データを返すメソッド\n func tableView(_ tableView:UITableView, cellForRowAt indexPath:IndexPath) -> UITableViewCell {\n if indexPath.section == 0 {\n //セルを取得して値を設定する。\n let cell = tableView.dequeueReusableCell(withIdentifier: \"RegisterCell\", for:indexPath as IndexPath) as! RegisterTableViewCell\n var register = dataList[indexPath.section]\n cell.registerTextField.placeholder = register[indexPath.row]\n //自作セルのデリゲート先に自分を設定する。\n cell.delegate = self\n return cell\n }else if indexPath.section == 1 {\n //セルを取得して値を設定する。\n let cell = tableView.dequeueReusableCell(withIdentifier: \"RegisterCell\", for:indexPath as IndexPath) as! RegisterTableViewCell\n var register = dataList[indexPath.section]\n cell.registerTextField.placeholder = register[indexPath.row]\n cell.registerTextField.isSecureTextEntry = true\n //自作セルのデリゲート先に自分を設定する。\n cell.delegate = self\n return cell\n }else if indexPath.section == 2 {\n //セルを取得して値を設定する。\n let cell = tableView.dequeueReusableCell(withIdentifier: \"RegisterCell\", for:indexPath as IndexPath) as! RegisterTableViewCell\n var register = dataList[indexPath.section]\n cell.registerTextField.placeholder = register[indexPath.row]\n //自作セルのデリゲート先に自分を設定する。\n cell.delegate = self\n return cell\n }else if indexPath.section == 3{\n //セルを取得して値を設定する。\n let cell = tableView.dequeueReusableCell(withIdentifier: \"RegisterCell\", for:indexPath as IndexPath) as! RegisterTableViewCell\n var register = dataList[indexPath.section]\n cell.registerTextField.placeholder = register[indexPath.row]\n //自作セルのデリゲート先に自分を設定する。\n cell.delegate = self\n return cell\n }else {\n //セルを取得する。\n let cell = tableView.dequeueReusableCell(withIdentifier: \"SexCell\", for:indexPath) as UITableViewCell\n var test = dataList[indexPath.section]\n cell.accessoryType = .checkmark\n cell.textLabel?.text = test[indexPath.row]\n return cell\n }\n }\n \n //データの個数を返すメソッド\n func tableView(_ tableView:UITableView, numberOfRowsInSection section:Int) -> Int {\n return dataList[section].count\n }\n \n //セクション名を返す\n func tableView(_ tableView:UITableView, titleForHeaderInSection section:Int) -> String?{\n return sectionIndex[section]\n }\n \n //セクションの個数を返す\n func numberOfSections(in tableView: UITableView) -> Int {\n return sectionIndex.count\n }\n \n override func viewDidLoad() {\n super.viewDidLoad()\n // Do any additional setup after loading the view, typically from a nib.\n //自作セルをテーブルビューに登録する。\n let testXib = UINib(nibName:\"RegisterTableViewCell\", bundle:nil)\n registerTableView.register(testXib, forCellReuseIdentifier:\"RegisterCell\")\n \n }\n \n //デリゲートメソッド\n func textFieldDidEndEditing(cell: RegisterTableViewCell, value:String) {\n //変更されたセルのインデックスを取得する。\n let index = registerTableView.indexPathForRow(at: cell.convert( cell.bounds.origin, to:registerTableView))\n \n //データを変更する。\n let sec = index!.section\n let row = index!.row\n \n dataList[sec][row] = value\n print(value)\n print(dataList)\n }\n \n override func didReceiveMemoryWarning() {\n super.didReceiveMemoryWarning()\n // Dispose of any resources that can be recreated.\n }\n \n \n }\n \n```\n\n・RegisterTableViewCell.swift\n\n```\n\n import UIKit\n \n \n //デリゲート先に適用してもらうプロトコル\n protocol RegisterDelegate {\n func textFieldDidEndEditing(cell:RegisterTableViewCell, value:String)\n }\n \n class RegisterTableViewCell: UITableViewCell, UITextFieldDelegate {\n \n @IBOutlet weak var registerTextField: UITextField!\n \n var delegate:RegisterDelegate! = nil\n \n override func awakeFromNib() {\n super.awakeFromNib()\n // Initialization code\n \n //テキストフィールドのデリゲート先を自分に設定する。\n registerTextField.delegate = self\n }\n \n override func setSelected(_ selected: Bool, animated: Bool) {\n super.setSelected(selected, animated: animated)\n \n // Configure the view for the selected state\n }\n \n \n //デリゲートメソッド\n func textFieldShouldReturn(_ textField: UITextField) -> Bool\n {\n //キーボードを閉じる。\n textField.resignFirstResponder()\n return true\n }\n \n \n //デリゲートメソッド\n func textFieldDidEndEditing(_ textField: UITextField) {\n //テキストフィールドから受けた通知をデリゲート先に流す。\n self.delegate.textFieldDidEndEditing(cell: self, value: registerTextField.text!)\n }\n \n \n }\n \n```", "comment_count": 2, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-09T07:02:10.040", "favorite_count": 0, "id": "33877", "last_activity_date": "2017-04-09T07:35:17.730", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "8489", "post_type": "question", "score": 0, "tags": [ "swift", "swift3" ], "title": "tableViewについてwithIdentifierで指定したIdentifierが有効とならない", "view_count": 561 }
[ { "body": "上記のコメントでも頂いているとおり、セクションの条件分岐が多かったことが原因でした。セクション数に合わせて条件分岐を修正したところ正しく動作いたしました。今後、tableViewを利用する際は、セクション数と条件分岐の数が適切か確認したいと思います。", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-09T07:35:17.730", "id": "33878", "last_activity_date": "2017-04-09T07:35:17.730", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "8489", "parent_id": "33877", "post_type": "answer", "score": 0 } ]
33877
33878
33878
{ "accepted_answer_id": "33893", "answer_count": 4, "body": "C言語で複数スレッドからファイルアクセスする場合、ロックする関数についてご教示ください。\n\n下記のようなプログラムを作成しています。\n\n・スレッド(1)は、ファイルに対してライトします。 \n・スレッド(2)は、スレッド(1)によってライトされたファイルに対してリードします。 \n・必ずしもスレッド(1)(2)は同じファイルにアクセスするわけではなく、スレッドごとにfopen()します。 \n・タイミングによってスレッド(1)(2)は同じファイルにアクセスします。\n\n・(不測の自体でロックをとったままスレッドが落ちてしまった場合、他方のスレッド側ロックを強制解除して処理は継続させたいです(別途エラーメッセージはログに出力します)。\n\nflock(fd,LOCK_EX)をつかってロックを取る方針で検討していたのですが、 \n「flock()はファイル記述子ごとにロックするので、 \nfopen()を別々に行っていては正しくロックできないのでは?」 \nとの指摘を受けて、ロックのとり方を再検討している最中です。", "comment_count": 5, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-09T07:51:19.613", "favorite_count": 0, "id": "33879", "last_activity_date": "2017-04-11T01:37:57.080", "last_edit_date": "2017-04-09T07:58:09.630", "last_editor_user_id": "21437", "owner_user_id": "21437", "post_type": "question", "score": 2, "tags": [ "linux", "c" ], "title": "複数スレッドからファイルアクセスする場合の、適切なロック方法", "view_count": 16794 }
[ { "body": "[前の質問](https://ja.stackoverflow.com/questions/33851/)の回答で sayuri\nさんが言いたかったのは、ロックする時と解除する時とで \n`fp` (というか file descriptor) が違う点が問題、ということだと思います。\n\n以下のように `flock()` でも問題ないと思います。\n\n```\n\n #include <stdio.h>\n #include <stdlib.h>\n #include <unistd.h>\n #include <sys/file.h>\n #include <pthread.h>\n \n #define N 2\n \n static FILE *fp0;\n \n static void *test0(void *parm)\n {\n int n = *(int *) parm;\n \n if ((fp0 = fopen(\"test.txt\", \"a+\")) == NULL) {\n perror(\"fopen\");\n exit(1);\n }\n \n if (flock(fileno(fp0), LOCK_EX | LOCK_NB) != 0) {\n perror(\"flock\");\n exit(1);\n }\n \n return NULL;\n }\n \n static void *test1(void *parm)\n {\n int n = *(int *) parm;\n FILE *fp;\n \n if (flock(fileno(fp0), LOCK_UN | LOCK_NB) != 0) {\n perror(\"flock\");\n exit(1);\n }\n \n if ((fp = fopen(\"test.txt\", \"a+\")) == NULL) {\n perror(\"fopen\");\n exit(1);\n }\n \n if (flock(fileno(fp), LOCK_EX | LOCK_NB) != 0) {\n perror(\"flock\");\n exit(1);\n }\n \n fclose(fp);\n \n return NULL;\n }\n \n int main(void)\n {\n pthread_t thr[N];\n pthread_attr_t attr[N];\n int n[N];\n \n for (int i = 0; i < N; i++)\n n[i] = i;\n \n pthread_attr_init(&attr[0]);\n pthread_create(&thr[0], &attr[0], test0, &n[0]);\n sleep(1);\n pthread_attr_init(&attr[1]);\n pthread_create(&thr[1], &attr[1], test1, &n[1]);\n \n for (int i = 0; i < N; i++) {\n void *r;\n pthread_join(thr[i], &r);\n }\n \n return 0;\n }\n \n```\n\n`test0()` 側スレッドで `fopen()` した `fp0` を、`test1()` 側スレッドに渡す必要があります。 \nこの `fp0` を放置すると、何度もスレッドが落ちた場合に `fclose()` されない `FILE *`\nがどんどん残っていってしまいます。従って強制解除と同時に `fclose()` も必要になるでしょうから、どのみち `test1()`\n側スレッドに渡す必要はあるので、この点は問題にはならないと思っています。", "comment_count": 3, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-09T13:52:53.950", "id": "33887", "last_activity_date": "2017-04-09T13:52:53.950", "last_edit_date": "2017-04-13T12:52:38.920", "last_editor_user_id": "-1", "owner_user_id": "5288", "parent_id": "33879", "post_type": "answer", "score": 2 }, { "body": "同一プロセス内のスレッド間のファイル読み書きの排他制御であれば、`pthread_mutex_lock()`で制御するほうが簡易かと思います。 \n(と言うか、同一プロセス(PID)内ではスレッド間で`fcntl()`でのファイルロックはできないと思われます)\n\n```\n\n /*\n * コード例(エラー判定は省略)\n */\n /* スレッド間で共有する排他制御変数 */\n pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZE;\n \n /*\n * スレッド1\n */\n void* thread1(void* arg) {\n /*\n * 中略\n */\n pthread_mutex_lock(&mutex);\n FILE* fp = fopen(\"file\", \"r\");\n /*\n * ファイル操作(読み込み)\n */\n fclose(fp);\n pthread_mutex_unlock(&mutex);\n /*\n * 以下、略\n */\n }\n /*\n * スレッド2\n */\n void* thread2(void* arg) {\n /*\n * 中略\n */\n pthread_mutex_lock(&mutex);\n FILE* fp = fopen(\"file\", \"w+\");\n /*\n * ファイル操作(書き込み)\n */\n fclose(fp);\n pthread_mutex_unlock(&mutex);\n /*\n * 以下、略\n */\n }\n \n```\n\nなお、本論から外れますが、スレッドが異常終了したことを考慮に入れるのであれば、スレッドの生死や排他変数の状態監視を行う別スレッドが必要になってくると思います。 \n複雑な処理の部類と思いますので、動作条件を見直した方がよいかと思います。", "comment_count": 3, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-09T14:41:43.747", "id": "33889", "last_activity_date": "2017-04-09T14:41:43.747", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "20098", "parent_id": "33879", "post_type": "answer", "score": 1 }, { "body": "Linuxではあまり役に立たないかもしれませんが\n\nC11で導入された[`fopen_s()`](http://en.cppreference.com/w/c/io/fopen)を使用すると排他オープンすることができます。ファイルシステムレベルでの排他なので別プロセス・別スレッドだけでなく同一スレッドであってもクローズするまでは再オープンすることができなくなります。\n\nただし、先行するファイル使用者がいつ完了するのか?という問題があります。完了待ちをすることを考えるとuser20098さんの提案されている`pthread_mutex_lock`などの排他・同期が適切に感じます。\n\n* * *\n\n> もスレッド(1)(2)は同じファイルにアクセスするわけではないので、mutexだと若干ロッ‌​ク範囲がおおきくなります。\n\nファイル毎にmutexを作成するまでです。ファイル名・mutexのペアを構造体で用意し、スレッド間で共有することになるでしょうか。 \nというように適切な設計を行っていくと\n\n> スレッド毎にfopen()して、できればスレッド間でファイルディスクリプタの受け渡しはしたくな‌​いです。\n\nなどとは言っていられないです。\n\n* * *\n\n> 排他を取るのはシングルプロセスです。\n\nとのことですが、ファイルを書き込むのも読み込むのも単一プロセス内ということでしたら、そもそもファイルを介さず、プロセス内スレッド間でメモリを共有すればいいのではと思います。", "comment_count": 2, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-09T21:48:02.253", "id": "33893", "last_activity_date": "2017-04-11T01:37:57.080", "last_edit_date": "2017-04-11T01:37:57.080", "last_editor_user_id": "4236", "owner_user_id": "4236", "parent_id": "33879", "post_type": "answer", "score": 3 }, { "body": "参考までに、以下は [Open file description locks](https://gavv.github.io/blog/file-\nlocks/#open-file-description-locks-fcntl) を使ったサンプルコードです。\n\nリンク先に記載がある通り、`POSIX record locks` との違いは以下で、\n\n> The only difference is in fcntl command names:\n```\n\n> F_OFD_SETLK instead of F_SETLK\n> F_OFD_SETLKW instead of F_SETLKW\n> F_OFD_GETLK instead of F_GETLK\n> \n```\n\nLinux kernel 3.15 以上でのみ利用可能です。\n\n※ `POSIX record locks` である `fcntl(fd, F_SETLKW, ...)` や `fcntl(fd, F_SETLK,\n...)`\nをコメントアウトしていますが、こちらを使うと出力ファイル(`/tmp/output.dat`)の中身は期待通りになりません(部分的に上書きされるなど)\n\n```\n\n #define _GNU_SOURCE\n #include <stdio.h>\n #include <stdlib.h>\n #include <unistd.h>\n #include <fcntl.h>\n #include <pthread.h>\n \n #define OUTPUT \"/tmp/output.dat\"\n \n void *write_thread(void *id){\n long tid = (long)id;\n struct flock lock = {\n .l_whence = SEEK_SET,\n .l_start = 0,\n .l_len = 0, // Lock whole file\n };\n \n int fd = open(OUTPUT, O_RDWR | O_CREAT, 0644);\n \n lock.l_type = F_WRLCK;\n fcntl(fd, F_OFD_SETLKW, &lock);\n //fcntl(fd, F_SETLKW, &lock);\n \n lseek(fd, 0, SEEK_END);\n \n int len; char buf[256];\n for (int i=0;i<5;i++) {\n len = sprintf(buf, \"tid=%ld, fd=%d, i=%d\\n\", tid, fd, i);\n write(fd, buf, len);\n }\n fsync(fd);\n \n lock.l_type = F_UNLCK;\n fcntl(fd, F_OFD_SETLK, &lock);\n //fcntl(fd, F_SETLK, &lock);\n close(fd);\n \n pthread_exit(NULL);\n }\n \n int main() {\n int num_threads = 3;\n pthread_t threads[num_threads];\n \n truncate(OUTPUT, 0);\n for (int i=0;i<num_threads;i++) {\n pthread_create(&threads[i], NULL, write_thread, (void *)i);\n }\n \n for (int i=0;i<num_threads;i++) {\n pthread_join(threads[i], NULL);\n }\n \n return 0;\n }\n \n```", "comment_count": 2, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-09T22:10:03.813", "id": "33894", "last_activity_date": "2017-04-09T22:10:03.813", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": null, "parent_id": "33879", "post_type": "answer", "score": 1 } ]
33879
33893
33893
{ "accepted_answer_id": null, "answer_count": 2, "body": "PHPとMySqlでプログラムしています。\n\n$data配列には、id(一意),dateが入っています。 \nこのデーターをMySQLのテーブルに挿入していきます。\n\nMySQLには、すでに同じdateが入っていたら、その$dataを除外して、MySQLにデーターをinsertしたいとします。\n\nシンプルに配列とMySQLテーブルのデーターを比較する方法があったら、ご教示ください。", "comment_count": 1, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-09T17:27:58.063", "favorite_count": 0, "id": "33891", "last_activity_date": "2017-05-11T02:58:02.803", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "20577", "post_type": "question", "score": 0, "tags": [ "php", "mysql", "sql" ], "title": "SQLとPHP配列を比較する", "view_count": 361 }
[ { "body": "一位のキーを用いて作成、更新が同時にできるものは下記のが用意されています。\n\n```\n\n INSERT INTO table (a,b,c) VALUES (1,2,3)\n ON DUPLICATE KEY UPDATE c=c+1;\n \n```\n\n<https://dev.mysql.com/doc/refman/5.6/ja/insert-on-duplicate.html>\n\n既に存在している場合は、更新項目を日付などにして更新するか、既存のデータを上書きする形で行うことができます。データの更新がない場合は実際に更新は走らないので高速でもあります。", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-24T15:28:21.940", "id": "34250", "last_activity_date": "2017-04-24T15:28:21.940", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "22763", "parent_id": "33891", "post_type": "answer", "score": 1 }, { "body": "データをselectして持ってきてからの比較が一番簡単かと思います。\n\n```\n\n select date from table_name;\n \n```\n\n配列にして取得してからinsertですね。\n\ninsert into .... duplicate key\nupdateを利用する場合は、もっと簡単で更新対象を更新日とかにすればデータは更新されず済みます。", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-05-10T13:57:10.293", "id": "34610", "last_activity_date": "2017-05-11T02:58:02.803", "last_edit_date": "2017-05-11T02:58:02.803", "last_editor_user_id": "3054", "owner_user_id": "22763", "parent_id": "33891", "post_type": "answer", "score": -1 } ]
33891
null
34250
{ "accepted_answer_id": "33907", "answer_count": 2, "body": "ec2 インスタンスをストップして、stopped の状態になったのちに、 CreateImage を行って、その後にインスタンスを再度 start\nする場合を考えます。\n\nこのとき、インスタンスの start は、 AMI の作成の完了を待つ必要がありますか?\n\nというのも、 AMI の作成は、その操作が実行されると、「作成中」状態の AMI が作成されて、ある一定時間の後に、その AMI が ready\nになります。もし ready になる前に launch しても問題ないのだとしたら、 AMI\n作成命令を行った時点でその時点のディスク情報はどこかしらに保持されていることになり、だったら何で AMI は一瞬で ready\nにならないのか、と疑問になります。怖いのは、AMI\nの作成は、元のインスタンスの、その時点のボリュームを利用しているパターンで、これが発生していた場合には、作成された AMI\nは不整合な状態になっている可能性があります。\n\nこの、 ec2 のインスタンスと AMI の動作の細かい仕様を見つけられずにいるので、質問しています。", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-10T04:32:22.487", "favorite_count": 0, "id": "33897", "last_activity_date": "2017-04-10T09:53:26.107", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "754", "post_type": "question", "score": 2, "tags": [ "aws" ], "title": "AWS インスタンスを、イメージを作成している途中で start しても問題ないか", "view_count": 3767 }
[ { "body": "AMI作成時はボリュームのスナップショットが作成されますが、スナップショットは差分で取られるため、作成に数分単位で時間がかかると\nドキュメントに書かれています。 \nご参考) [Linux\nインスタンス用ユーザーガイド](http://docs.aws.amazon.com/ja_jp/AWSEC2/latest/UserGuide/creating-\nan-ami-ebs.html)\n\nそのため AMI が ready になるまで (少なくとも スナップショットの作成が終わるまでは) インスタンス側は 一貫した状態を保つ意味で\n停止している必要があると思います。", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-10T08:18:21.393", "id": "33901", "last_activity_date": "2017-04-10T08:18:21.393", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "5008", "parent_id": "33897", "post_type": "answer", "score": 0 }, { "body": "@take88 に掲載してもらったリンク先を読み込んでみた結果、\n\n * AMI 作成が pending になっている状態でも、その対象のインスタンスは start しても構わない。\n\nのではないかと思うに至りました。\n\n### 理由\n\n * AMI 作成ページの説明によれば、 \n<http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/creating-an-ami-ebs.html> \nAMI は基本的にインスタンスを構成するボリュームに対する snapshot でもって構成されている。\n\n * snapshot 作成のページによれば、 \n<http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-creating-\nsnapshot.html> \n\"While it is completing, an in-progress snapshot is not affected by ongoing\nreads and writes to the volume.\" \nとあるので、 snapshot の作成は、元 volume の書き込みに対して影響を受けない。", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-10T09:53:26.107", "id": "33907", "last_activity_date": "2017-04-10T09:53:26.107", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "754", "parent_id": "33897", "post_type": "answer", "score": 0 } ]
33897
33907
33901
{ "accepted_answer_id": "33914", "answer_count": 1, "body": "現在フォームを作成し、フォームで戻るボタンを選択した際にアラートを表示させるようにしています。\n\nその際「このページでこれ以上ダイアログボックスを生成しない」とメッセージとチェックボックスが表示されるため、この\n**メッセージとダイヤログをJSで非表示にする設定** はございますでしょうか? \nブラウザ側で制御する方法は見つかったのですが、システム側で非表示にする設定が見つからず \nどなたかご教授頂ければと存じます。\n\n確認したブラウザは、クロームのバージョン 57.0.2987.133 になります \nご回答頂く際はJSはでもJqueryでも問題ございません。 \n恐れ入りますが、よろしくお願いします \n\n```\n\n <div class=\"entryProfile-buttonWrapper--fb flex\">\r\n <div>\r\n <a class=\"btn btn-flat-facebook w-80-percent\" href=\"/users/auth/facebook?is_business=false\">\r\n Facebookで登録・ログイン </a>\r\n </div>\r\n </div>\r\n \r\n <form accept-charset=\"UTF-8\" action=\"/registration\" class=\"new_user\" id=\"js-registrationForm\" method=\"post\">\r\n <div class=\"form-group row\">\r\n <div class=\"col-xs-3 text-left\">\r\n <span class=\"text-bold\">姓(全角漢字)</span>\r\n </div>\r\n <div class=\"col-xs-4\">\r\n <input class=\"form-control placeholder-no-fix\" id=\"user_profile_attributes_last_name\" name=\"user[profile_attributes][last_name]\" placeholder=\"内田\" type=\"text\">\r\n </div>\r\n </div>\r\n <input class=\"btn btn-blue registrationForm-submit w-90-percent track-regist-db\" data-disable-with=\"送信中...\" id=\"submit-registration\" name=\"commit\" type=\"submit\" value=\"無料会員登録する\">\r\n </form>\n```\n\n```\n\n onBeforeunloadHandler = (e) ->\r\n e.returnValue = 'このサイトを離れてもよろしいですか?'\r\n $(window).on 'beforeunload', onBeforeunloadHandler\r\n \r\n $('.btn.btn-flat-facebook').on 'click', (e) ->\r\n $(window).off 'beforeunload', onBeforeunloadHandler\r\n $('form').on 'submit', (e) ->\r\n $(window).off 'beforeunload', onBeforeunloadHandler\n```", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-10T04:55:37.820", "favorite_count": 0, "id": "33899", "last_activity_date": "2017-04-10T15:59:43.363", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "20360", "post_type": "question", "score": 0, "tags": [ "javascript", "jquery", "coffeescript" ], "title": "beforeunloadイベントを利用した確認ダイヤログの表示で、チェックボックスを表示させない", "view_count": 3923 }
[ { "body": "## 本題について\n\n> メッセージとダイヤログをJSで非表示にする設定\n\nそれはブラウザの機能なのでオフにすることが出来ないはずです。 \n[英語版StackOverflowのページ](https://stackoverflow.com/questions/11729835/how-to-\ndisable-prevent-this-page-from-creating-additional-dialogs) \nそれが出来てしまうと悪意のある人によってアラートを表示しまくるといった嫌がらせが可能になってしまうかもしれないからです。\n\n## 代案\n\n警告表示にアラートではなく自作のモーダルウィンドウを使うというのはどうでしょうか? \n更にイベントはbeforeunloadではなくpopstateを使うというのはどうでしょうか? \npopstateを使うとAjaxによるページの更新が必要になってきます。 \nなので直接遷移後のページに飛んでくることへの対策としてサーバーソフトでrewriteをしたりNode.jsなどでサーバーサイドのルーターライブラリを使って同じページを返してJavaScript側で遷移をさせると行ったことが必要になってきます。\n\n少し大掛かりになりそうなのでダイアログを消すためだけにわざわざそれをするのはあまりおすすめはできません。 \nHistoryAPIを使ってモーダルの表示非表示を切り替えるだけのものはフラグが多く雑ですが書いてみたのでよかったらどうぞ。\n\nHTML\n\n```\n\n <button class=\"js-button-push-form\">フォームのURLをpushする</button>\n <button class=\"js-button-push-notform\">フォームでないURLをpushする</button>\n <div class=\"js-modal-back-alert\">\n <p>このサイトを離れてもよろしいですか?</p>\n <button class=\"js-modal-button-cancel\">戻らない</button>\n <button class=\"js-modal-button-accept\">戻る</button>\n </div>\n <div class=\"js-modal-overlay\"></div>\n \n```\n\nCSS\n\n```\n\n .js-modal-back-alert {\n display: none;\n position: fixed;\n z-index: 2;\n }\n \n .js-modal-overlay {\n background-color:rgba(0,0,0,0.75);\n display: none;\n height: 100%;\n left: 0;\n position: fixed;\n top: 0;\n width: 100%;\n z-index: 1;\n }\n \n```\n\nJavaScript\n\n```\n\n // ハッシュ#が付いてしまいますがhashchangeイベントを使ったほうがきれいなコードになるかと思います。\n \n let canBack = false;\n let isFormPage = false;\n \n const updateIsForm = () => {\n isFormPage = location.pathname === '/form-url';\n };\n \n const hideModal = e => {\n $('.js-modal-overlay').fadeOut();\n $('.js-modal-back-alert').fadeOut();\n };\n \n const showModal = e => {\n $('.js-modal-overlay').fadeIn('slow');\n $('.js-modal-back-alert').fadeIn('slow');\n };\n \n $(window).on('popstate', e => {\n if (!canBack && isFormPage) {\n history.pushState(null, 'ページ名', '/form-url');\n showModal();\n return;\n }\n updateIsForm();\n canBack = false;\n });\n \n // 確認モーダルの無効化\n \n $('form').on('submit', e => {\n e.preventDefault();\n canBack = true;\n });\n \n $('.js-button-fb-login').on('click', e => {\n e.preventDefault();\n canBack = true;\n });\n \n // 履歴追加\n \n $('.js-button-push-form').on('click', e => {\n history.pushState({formAddr: true}, 'フォームのページ', '/form-url');\n updateIsForm();\n });\n \n $('.js-button-push-notform').on('click', e => {\n history.pushState({formAddr: false}, 'フォームじゃないページ', '/not-form-url');\n updateIsForm();\n });\n \n // モーダル\n \n $('.js-modal-button-accept').on('click', e => {\n canBack = true;\n history.back();\n hideModal();\n });\n \n $('.js-modal-button-cancel').on('click', hideModal);\n \n```\n\n追記: \nHistoryAPIを使うときは何らかのサーバー上で行わないとエラーになるので注意して下さい。", "comment_count": 1, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-10T15:50:15.757", "id": "33914", "last_activity_date": "2017-04-10T15:59:43.363", "last_edit_date": "2017-05-23T12:38:56.467", "last_editor_user_id": "-1", "owner_user_id": "14222", "parent_id": "33899", "post_type": "answer", "score": 1 } ]
33899
33914
33914
{ "accepted_answer_id": null, "answer_count": 1, "body": "## 発生している問題\n\nネットに出ている情報をいろいろ試してみましたが、zipruby が入りません。 \n1.`gem install zipruby` \nネットに出ている通り\n\n```\n\n C:\\>gem install zipruby \n Building native extensions. This could take a while... \n ERROR: Error installing zipruby: \n ERROR: Failed to build gem native extension. \n \n C:/Ruby/bin/ruby.exe extconf.rb \n checking for zlib.h... no \n *** extconf.rb failed *** \n Could not create Makefile due to some reason, probably lack of \n necessary libraries and/or headers. Check the mkmf.log file for more \n details. You may need configuration options. \n \n Provided configuration options: \n --with-opt-dir \n --without-opt-dir \n --with-opt-include \n --without-opt-include=${opt-dir}/include \n --with-opt-lib \n --without-opt-lib=${opt-dir}/lib \n --with-make-prog \n --without-make-prog \n --srcdir=. \n --curdir \n --ruby=C:/Ruby/bin/ruby \n \n I am an extreme newbie to building C extensions, so my Googling for \n details on the zlib library did not do me much good. Any suggestions \n for how to proceed? \n \n```\n\nが出力されます。\n\n2.`gem install zipruby1.9 --platform mswin32` \nネットで紹介されている方法ですが、\n\n```\n\n C:\\>gem install zipruby1.9 --platform mswin32\n ERROR: Could not find a valid gem 'zipruby1.9' (>= 0) in any repository\n ERROR: Possible alternatives: zipruby1.9 \n \n```\n\nとなり入りません。\n\n3.`zlib.h` を入れて(zlib-1.2.3-lib.zip) `gem install zipruby`\n\n```\n\n C:\\>gem install zipruby\n Temporarily enhancing PATH to include DevKit...\n Building native extensions. This could take a while...\n ERROR: Error installing zipruby:\n ERROR: Failed to build gem native extension.\n \n current directory: C:/Ruby193/lib/ruby/gems/1.9.1/gems/zipruby-0.3.6/ext\n C:/Ruby193/bin/ruby.exe -r ./siteconf20170410-2492-i5v1a8.rb extconf.rb\n checking for zlib.h... yes\n checking for main() in -lz... yes\n checking for fseeko()... yes\n checking for ftello()... yes\n checking for mkstemp()... no\n creating Makefile\n \n current directory: C:/Ruby193/lib/ruby/gems/1.9.1/gems/zipruby-0.3.6/ext\n make clean\n \n current directory: C:/Ruby193/lib/ruby/gems/1.9.1/gems/zipruby-0.3.6/ext\n make\n generating zipruby-i386-mingw32.def\n compiling mkstemp.c\n mkstemp.c:51:0: warning: \"S_ISDIR\" redefined\n c:\\ruby193\\devkit\\mingw\\bin\\../lib/gcc/mingw32/4.5.2/../../../../include/sys/sta\n t.h:68:0: note: this is the location of the previous definition\n compiling tmpfile.c\n tmpfile.c: In function 'zipruby_tmpnam':\n tmpfile.c:56:3: warning: implicit declaration of function 'strcpy_s'\n tmpfile.c:62:5: warning: implicit declaration of function '_sopen_s'\n compiling zipruby.c\n compiling zipruby_archive.c\n zipruby_archive.c: In function 'zipruby_archive_get_name':\n zipruby_archive.c:407:5: warning: format '%d' expects type 'int', but argument 3\n has type 'VALUE'\n zipruby_archive.c: In function 'zipruby_archive_add_io':\n zipruby_archive.c:701:81: warning: format '%s' expects type 'char *', but argume\n nt 3 has type 'struct RString *'\n zipruby_archive.c:717:78: warning: format '%s' expects type 'char *', but argume\n nt 3 has type 'struct RString *'\n zipruby_archive.c:726:47: warning: format '%s' expects type 'char *', but argume\n nt 3 has type 'struct RString *'\n zipruby_archive.c: In function 'zipruby_archive_replace_io':\n zipruby_archive.c:780:97: warning: format '%s' expects type 'char *', but argume\n nt 4 has type 'struct RString *'\n zipruby_archive.c:789:66: warning: format '%s' expects type 'char *', but argume\n nt 4 has type 'struct RString *'\n zipruby_archive.c:796:66: warning: format '%s' expects type 'char *', but argume\n nt 4 has type 'struct RString *'\n zipruby_archive.c: In function 'zipruby_archive_read':\n zipruby_archive.c:1447:3: warning: implicit declaration of function 'fopen_s'\n zipruby_archive.c:1471:3: warning: implicit declaration of function '_fclose_nol\n ock'\n compiling zipruby_error.c\n compiling zipruby_file.c\n zipruby_file.c:13:14: warning: 'zipruby_file' declared 'static' but never define\n d\n compiling zipruby_stat.c\n compiling zipruby_zip.c\n compiling zipruby_zip_source_io.c\n compiling zipruby_zip_source_proc.c\n compiling zip_add.c\n compiling zip_add_dir.c\n compiling zip_close.c\n zip_close.c: In function 'zip_close':\n zip_close.c:146:29: warning: assignment discards qualifiers from pointer target\n type\n zip_close.c:153:6: warning: implicit declaration of function 'fseeko'\n zip_close.c:188:2: warning: implicit declaration of function 'ftello'\n zip_close.c: In function 'copy_data':\n zip_close.c:475:11: warning: comparison between signed and unsigned integer expr\n essions\n zip_close.c:475:39: warning: signed and unsigned type in conditional expression\n compiling zip_crypt.c\n zip_crypt.c:25:8: warning: return type defaults to 'int'\n zip_crypt.c: In function 'zipenc_crc32':\n zip_crypt.c:26:3: warning: pointer targets in passing argument 2 of 'crc32' diff\n er in signedness\n c:\\ruby193\\devkit\\mingw\\bin\\../lib/gcc/mingw32/4.5.2/../../../../include/zlib.h:\n 1285:23: note: expected 'const Bytef *' but argument is of type 'char *'\n zip_crypt.c: In function 'init_keys':\n zip_crypt.c:51:17: warning: comparison between signed and unsigned integer expre\n ssions\n zip_crypt.c: In function 'decrypt_data':\n zip_crypt.c:78:17: warning: comparison between signed and unsigned integer expre\n ssions\n zip_crypt.c: In function 'copy_decrypt':\n zip_crypt.c:98:3: warning: comparison of unsigned expression < 0 is always false\n \n zip_crypt.c:109:28: warning: comparison between signed and unsigned integer expr\n essions\n zip_crypt.c:109:28: warning: signed and unsigned type in conditional expression\n zip_crypt.c: In function 'encrypt_data':\n zip_crypt.c:172:17: warning: comparison between signed and unsigned integer expr\n essions\n zip_crypt.c: In function 'copy_encrypt':\n zip_crypt.c:200:28: warning: comparison between signed and unsigned integer expr\n essions\n zip_crypt.c:200:28: warning: signed and unsigned type in conditional expression\n zip_crypt.c: In function '_zip_crypt':\n zip_crypt.c:265:5: warning: implicit declaration of function 'fseeko'\n zip_crypt.c:293:5: warning: implicit declaration of function 'ftello'\n compiling zip_delete.c\n compiling zip_dirent.c\n zip_dirent.c: In function '_zip_cdir_write':\n zip_dirent.c:109:5: warning: implicit declaration of function 'ftello'\n compiling zip_entry_free.c\n compiling zip_entry_new.c\n compiling zip_error.c\n compiling zip_error_clear.c\n compiling zip_error_get.c\n compiling zip_error_get_sys_type.c\n compiling zip_error_strerror.c\n compiling zip_error_to_str.c\n compiling zip_err_str.c\n compiling zip_fclose.c\n compiling zip_file_error_clear.c\n compiling zip_file_error_get.c\n compiling zip_file_get_offset.c\n zip_file_get_offset.c: In function '_zip_file_get_offset':\n zip_file_get_offset.c:64:5: warning: implicit declaration of function 'fseeko'\n compiling zip_file_strerror.c\n compiling zip_fopen.c\n compiling zip_fopen_index.c\n zip_fopen_index.c: In function '_zip_file_fillbuf':\n zip_fopen_index.c:155:5: warning: implicit declaration of function 'fseeko'\n compiling zip_fread.c\n compiling zip_free.c\n compiling zip_get_archive_comment.c\n compiling zip_get_file_comment.c\n compiling zip_get_name.c\n compiling zip_get_num_files.c\n compiling zip_memdup.c\n compiling zip_name_locate.c\n compiling zip_new.c\n compiling zip_open.c\n zip_open.c: In function 'zip_open':\n zip_open.c:84:5: warning: implicit declaration of function 'fseeko'\n zip_open.c:85:5: warning: implicit declaration of function 'ftello'\n compiling zip_rename.c\n compiling zip_replace.c\n compiling zip_set_archive_comment.c\n compiling zip_set_file_comment.c\n compiling zip_set_name.c\n compiling zip_source_buffer.c\n compiling zip_source_file.c\n compiling zip_source_filep.c\n zip_source_filep.c: In function 'read_file':\n zip_source_filep.c:105:2: warning: implicit declaration of function 'fseeko'\n zip_source_filep.c:115:14: warning: comparison between signed and unsigned integer expressions\n zip_source_filep.c:115:38: warning: signed and unsigned type in conditional expression\n compiling zip_source_free.c\n compiling zip_source_function.c\n compiling zip_source_zip.c\n zip_source_zip.c: In function 'read_zip':\n zip_source_zip.c:132:20: warning: comparison between signed and unsigned integer expressions\n zip_source_zip.c:132:44: warning: signed and unsigned type in conditional expression\n zip_source_zip.c:143:14: warning: comparison between signed and unsigned integer expressions\n zip_source_zip.c:143:32: warning: signed and unsigned type in conditional expression\n compiling zip_stat.c\n compiling zip_stat_index.c\n compiling zip_stat_init.c\n compiling zip_strerror.c\n compiling zip_unchange.c\n compiling zip_unchange_all.c\n compiling zip_unchange_archive.c\n compiling zip_unchange_data.c\n linking shared-object zipruby.so\n tmpfile.o: In function `zipruby_tmpnam':\n C:\\Ruby193\\lib\\ruby\\gems\\1.9.1\\gems\\zipruby-0.3.6\\ext/tmpfile.c:56: undefined reference to `strcpy_s'\n C:\\Ruby193\\lib\\ruby\\gems\\1.9.1\\gems\\zipruby-0.3.6\\ext/tmpfile.c:62: undefined reference to `_sopen_s'\n zipruby_archive.o: In function `zipruby_archive_read':\n C:\\Ruby193\\lib\\ruby\\gems\\1.9.1\\gems\\zipruby-0.3.6\\ext/zipruby_archive.c:1447: undefined reference to `fopen_s'\n C:\\Ruby193\\lib\\ruby\\gems\\1.9.1\\gems\\zipruby-0.3.6\\ext/zipruby_archive.c:1471: undefined reference to `_fclose_nolock'\n zip_close.o: In function `add_data':\n C:\\Ruby193\\lib\\ruby\\gems\\1.9.1\\gems\\zipruby-0.3.6\\ext/zip_close.c:293: undefined reference to `ftello'\n C:\\Ruby193\\lib\\ruby\\gems\\1.9.1\\gems\\zipruby-0.3.6\\ext/zip_close.c:312: undefined reference to `ftello'\n C:\\Ruby193\\lib\\ruby\\gems\\1.9.1\\gems\\zipruby-0.3.6\\ext/zip_close.c:314: undefined reference to `fseeko'\n C:\\Ruby193\\lib\\ruby\\gems\\1.9.1\\gems\\zipruby-0.3.6\\ext/zip_close.c:328: undefined reference to `fseeko'\n zip_close.o: In function `zip_close':\n C:\\Ruby193\\lib\\ruby\\gems\\1.9.1\\gems\\zipruby-0.3.6\\ext/zip_close.c:188: undefined reference to `ftello'\n C:\\Ruby193\\lib\\ruby\\gems\\1.9.1\\gems\\zipruby-0.3.6\\ext/zip_close.c:153: undefined reference to `fseeko'\n zip_crypt.o: In function `zip_crypt':\n C:\\Ruby193\\lib\\ruby\\gems\\1.9.1\\gems\\zipruby-0.3.6\\ext/zip_crypt.c:293: undefined reference to `ftello'\n C:\\Ruby193\\lib\\ruby\\gems\\1.9.1\\gems\\zipruby-0.3.6\\ext/zip_crypt.c:265: undefined reference to `fseeko'\n zip_dirent.o: In function `zip_cdir_write':\n C:\\Ruby193\\lib\\ruby\\gems\\1.9.1\\gems\\zipruby-0.3.6\\ext/zip_dirent.c:109: undefined reference to `ftello'\n C:\\Ruby193\\lib\\ruby\\gems\\1.9.1\\gems\\zipruby-0.3.6\\ext/zip_dirent.c:116: undefined reference to `ftello'\n zip_file_get_offset.o: In function `zip_file_get_offset':\n C:\\Ruby193\\lib\\ruby\\gems\\1.9.1\\gems\\zipruby-0.3.6\\ext/zip_file_get_offset.c:64:undefined reference to `fseeko'\n zip_fopen_index.o: In function `zip_file_fillbuf':\n C:\\Ruby193\\lib\\ruby\\gems\\1.9.1\\gems\\zipruby-0.3.6\\ext/zip_fopen_index.c:155: undefined reference to `fseeko'\n C:\\Ruby193\\lib\\ruby\\gems\\1.9.1\\gems\\zipruby-0.3.6\\ext/zip_fopen_index.c:155: undefined reference to `fseeko'\n zip_open.o: In function `zip_checkcons':\n C:\\Ruby193\\lib\\ruby\\gems\\1.9.1\\gems\\zipruby-0.3.6\\ext/zip_open.c:282: undefinedreference to `fseeko'\n zip_open.o: In function `zip_open':\n C:\\Ruby193\\lib\\ruby\\gems\\1.9.1\\gems\\zipruby-0.3.6\\ext/zip_open.c:84: undefined reference to `fseeko'\n C:\\Ruby193\\lib\\ruby\\gems\\1.9.1\\gems\\zipruby-0.3.6\\ext/zip_open.c:85: undefined reference to `ftello'\n zip_open.o: In function `zip_find_central_dir':\n C:\\Ruby193\\lib\\ruby\\gems\\1.9.1\\gems\\zipruby-0.3.6\\ext/zip_open.c:436: undefinedreference to `fseeko'\n zip_open.o: In function `zip_readcdir':\n C:\\Ruby193\\lib\\ruby\\gems\\1.9.1\\gems\\zipruby-0.3.6\\ext/zip_open.c:217: undefinedreference to `fseeko'\n C:\\Ruby193\\lib\\ruby\\gems\\1.9.1\\gems\\zipruby-0.3.6\\ext/zip_open.c:220: undefinedreference to `ftello'\n zip_source_filep.o: In function `read_file':\n C:\\Ruby193\\lib\\ruby\\gems\\1.9.1\\gems\\zipruby-0.3.6\\ext/zip_source_filep.c:105: undefined reference to `fseeko'\n collect2: ld returned 1 exit status\n make: *** [zipruby.so] Error 1\n \n make failed, exit code 2\n \n Gem files will remain installed in C:/Ruby193/lib/ruby/gems/1.9.1/gems/zipruby-0\n .3.6 for inspection.\n Results logged to C:/Ruby193/lib/ruby/gems/1.9.1/extensions/x86-mingw32/1.9.1/zi\n pruby-0.3.6/gem_make.out\n \n```\n\nとなり、やはりエラーとなります。\n\n何方かインストールに成功されている方ご教授お願いします。\n\n* * *\n\n## 環境\n\n * OS:Windows7 x86-64\n * Ruby:1.9.3(mingw32)\n * Development Kit:4.5.2", "comment_count": 2, "content_license": "CC BY-SA 4.0", "creation_date": "2017-04-10T08:55:07.060", "favorite_count": 0, "id": "33904", "last_activity_date": "2020-09-24T14:03:50.510", "last_edit_date": "2019-09-18T07:20:02.933", "last_editor_user_id": "32986", "owner_user_id": "22483", "post_type": "question", "score": 0, "tags": [ "ruby" ], "title": "zipruby が入りません。(Ruby 1.9.3 mingw32 に zipruby 0.3.6)", "view_count": 410 }
[ { "body": "あてずっぽうですが `gem install zipruby --platform mswin32` だとどうですか?", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-10T09:18:28.800", "id": "33905", "last_activity_date": "2017-04-10T09:18:28.800", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "5008", "parent_id": "33904", "post_type": "answer", "score": 0 } ]
33904
null
33905
{ "accepted_answer_id": null, "answer_count": 1, "body": "現在、JenkinsにてAndroidプロジェクト用にCI環境を構築しているのですが、Checkstyleプラグインが動作せずに困っております。\n\n## ■環境\n\nOS:Windows 7 64bit/Ubuntu 16.04 \nJenkins:2.53 \nCheckstyle Plug-in:3.47\n\n## ■発生手順\n\n①Android SDKを用意し、手動でGradleビルドが通る環境を構築(Windows/Linux共に)する。 \n②Jeninisのタスクでシェルの実行で、Gradleビルド追加。チェックスタイル実行を追加。 \n③ビルド実行。\n\n以下の例外が発生し、Checkstyleが正常に完了しない。\n\n== 例外 ==\n\n```\n\n モジュール : 例外により、ファイル /var/lib/jenkins/workspace/LIBERTA-APP TEST/checkstyle-result.xml の処理に失敗しました:\n org.xml.sax.SAXException: Input stream is not a Checkstyle file. at hudson.plugins.checkstyle.parser.CheckStyleParser.parse(CheckStyleParser.java:69)\n at hudson.plugins.analysis.core.AbstractAnnotationParser.parse(AbstractAnnotationParser.java:54)\n at hudson.plugins.analysis.core.FilesParser.parseFile(FilesParser.java:323) \n at hudson.plugins.analysis.core.FilesParser.parseFiles(FilesParser.java:281) \n at hudson.plugins.analysis.core.FilesParser.parserCollectionOfFiles(FilesParser.java:232) \n at hudson.plugins.analysis.core.FilesParser.invoke(FilesParser.java:203) \n at hudson.plugins.analysis.core.FilesParser.invoke(FilesParser.java:31) \n at hudson.FilePath.act(FilePath.java:997) \n at hudson.FilePath.act(FilePath.java:975) \n at hudson.plugins.checkstyle.CheckStylePublisher.perform(CheckStylePublisher.java:78) \n at hudson.plugins.analysis.core.HealthAwarePublisher.perform(HealthAwarePublisher.java:68) \n at hudson.plugins.analysis.core.HealthAwareRecorder.perform(HealthAwareRecorder.java:295) \n at hudson.tasks.BuildStepCompatibilityLayer.perform(BuildStepCompatibilityLayer.java:81) \n at hudson.tasks.BuildStepMonitor$1.perform(BuildStepMonitor.java:20) \n at hudson.model.AbstractBuild$AbstractBuildExecution.perform(AbstractBuild.java:779) \n at hudson.model.AbstractBuild$AbstractBuildExecution.performAllBuildSteps(AbstractBuild.java:720) \n at hudson.model.Build$BuildExecution.post2(Build.java:186) \n at hudson.model.AbstractBuild$AbstractBuildExecution.post(AbstractBuild.java:665) \n at hudson.model.Run.execute(Run.java:1760) \n at hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:43) \n at hudson.model.ResourceController.execute(ResourceController.java:97)\n at hudson.model.Executor.run(Executor.java:405)\n \n```\n\n## ■確認状況\n\nまず、例外の内容を確認しました。\n\n[参考サイト][1]\n\n<https://github.com/jenkinsci/checkstyle-\nplugin/blob/master/src/main/java/hudson/plugins/checkstyle/parser/CheckStyleParser.java>\n\n```\n\n module = (CheckStyle)digester.parse(new InputStreamReader(file, \"UTF-8\"));\n if (module == null) {\n throw new SAXException(\"Input stream is not a Checkstyle file.\");\n }\n \n```\n\n例外は、上記のコード上の69行目で発生しているようでした。\n\nUTF-8文字コード指定されており、チェックスタイルのxmlがS-JISとなっていたので、 \nビルド前に以下のコマンドを追加し、変換を掛けたファイルを使用するようにしました。\n\n```\n\n # iconv -f SHIFT_JIS -t UTF-8 ./codingRule/JavaCodeStyle.xml -o ./codingRule/utf.xml\n \n```\n\njenkinsのworkspaceを確認しましたが、確かに入力ファイルはUTF-8となっているのですが、状況が変わりません。\n\n使用しているcheckstyle.xmlは、\n\n<http://checkstyle.sourceforge.net/google_style.html>\n\nで公開されているgoogleのJavaの規約なのですが、手元のAndorid Studio用のプラグインだと問題無く動作します。 \n試しに、以下の用に何も設定に含まない最小構成の入力ファイルを用意しましたが、結果変わらずです。\n\n== 最小構成のXML ==\n\n```\n\n <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n <module name = \"Checker\">\n </module>\n \n```\n\n1日試行錯誤しましたが、手詰まり状態です。 \nどなたか同じ状況に陥った事がある方、いらっしゃいましたらお力を貸して頂けませんでしょうか。", "comment_count": 5, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-10T09:47:53.813", "favorite_count": 0, "id": "33906", "last_activity_date": "2017-04-11T11:37:02.153", "last_edit_date": "2017-04-10T11:58:09.510", "last_editor_user_id": null, "owner_user_id": "22484", "post_type": "question", "score": 1, "tags": [ "xml", "jenkins" ], "title": "Jenkinsでcheckstyleプラグインを実行するとパーサーエラーで結果が出力されない", "view_count": 1676 }
[ { "body": "もしかしたら \n「ジョブの設定>ビルド後の処理>Checkstyle警告の集計>集計するファイル」に \nスタイル定義ファイル(checkstyle.xml)を設定していませんか?\n\nもし、そのように設定してるなら…\n\nここは、スタイルをチェックした結果を集計するレポートファイルを指定する場所なので \ngradle なら\n\n```\n\n build/reports/checkstyle/*.xml\n \n```\n\nとかになると思います。", "comment_count": 2, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-11T11:37:02.153", "id": "33933", "last_activity_date": "2017-04-11T11:37:02.153", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "4419", "parent_id": "33906", "post_type": "answer", "score": 2 } ]
33906
null
33933
{ "accepted_answer_id": null, "answer_count": 2, "body": "以下のようにwebdriverでFirefox起動時にjavascriptが無効になるように設定しているのですが、設定が反映しません。\n\n```\n\n from selenium import webdriver\n profile = webdriver.FirefoxProfile()\n profile.set_preference(\"javascript.enabled\", False)\n browser = webdriver.Firefox(firefox_profile=profile)\n \n```\n\nFirefoxで `about:config` から値を確認してみると `javascript.enabled` の項目が `true` になっています。 \nFirefoxの `about:config` の画面で `javascript.enabled` をダブルクリックすると `false`\nにはできるのですが、試験の度に手動で`false`に切り替えるというわけにもいかず\n\npython側で `javascript.enabled` の値を指定できる方法を教えて頂けないでしょうか。\n\nバージョンは以下の通りです。 \npython 3.5.1 \nselenium 3.3.3 \nFirefox 51.0.1 (32 ビット) \nWindows 8.1", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-10T10:01:25.960", "favorite_count": 0, "id": "33908", "last_activity_date": "2022-06-13T15:17:39.330", "last_edit_date": "2017-04-10T10:41:18.490", "last_editor_user_id": null, "owner_user_id": null, "post_type": "question", "score": 4, "tags": [ "python", "firefox", "selenium" ], "title": "python seleniumでjavascriptを無効にする", "view_count": 1484 }
[ { "body": "```\n\n browser.get('about:config')\n sleep (3)\n browser.find_element_by_id('warningButton').click()\n browser.find_element_by_id('about-config-search').send_keys('javascript.enabled')\n sleep (3)\n browser.find_element_by_class_name('button-toggle').click()\n \n```", "comment_count": 0, "content_license": "CC BY-SA 4.0", "creation_date": "2019-12-07T06:53:49.937", "id": "61201", "last_activity_date": "2019-12-07T08:53:00.740", "last_edit_date": "2019-12-07T08:53:00.740", "last_editor_user_id": "3068", "owner_user_id": "36969", "parent_id": "33908", "post_type": "answer", "score": 0 }, { "body": "```\n\n from selenium import webdriver\n from selenium.webdriver.firefox.options import Options\n options = Options()\n options.set_preference('javascript.enabled', False)\n browser = webdriver.Firefox(options=options)\n \n```\n\n検証OS: Ubuntu 20.04.4 LTS \n[![スクリーンショット](https://i.stack.imgur.com/Z1O9z.png)](https://i.stack.imgur.com/Z1O9z.png)", "comment_count": 0, "content_license": "CC BY-SA 4.0", "creation_date": "2022-06-13T15:17:39.330", "id": "89373", "last_activity_date": "2022-06-13T15:17:39.330", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "53038", "parent_id": "33908", "post_type": "answer", "score": 1 } ]
33908
null
89373
{ "accepted_answer_id": null, "answer_count": 1, "body": "Google フォームでドメイン内のアンケートを作成しています。 \n現在、回答者のメールアドレスは手入力してもらっているのですが、 \nこれを自動にしてほしいという要望がきています。\n\nもう少し具体的にいうとフォーム送信時のトリガーで \n回答者のメールアドレスをgoogle スクリプト参照できるようにしたいです。\n\n回答者に手入力してもらわずにgoogle スクリプトで回答者のメールアドレスを \n取得することは可能でしょうか。", "comment_count": 1, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-10T12:10:34.987", "favorite_count": 0, "id": "33909", "last_activity_date": "2020-10-14T14:00:25.100", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "18637", "post_type": "question", "score": 0, "tags": [ "google-apps-script" ], "title": "Google フォームでドメイン内の回答者のメールアドレスをgoolge スクリプトから参照したい", "view_count": 3454 }
[ { "body": "「フォーム送信時のトリガーで回答者のメールアドレス」というのは現在ログイン中のユーザーということでよいでしょうか? \n以下のような形で取得可能かと思います。\n\n```\n\n var usr = Session.getActiveUser();\n var email = usr.getEmail();\n \n```\n\n<https://developers.google.com/apps-script/reference/base/session>", "comment_count": 2, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-11T08:51:08.390", "id": "33930", "last_activity_date": "2017-04-11T08:51:08.390", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "19716", "parent_id": "33909", "post_type": "answer", "score": 1 } ]
33909
null
33930
{ "accepted_answer_id": "33916", "answer_count": 1, "body": "OS: Windows7、Windows10 \n.NET Framework: 3.0、4.5 \n開発環境: VisualStudio 2013、VisualStudio 2015\n\n`Popup`の中に`ComboBox`を入れて表示していたのですが、 \n想定していたものとは異なる動作をしました。\n\nXAML\n\n```\n\n <Window \n x:Class=\"SandBox.MainWindow\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n Title=\"MainWindow\" Height=\"100\" Width=\"100\">\n <Grid>\n <Button Click=\"OnClick\">\n <StackPanel>\n <TextBlock Text=\"ボタン\"/>\n <Popup x:Name=\"Popup\" StaysOpen=\"False\">\n <StackPanel>\n <TextBlock Text=\"ポップアップ\" Background=\"White\"/>\n <ComboBox x:Name=\"ComboBox\">\n <ComboBoxItem><TextBlock Text=\"選択肢1\"/></ComboBoxItem>\n <ComboBoxItem><TextBlock Text=\"選択肢2\"/></ComboBoxItem>\n <ComboBoxItem><TextBlock Text=\"選択肢3\"/></ComboBoxItem>\n </ComboBox>\n </StackPanel>\n </Popup>\n </StackPanel>\n </Button>\n </Grid>\n </Window>\n \n```\n\nC#\n\n```\n\n private void OnClick(object sender, RoutedEventArgs e)\n {\n Popup.IsOpen = true;\n DispatcherTimer timer = new DispatcherTimer();\n timer.Tick += delegate\n {\n // Popup.StaysOpen = true;\n ComboBox.IsDropDownOpen = false;\n // Popup.StaysOpen = false;\n timer.Stop();\n };\n timer.Interval = TimeSpan.FromSeconds(3.0);\n timer.Start();\n }\n \n```\n\n操作手順は以下の通りです。\n\n 1. ボタンをクリックします。\n 2. コンボボックスが表示されるので、 \nコンボボックスをクリックしてドロップダウンリストを表示させます。\n\n 3. ドロップダウンリストが表示されたままの状態で、 \nマウスカーソルをウインドウ外へ移動させます。\n\n 4. タイマーが作動しドロップダウンリストが閉じると、ポップアップも閉じてしまいます。 \nこれはマウスカーソルがウインドウ内の場合は起こりません。\n\n実はコメントアウトしている`StaysOpen`を直前と直後に変更する方法で回避はできるのですが、 \n結局`ComboBox`と`Popup`の何が悪さをしているのかまでは分かりませんでした。\n\nこの現象は一体なぜ起きるのでしょうか?", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-10T13:26:00.677", "favorite_count": 0, "id": "33911", "last_activity_date": "2017-04-10T18:14:00.333", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "70", "post_type": "question", "score": 1, "tags": [ "wpf" ], "title": "ComboBoxの動作にPopupが影響を受ける原因は?", "view_count": 653 }
[ { "body": "`Popup.StaysOpen`を`true`に設定している場合、`Popup`は自要素外のマウスイベントを受け取ってポップアップを閉じることになります。ですので内部的にはポップアップウィンドウの表示後にマウスキャプチャーを`SubTree`モードで取得し、閉じられたときに解放するという動作をします。これは`ComboBox`のテンプレートに含まれる`Popup`についても同様です。\n\n質問の事象は`ComboBox`のドロップダウンが閉じられた際にマウスキャプチャーが変更されるのですが、これが`Popup`に移行するとは限らないために発生しています。おそらく`Mouse`や`MouseDevice`の都合でヒットテストが行われているのでしょう。", "comment_count": 1, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-10T18:14:00.333", "id": "33916", "last_activity_date": "2017-04-10T18:14:00.333", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "5750", "parent_id": "33911", "post_type": "answer", "score": 1 } ]
33911
33916
33916
{ "accepted_answer_id": "33940", "answer_count": 1, "body": "ruby on railsでintro.jsを使用ししたいと思っています。複数ページで利用してます。 \nが、inputフィールドに2つintroを設定したところ2つめのところでエラーが出ます。\n\n```\n\n = f.text_field :hoge_sales, class: 'form-control', 'data-step':3, 'data-intro': '売上入力してちょ'\n \n = f.text_field :poge_cost, class: 'form-control', 'data-step':4, 'data-intro': '入力してちょ'\n \n```\n\nコンソールに出ているエラーは↓こんな感じです。解決法ご存知でしたら教えてください。\n\n```\n\n Uncaught TypeError: Cannot set property 'className' of null\n at introjs.self-8070938….js?body=1:18\n (anonymous) @ introjs.self-8070938….js?body=1:18\n \n```\n\njsの中身を見るとエラーが出てる箇所はココのようです。d.querySelectorのとこ\n\n```\n\n b._lastShowElementTimer = setTimeout(function() {\n null != f && (f.innerHTML = a.step);\n h.innerHTML = a.intro;\n s.style.display = \"block\";\n H.call(b, a.element, s, p, f);\n d.querySelector(\".introjs-bullets li > a.active\").className = \"\";\n \n```", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-10T14:12:10.550", "favorite_count": 0, "id": "33912", "last_activity_date": "2017-04-12T02:27:09.380", "last_edit_date": "2017-04-10T23:40:36.560", "last_editor_user_id": "10851", "owner_user_id": "10851", "post_type": "question", "score": 1, "tags": [ "javascript", "ruby-on-rails", "rubygems" ], "title": "intro.js inputに二つ以上設定するとエラーになる", "view_count": 226 }
[ { "body": "複数ページを遷移すると発生する問題らしいです。workroundとしてclassNameに値を入れてあげると動くようになりました。\n\n```\n\n if RegExp('multipage=2', 'gi').test(window.location.search)\n introJs().setOption('showStepNumbers', false).start()\n $('.introjs-bullets li a')[0].className = 'active'\n \n```\n\nもっといい解決方法があれば教えてください", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-12T02:27:09.380", "id": "33940", "last_activity_date": "2017-04-12T02:27:09.380", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "10851", "parent_id": "33912", "post_type": "answer", "score": 0 } ]
33912
33940
33940
{ "accepted_answer_id": "33917", "answer_count": 1, "body": "「Copy Syntax Highlight for OS X」をインストールしまして、 \nAtomの右クリックで使いたいのですが、 \n項目が出てきません。\n\n[http://www.moongift.jp/2015/11/copy-syntax-highlight-for-os-x-\nシンタックスハイライトを適用してコピ/](http://www.moongift.jp/2015/11/copy-syntax-highlight-for-\nos-x-%E3%82%B7%E3%83%B3%E3%82%BF%E3%83%83%E3%82%AF%E3%82%B9%E3%83%8F%E3%82%A4%E3%83%A9%E3%82%A4%E3%83%88%E3%82%92%E9%81%A9%E7%94%A8%E3%81%97%E3%81%A6%E3%82%B3%E3%83%94/)\n\nテキストエディタやsafari上では、項目が出て、正しく使えます。", "comment_count": 2, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-10T16:05:52.780", "favorite_count": 0, "id": "33915", "last_activity_date": "2017-04-10T22:51:17.543", "last_edit_date": "2017-04-10T22:51:17.543", "last_editor_user_id": "8000", "owner_user_id": "12297", "post_type": "question", "score": 0, "tags": [ "macos", "atom-editor" ], "title": "「Copy Syntax Highlight for OS X」がAtomの右クリックに出てこない", "view_count": 80 }
[ { "body": "Atomのコンテキストメニュー(右クリックででるメニュー)はAtom上で独自に制御されており、OSが提供するコンテキストメニューを表示するようにはできておりません。「Copy\nSyntax Highlight for OS\nX」以外にも「サービス(Service)」の項目自体がなく、その他「スピーチ(Speech)」等も無いのがわかるかと思います。全てのメニューがAtom独自にカスタマイズされているからです。\n\nでは、OSが提供するコンテキストメニューを表示するようにするにはどうすれば良いのかというと、設定には表示させるような項目がありませんのでパッケージで実現するしかないと思われます。しかし、そのようなパッケージも見つかりませんでしたので作るしか無いと思います。JavaScriptの知識があれば誰でも作れますので、チャレンジしてみて下さい(実際はCoffeeScriptまたはTypeScript、Babel(ES6以降)で作ることを推奨します)。", "comment_count": 1, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-10T22:20:20.307", "id": "33917", "last_activity_date": "2017-04-10T22:20:20.307", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "7347", "parent_id": "33915", "post_type": "answer", "score": 0 } ]
33915
33917
33917
{ "accepted_answer_id": "33921", "answer_count": 1, "body": "タイトルの通り、vectorの要素をシャッフルしたいのですが毎回同じになってしまい困っています。\n\nどなたか間違いのご指摘お願いできないでしょうかm(_ _)m\n\n**\\-----動作環境-----**\n\n**g++ --version**\n\n```\n\n Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include- dir=/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/De\n veloper/SDKs/MacOSX10.12.sdk/usr/include/c++/4.2.1\n Apple LLVM version 8.0.0 (clang-800.0.42.1)\n Target: x86_64-apple-darwin16.4.0\n Thread model: posix\n InstalledDir: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin\n \n```\n\n**OS info**\n\n```\n\n ProductName: Mac OS X\n ProductVersion: 10.12.3\n BuildVersion: 16D32\n \n```\n\n**コンパイル方法**\n\n```\n\n g++ test.cpp\n \n```\n\n**test.cppの中身**\n\n```\n\n #include <iostream>\n #include <ctime> // time\n #include <cstdlib> // rand\n #include <vector>\n #include <algorithm>\n \n using namespace std;\n \n int main(){\n vector<int> v;\n for(int i=1; i<=5; ++i) v.push_back(i);\n \n cout << \"vector before shuffling : \";\n \n vector<int>::const_iterator iter;\n for(iter=v.begin(); iter!=v.end(); ++iter) cout << *iter << ' ';\n \n cout << endl << endl;\n \n // shuffle vector\n srand(time(0));\n random_shuffle(v.begin(), v.end());\n \n cout << \"vector after shuffling : \";\n for(iter=v.begin(); iter!=v.end(); ++iter) cout << *iter << ' ';\n \n return 0;\n }\n \n```", "comment_count": 8, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-10T23:37:09.450", "favorite_count": 0, "id": "33918", "last_activity_date": "2017-04-11T01:24:32.067", "last_edit_date": "2017-04-11T00:21:11.913", "last_editor_user_id": "18535", "owner_user_id": "18535", "post_type": "question", "score": 1, "tags": [ "c++" ], "title": "vectorの要素をrandom_shuffleを使ってシャッフルしたいが、srand(time(0))とシードの設定をしてもシャッフルが毎回同じになってしまう", "view_count": 983 }
[ { "body": "774RRさんがすでにコメントされていますが、Mac\nOSの実装では`srand(time(0))`で初期化すると短期的には最初の`rand()`の結果が毎秒`16807`ずつ増加するという規則性があります。この仕様により固定的な動作をしてしまう場合があります。詳細は[こちらの回答](https://ja.stackoverflow.com/a/12005/4236)。", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-11T01:24:32.067", "id": "33921", "last_activity_date": "2017-04-11T01:24:32.067", "last_edit_date": "2017-04-13T12:52:38.920", "last_editor_user_id": "-1", "owner_user_id": "4236", "parent_id": "33918", "post_type": "answer", "score": 2 } ]
33918
33921
33921
{ "accepted_answer_id": null, "answer_count": 1, "body": "ExcelでCSV形式(UTF-8)で簡単なデータを作成(1行目が英字、以降数字)し、Rで `read.csv(\"ファイル名\",header=T)`\nで読み込もうとすると\n\n```\n\n make.names(col.names, unique = TRUE) でエラー: \n '<ef>サ<bf>area' に不正なマルチバイト文字があります \n > \n \n```\n\nというエラーが出ます。 \n調べたところ、エンコーディングの問題とあったのですが、UTF-8形式にしているので条件はクリアしているはずなのですがうまくいきません。\n\n解決方法を教えていただけると助かります。", "comment_count": 4, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-11T00:30:40.747", "favorite_count": 0, "id": "33919", "last_activity_date": "2017-07-07T20:33:55.670", "last_edit_date": "2017-04-11T01:23:35.700", "last_editor_user_id": "19110", "owner_user_id": "22488", "post_type": "question", "score": 0, "tags": [ "r", "csv" ], "title": "CSVを読み込もうとすると「不正なマルチバイト文字があります」というエラーが出る", "view_count": 66550 }
[ { "body": "エンコーディングを明示的に指定してください。\n\n```\n\n read.csv(\"ファイル名\", header=T, fileEncoding=\"utf-8\")\n \n```\n\n\\--\n[metropolisさん](https://ja.stackoverflow.com/users/16894/metropolis)の[コメント](https://ja.stackoverflow.com/questions/33919/csv%E3%82%92%E8%AA%AD%E3%81%BF%E8%BE%BC%E3%82%82%E3%81%86%E3%81%A8%E3%81%99%E3%82%8B%E3%81%A8-%E4%B8%8D%E6%AD%A3%E3%81%AA%E3%83%9E%E3%83%AB%E3%83%81%E3%83%90%E3%82%A4%E3%83%88%E6%96%87%E5%AD%97%E3%81%8C%E3%81%82%E3%82%8A%E3%81%BE%E3%81%99-%E3%81%A8%E3%81%84%E3%81%86%E3%82%A8%E3%83%A9%E3%83%BC%E3%81%8C%E5%87%BA%E3%82%8B#comment33426_33919)より。", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-11T01:26:33.967", "id": "33922", "last_activity_date": "2017-07-07T20:33:55.670", "last_edit_date": "2017-07-07T20:33:55.670", "last_editor_user_id": "19110", "owner_user_id": "19110", "parent_id": "33919", "post_type": "answer", "score": 1 } ]
33919
null
33922
{ "accepted_answer_id": null, "answer_count": 1, "body": "```\n\n read.csv(\"ファイル名\", header=T, fileEncoding=\"utf-8\")\n \n```\n\nで読み取りをしようとしたところ、\n\n```\n\n [1] X.\n <0 行> (または長さ 0 の row.names) \n 警告メッセージ: \n 1: read.table(file = file, header = header, sep = sep, quote = quote, で: \n 入力コネクション 'mal.csv' に不正な入力がありました \n 2: read.table(file = file, header = header, sep = sep, quote = quote, で: \n incomplete final line found by readTableHeader on 'mal.csv'\n \n```\n\nのようなエラーがでます。\n\nデータは\n\n```\n\n area walk old cost\n 27.2 13 31 5.6\n 29.7 14 30 6.3\n 50.2 5 13 9\n 43 19 10 9.2\n 37.2 6 9 9.5\n 46.3 13 8 9.8\n 39.5 10 12 10\n 51.8 2 15 11\n 54.7 2 15 11.3\n 62.6 2 15 12.5\n 53.5 8 8 13.1\n \n```\n\nです。(上記はExcelからコピーしましたが、csv形式で保存しているので,区切りになっています)\n\n何が問題か、どう解決するか教えていただけないでしょうか?", "comment_count": 4, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-11T01:13:39.393", "favorite_count": 0, "id": "33920", "last_activity_date": "2017-07-07T20:34:30.223", "last_edit_date": "2017-04-11T04:25:07.573", "last_editor_user_id": "19110", "owner_user_id": "22488", "post_type": "question", "score": 0, "tags": [ "r", "csv" ], "title": "CSVを読み込もうとすると「不正な入力がありました」というエラーが出る", "view_count": 20283 }
[ { "body": "エラーメッセージに `incomplete final line found by ...` とありますので、 `mal.csv`\nの最終行が改行されていない(ファイルの終わりに改行コードがない)のかもしれません。\n\nまた、見た所、カンマ区切りではなくてタブ区切りになっています。タブだけでなく、スペースでも区切られている様ですので、\n`read‌​.table(\"mal.csv\", header=T, ...)` とすれば良いかと思いますが、ヘッダ部分(\n`area.walk.old.cost` )の区切り文字が `.` になっている様に見受けられるのでエラーになってしまいそうです。一度確認して下さい。\n\n\\--\n[metropolisさん](https://ja.stackoverflow.com/users/16894/metropolis)の[コメント1](https://ja.stackoverflow.com/questions/33920/csv%E3%82%92%E8%AA%AD%E3%81%BF%E8%BE%BC%E3%82%82%E3%81%86%E3%81%A8%E3%81%99%E3%82%8B%E3%81%A8-%E4%B8%8D%E6%AD%A3%E3%81%AA%E5%85%A5%E5%8A%9B%E3%81%8C%E3%81%82%E3%82%8A%E3%81%BE%E3%81%97%E3%81%9F-%E3%81%A8%E3%81%84%E3%81%86%E3%82%A8%E3%83%A9%E3%83%BC%E3%81%8C%E5%87%BA%E3%82%8B#comment33431_33920)、[2](https://ja.stackoverflow.com/questions/33920/csv%E3%82%92%E8%AA%AD%E3%81%BF%E8%BE%BC%E3%82%82%E3%81%86%E3%81%A8%E3%81%99%E3%82%8B%E3%81%A8-%E4%B8%8D%E6%AD%A3%E3%81%AA%E5%85%A5%E5%8A%9B%E3%81%8C%E3%81%82%E3%82%8A%E3%81%BE%E3%81%97%E3%81%9F-%E3%81%A8%E3%81%84%E3%81%86%E3%82%A8%E3%83%A9%E3%83%BC%E3%81%8C%E5%87%BA%E3%82%8B#comment33435_33920)より", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-11T04:31:39.693", "id": "33925", "last_activity_date": "2017-07-07T20:34:30.223", "last_edit_date": "2017-07-07T20:34:30.223", "last_editor_user_id": "19110", "owner_user_id": "19110", "parent_id": "33920", "post_type": "answer", "score": 1 } ]
33920
null
33925
{ "accepted_answer_id": "33932", "answer_count": 1, "body": "たまにお世話になっている者です。 \nemacsで操作です。 \n私のemacsでの設定で, C-u 0 l \nでカーソル行をトップ行にできます。 \nこれはかなり使います、でもこの \n「コントロール + u」,「0」「エル」操作 \nは多く、少しでも順序を間違えると編集して \nしまいます。この操作を C-t 「コントロール + t」 \nしたいのですがinit.elの記述で可能でしょうか? \nどのたか教えてもらえればと思います。 \nnagao", "comment_count": 3, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-11T02:39:52.680", "favorite_count": 0, "id": "33923", "last_activity_date": "2017-04-12T05:42:29.490", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "14412", "post_type": "question", "score": 1, "tags": [ "emacs" ], "title": "C-t 操作でカーソル行をトップ行へ持って行く", "view_count": 137 }
[ { "body": "metropolisさんとemasakaさんのコメントで解決できました。ありがとうございます。 \nglobal-binding で良ければ\n\n```\n\n (global-set-key (kbd \"C-t\")\n '(lambda () (interactive) (recenter-top-bottom 0)))\n \n```\n\nただし、デフォルトの `Ctrl`+`t`(`transpose-chars`) が使えなくなります。\n\nちなみに、いまのEmacsだとデフォルトでC-lが`recenter-top-\nbottom`に割り当てられているので、`Ctrl`+`l‌`​を2回打つとカーソル行が画面最上行になる‌​と思います。", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-11T10:39:17.837", "id": "33932", "last_activity_date": "2017-04-12T05:42:29.490", "last_edit_date": "2017-04-12T05:42:29.490", "last_editor_user_id": "2521", "owner_user_id": "14412", "parent_id": "33923", "post_type": "answer", "score": 1 } ]
33923
33932
33932
{ "accepted_answer_id": null, "answer_count": 0, "body": "dockerにCentOS7のコンテナーを準備してzabbix Serverのインストールを試みています。\n\n<http://qiita.com/atanaka7/items/294a639effdb804cfdaa>\n\nのサイトをたよりに \n・Zabbix LLCリポジトリを登録\n\n```\n\n # yum install http://repo.zabbix.com/zabbix/3.0/rhel/7/x86_64/zabbix-release-3.0-1.el7.noarch.rpm\n \n```\n\n・Zabbix関連のパッケージをインストール\n\n```\n\n yum install zabbix-server-mysql zabbix-web-mysql zabbix-web-japanese zabbix-agent\n \n```\n\nしかし、テーブルを作成して初期データを登録しようとしたところ、\n\n```\n\n # zcat /usr/share/doc/zabbix-server-mysql-3.0.0/create.sql.gz | mysql -uroot zabbix\n \n```\n\nのcreate.sql.gzファイルが見つかりません。\n\n他にも検索しましたcreate.sql.gzだけを持ってくるような情報はありませんでした。 \nこちら何かにファイル名が変更されている可能性はありますでしょうか? \nもしくは正常なやり方をご存知であればご教示お願いします。", "comment_count": 15, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-11T05:13:20.990", "favorite_count": 0, "id": "33926", "last_activity_date": "2017-04-11T05:13:20.990", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "8593", "post_type": "question", "score": 2, "tags": [ "zabbix" ], "title": "Zabbix3.0のテーブル作成及び初期データ登録の際のcreate.sql.gzの所在", "view_count": 3217 }
[]
33926
null
null
{ "accepted_answer_id": null, "answer_count": 0, "body": "Json形式のオブジェクトをDataContractJsonSerializerを \nつかってシリアライズ・デシリアライズしています。\n\nここで、DataMemberの名前を動的に変更できるクラスを作成できると非常に楽に書けるのですが、いい方法はありますでしょうか?\n\n```\n\n [DataContract]\n public class TestClass\n {\n [DataMember(Name=\"name\")]\n public string data1{get;set;}\n }\n \n```\n\nこの中の `Name=\"name\"` の部分をコンストラクタなどで動的に変更したいです", "comment_count": 3, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-11T06:03:32.547", "favorite_count": 0, "id": "33927", "last_activity_date": "2017-04-11T06:10:08.540", "last_edit_date": "2017-04-11T06:10:08.540", "last_editor_user_id": "8000", "owner_user_id": "22495", "post_type": "question", "score": 1, "tags": [ "c#", "json" ], "title": "属性 DataMemberAttribute の Name を 動的に変更したい", "view_count": 2070 }
[]
33927
null
null
{ "accepted_answer_id": "33996", "answer_count": 1, "body": "Rails で未ログインの場合だけ view をキャッシュする良い方法はありますでしょうか?\n\nフラグメントキャッシュでできないかと思い、 Google 検索をしてみましたが、情報が見つからなかったため、質問させていただきました。\n\n具体的な利用シーンとしましては、未ログインでもログイン済みでも同じ表示がされるページがあり、そのページは別にある管理画面からの投稿を10〜20件ほど表示をしていまして、そのページの表示を速くするためにキャッシュを利用したいと考えています。\n\n現在、そのページが表示されるのに約1秒かかっています。(Developer tools にて計測しました。)\n\n正確な数字でないですが、体感的には未ログインの場合のアクセスが7割くらいと思われるので、未ログインの場合だけでも表示を速くできればと考えています。\n\n下記のように if 文で分岐すればできるかと思いますが、できれば HTML\nは2回書きたくないということと、導入したいページが比較的多く、パーシャルにするのも少々手間なため、さくっと導入できる方法があったりしないかなと思い、質問をさせていただきました。(わがままですみません^^;)\n\n```\n\n - if user_signed_in?\n %div\n - # ログイン済みの場合の HTML\n - else\n - cache\n %div\n - # 未ログインの場合の HTML\n \n```\n\nと、ここまで書いて思ったこととしましては、キャッシュしたい部分をパーシャルにして、上記のように if 文で分岐するのがスマートかなと思いました。", "comment_count": 2, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-11T07:52:43.453", "favorite_count": 0, "id": "33928", "last_activity_date": "2017-04-14T03:17:32.847", "last_edit_date": "2017-04-12T02:36:27.100", "last_editor_user_id": "8160", "owner_user_id": "8160", "post_type": "question", "score": 1, "tags": [ "ruby-on-rails" ], "title": "Rails で未ログインの場合だけ view をキャッシュする方法", "view_count": 239 }
[ { "body": "> キャッシュしたい部分をパーシャルにして、上記のように if 文で分岐するのがスマートかなと思いました。\n\n以下のように `cache_if` を使用するともう少しスマートになりそうです。\n\n```\n\n - cache_if user_signed_in?, expires_in: 10.minutes\n = render hoge\n \n```\n\n> そのページは別にある管理画面からの投稿を10〜20件ほど表示\n\nどの程度の頻度で管理画面から投稿が追加・修正されるかによって、 `expires_in:`\nの値を設定すれば、キャッシュによって管理画面から追加・修正した投稿が反映されてない、といった事態を防げるのでさらに良いかと思います。\n\n * 参考: \n<http://guides.rubyonrails.org/caching_with_rails.html#fragment-caching>", "comment_count": 1, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-14T03:17:32.847", "id": "33996", "last_activity_date": "2017-04-14T03:17:32.847", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "22531", "parent_id": "33928", "post_type": "answer", "score": 2 } ]
33928
33996
33996
{ "accepted_answer_id": null, "answer_count": 1, "body": "divタグのcssに「overflow-y: scroll;-webkit-overflow-scrolling:\ntouch;」を設定し、iOSのwebviewにて画面の一部を慣性スクロールするように設定をしています。\n\ndivタグ内にリストやテーブルを作成し、各行タップ(touchstart or\ntouchend)により異なるページへ遷移するようにイベントを指定しているのですが、慣性スクロール中にタップすると慣性スクロール前の画面表示の位置にある行がタップされてしまい、意図しないページへ遷移します。\n\n慣性スクロール中にタップした場合、どのようなイベント設定にすると画面表示通りの行タップになるのでしょうか。 \n※画面の一部ではなく、全体のスクロールにした場合は想定通りの動作をします。\n\n以下、簡易なサンプルコードです。\n\n```\n\n <!DOCTYPE html>\n <html>\n <head>\n <style type=\"text/css\">\n div {border:1px solid;width:100%;height:500px;overflow-y:auto;-webkit-overflow-scrolling:touch;}\n ul {list-style:none;}\n li {height:150px; border-bottom:1px solid;}\n </style>\n <script type=\"text/javascript\">\n var onLoad = function () {\n elements = document.getElementsByTagName('li');\n for (var i = 0; i < elements.length; i++) {\n elements[i].addEventListener('touchstart', function (e) {\n console.log(e.target.innerText);\n });\n }\n };\n </script>\n </head>\n <body onLoad=\"onLoad()\">\n <div>\n <ul>\n <li>a</li>\n <li>b</li>\n <li>c</li>\n <li>d</li>\n <li>e</li>\n <li>f</li>\n <li>g</li>\n <li>h</li>\n <li>i</li>\n <li>j</li>\n <li>k</li>\n <li>l</li>\n <li>m</li>\n <li>n</li>\n </ul>\n </div>\n </body>\n </html>\n \n```", "comment_count": 2, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-11T09:14:18.810", "favorite_count": 0, "id": "33931", "last_activity_date": "2018-10-26T05:00:55.837", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "22498", "post_type": "question", "score": 4, "tags": [ "javascript" ], "title": "画面一部の慣性スクロール中のtouchstartイベントによる動作について", "view_count": 1921 }
[ { "body": "自己回答になります。 \n投稿してからしばらく経ちましたが、 \nその後の調査で、UIWebviewの場合のみ起きるようです。 \nブラウザ(Safari、Chrome)、WKWebviewの場合は正常にタップ位置を取得することができました。 \nもしかすると何かしらの方法が存在するかもしれませんが、今回はUIWebviewの仕様ということで自己解決とします。 \nありがとうございました。", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-05-12T06:49:50.903", "id": "34654", "last_activity_date": "2017-05-12T06:49:50.903", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "22498", "parent_id": "33931", "post_type": "answer", "score": 1 } ]
33931
null
34654
{ "accepted_answer_id": null, "answer_count": 1, "body": "## 概要\n\nDockerで作成したPostgreSQLサーバのディレクトリをホストにマウントできず困っています。\n\n* * *\n\n## 質問内容\n\nDockerでPostgreSQLを用いたデータベースコンテナを作成しようとしています。 \npostgres公式のイメージを使用し、データを永続化させるため、 \n/var/lib/postgresql/dataをホストのvolディレクトリにマウントして実行しようとし、 \n以下のコマンドを実行しましたが、コンテナが起動しません。\n\n**実行したコマンド**\n\n```\n\n $ docker run -d -p 5432:5432 -v `pwd`/vol:/var/lib/postgresql/data postgres:9.6.2\n \n```\n\n※-vオプションを指定しなければ、起動することができました。\n\n他のサイトではこの方法でマウントできると書いてありましたが、コンテナが起動しない原因つていて、なにか考えられることはないでしょうか。\n\n環境は以下の通りです。\n\n * Windows 10(64bit)\n * Docker Quickstart Terminal\n * VirtualBox 5.1.0\n\nあまり詳しくないので、常識的な質問でしたら申し訳ありません。 \nよろしくお願いいたします。", "comment_count": 3, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-11T15:51:18.400", "favorite_count": 0, "id": "33937", "last_activity_date": "2018-07-14T00:11:10.973", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "22502", "post_type": "question", "score": 0, "tags": [ "postgresql", "docker" ], "title": "DockerでpostgresqlDBの永続化について", "view_count": 870 }
[ { "body": "VirtualBoxではdockerを使っていないのですが、``pwd`` が余計では? \n``pwd`/vol` の部分を絶対パスにしてみてはいかがでしょうか。", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-11-28T14:27:15.370", "id": "39916", "last_activity_date": "2017-11-29T02:29:24.903", "last_edit_date": "2017-11-29T02:29:24.903", "last_editor_user_id": "19110", "owner_user_id": "26367", "parent_id": "33937", "post_type": "answer", "score": -1 } ]
33937
null
39916
{ "accepted_answer_id": null, "answer_count": 1, "body": "MAMPでPythonのWebアプリケーション開発を行っているのですが, PythonのMySQL-Pythonがエラーでインストールできません.\n調べてみたところMySQL-Pythonのインストールに関してエラーが発生するケースが多いようですが, 色々調べて試してみたもののうまくいきません. \n以下, ターミナルのログです.\n\n## エラー\n\n```\n\n $ sudo pip install mysql-python\n The directory '/Users/Owner/Library/Caches/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.\n The directory '/Users/Owner/Library/Caches/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.\n Collecting mysql-python\n Downloading MySQL-python-1.2.5.zip (108kB)\n 100% |████████████████████████████████| 112kB 1.2MB/s \n Installing collected packages: mysql-python\n Running setup.py install for mysql-python ... error\n Complete output from command /usr/bin/python -u -c \"import setuptools, tokenize;__file__='/private/tmp/pip-build-2QuhFE/mysql-python/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\\r\\n', '\\n');f.close();exec(compile(code, __file__, 'exec'))\" install --record /tmp/pip-wx4saf-record/install-record.txt --single-version-externally-managed --compile:\n running install\n running build\n running build_py\n creating build\n creating build/lib.macosx-10.12-intel-2.7\n copying _mysql_exceptions.py -> build/lib.macosx-10.12-intel-2.7\n creating build/lib.macosx-10.12-intel-2.7/MySQLdb\n copying MySQLdb/__init__.py -> build/lib.macosx-10.12-intel-2.7/MySQLdb\n copying MySQLdb/converters.py -> build/lib.macosx-10.12-intel-2.7/MySQLdb\n copying MySQLdb/connections.py -> build/lib.macosx-10.12-intel-2.7/MySQLdb\n copying MySQLdb/cursors.py -> build/lib.macosx-10.12-intel-2.7/MySQLdb\n copying MySQLdb/release.py -> build/lib.macosx-10.12-intel-2.7/MySQLdb\n copying MySQLdb/times.py -> build/lib.macosx-10.12-intel-2.7/MySQLdb\n creating build/lib.macosx-10.12-intel-2.7/MySQLdb/constants\n copying MySQLdb/constants/__init__.py -> build/lib.macosx-10.12-intel-2.7/MySQLdb/constants\n copying MySQLdb/constants/CR.py -> build/lib.macosx-10.12-intel-2.7/MySQLdb/constants\n copying MySQLdb/constants/FIELD_TYPE.py -> build/lib.macosx-10.12-intel-2.7/MySQLdb/constants\n copying MySQLdb/constants/ER.py -> build/lib.macosx-10.12-intel-2.7/MySQLdb/constants\n copying MySQLdb/constants/FLAG.py -> build/lib.macosx-10.12-intel-2.7/MySQLdb/constants\n copying MySQLdb/constants/REFRESH.py -> build/lib.macosx-10.12-intel-2.7/MySQLdb/constants\n copying MySQLdb/constants/CLIENT.py -> build/lib.macosx-10.12-intel-2.7/MySQLdb/constants\n running build_ext\n building '_mysql' extension\n creating build/temp.macosx-10.12-intel-2.7\n cc -fno-strict-aliasing -fno-common -dynamic -arch i386 -arch x86_64 -g -Os -pipe -fno-common -fno-strict-aliasing -fwrapv -DENABLE_DTRACE -DMACOSX -DNDEBUG -Wall -Wstrict-prototypes -Wshorten-64-to-32 -DNDEBUG -g -fwrapv -Os -Wall -Wstrict-prototypes -DENABLE_DTRACE -arch i386 -arch x86_64 -pipe -Dversion_info=(1,2,5,'final',1) -D__version__=1.2.5 -I/usr/local/Cellar/mysql/5.7.14/include/mysql -I/System/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -c _mysql.c -o build/temp.macosx-10.12-intel-2.7/_mysql.o -fno-omit-frame-pointer\n In file included from _mysql.c:44:\n /usr/local/Cellar/mysql/5.7.14/include/mysql/my_config.h:174:9: warning: 'SIZEOF_LONG' macro redefined [-Wmacro-redefined]\n #define SIZEOF_LONG 8\n ^\n /System/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7/pymacconfig.h:54:17: note: previous definition is here\n # define SIZEOF_LONG 4\n ^\n In file included from _mysql.c:44:\n /usr/local/Cellar/mysql/5.7.14/include/mysql/my_config.h:179:9: warning: 'SIZEOF_TIME_T' macro redefined [-Wmacro-redefined]\n #define SIZEOF_TIME_T 8\n ^\n /System/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7/pymacconfig.h:57:17: note: previous definition is here\n # define SIZEOF_TIME_T 4\n ^\n _mysql.c:1589:10: warning: comparison of unsigned expression = sizeof(row_converters)) {\n ~~~ ^ ~\n 3 warnings generated.\n _mysql.c:287:14: warning: implicit conversion loses integer precision: 'Py_ssize_t' (aka 'long') to 'int' [-Wshorten-64-to-32]\n cmd_argc = PySequence_Size(cmd_args);\n ~ ^~~~~~~~~~~~~~~~~~~~~~~~~\n _mysql.c:317:12: warning: implicit conversion loses integer precision: 'Py_ssize_t' (aka 'long') to 'int' [-Wshorten-64-to-32]\n groupc = PySequence_Size(groups);\n ~ ^~~~~~~~~~~~~~~~~~~~~~~\n _mysql.c:470:14: warning: implicit conversion loses integer precision: 'Py_ssize_t' (aka 'long') to 'int' [-Wshorten-64-to-32]\n int j, n2=PySequence_Size(fun);\n ~~ ^~~~~~~~~~~~~~~~~~~~\n _mysql.c:1127:9: warning: implicit conversion loses integer precision: 'unsigned long' to 'int' [-Wshorten-64-to-32]\n len = mysql_real_escape_string(&(self->connection), out, in, size);\n ~ ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n _mysql.c:1129:9: warning: implicit conversion loses integer precision: 'unsigned long' to 'int' [-Wshorten-64-to-32]\n len = mysql_escape_string(out, in, size);\n ~ ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n _mysql.c:1168:9: warning: implicit conversion loses integer precision: 'Py_ssize_t' (aka 'long') to 'int' [-Wshorten-64-to-32]\n size = PyString_GET_SIZE(s);\n ~ ^~~~~~~~~~~~~~~~~~~~\n /System/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7/stringobject.h:92:32: note: expanded from macro 'PyString_GET_SIZE'\n #define PyString_GET_SIZE(op) Py_SIZE(op)\n ^~~~~~~~~~~\n /System/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7/object.h:116:56: note: expanded from macro 'Py_SIZE'\n #define Py_SIZE(ob) (((PyVarObject*)(ob))->ob_size)\n ~~~~~~~~~~~~~~~~~~~~~~^~~~~~~\n _mysql.c:1178:9: warning: implicit conversion loses integer precision: 'unsigned long' to 'int' [-Wshorten-64-to-32]\n len = mysql_real_escape_string(&(self->connection), out+1, in, size);\n ~ ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n _mysql.c:1180:9: warning: implicit conversion loses integer precision: 'unsigned long' to 'int' [-Wshorten-64-to-32]\n len = mysql_escape_string(out+1, in, size);\n ~ ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n _mysql.c:1274:11: warning: implicit conversion loses integer precision: 'Py_ssize_t' (aka 'long') to 'int' [-Wshorten-64-to-32]\n if ((n = PyObject_Length(o)) == -1) goto error;\n ~ ^~~~~~~~~~~~~~~~~~\n /System/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7/abstract.h:434:25: note: expanded from macro 'PyObject_Length'\n #define PyObject_Length PyObject_Size\n ^\n _mysql.c:1466:10: warning: implicit conversion loses integer precision: 'unsigned long' to 'int' [-Wshorten-64-to-32]\n len = strlen(buf);\n ~ ^~~~~~~~~~~\n _mysql.c:1468:10: warning: implicit conversion loses integer precision: 'unsigned long' to 'int' [-Wshorten-64-to-32]\n len = strlen(buf);\n ~ ^~~~~~~~~~~\n _mysql.c:1504:11: warning: implicit conversion loses integer precision: 'unsigned long' to 'int' [-Wshorten-64-to-32]\n len = strlen(buf);\n ~ ^~~~~~~~~~~\n _mysql.c:1506:11: warning: implicit conversion loses integer precision: 'unsigned long' to 'int' [-Wshorten-64-to-32]\n len = strlen(buf);\n ~ ^~~~~~~~~~~\n _mysql.c:1589:10: warning: comparison of unsigned expression = sizeof(row_converters)) {\n ~~~ ^ ~\n 14 warnings generated.\n cc -bundle -undefined dynamic_lookup -arch i386 -arch x86_64 -Wl,-F. build/temp.macosx-10.12-intel-2.7/_mysql.o -L/usr/local/Cellar/mysql/5.7.14/lib -lmysqlclient -lssl -lcrypto -o build/lib.macosx-10.12-intel-2.7/_mysql.so\n ld: library not found for -lssl\n clang: error: linker command failed with exit code 1 (use -v to see invocation)\n error: command 'cc' failed with exit status 1\n \n ----------------------------------------\n Command \"/usr/bin/python -u -c \"import setuptools, tokenize;__file__='/private/tmp/pip-build-2QuhFE/mysql-python/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\\r\\n', '\\n');f.close();exec(compile(code, __file__, 'exec'))\" install --record /tmp/pip-wx4saf-record/install-record.txt --single-version-externally-managed --compile\" failed with error code 1 in /private/tmp/pip-build-2QuhFE/mysql-python/\n```\n\n## Pythonのバージョン\n\n2.7.10です.\n\n```\n\n $ python --version\n Python 2.7.10\n```\n\nご教授お願いいたします.", "comment_count": 2, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-11T15:54:18.537", "favorite_count": 0, "id": "33938", "last_activity_date": "2022-05-04T06:05:00.560", "last_edit_date": "2021-02-05T16:26:27.030", "last_editor_user_id": "3060", "owner_user_id": "22465", "post_type": "question", "score": 0, "tags": [ "python", "mysql", "macos", "pip" ], "title": "macOS Sierra 10.12.4でMySQL-Pythonがインストールできない (pip)", "view_count": 641 }
[ { "body": "`pip freeze` で pyOpenSSL が入っていることは確認したのですが, どうやらバージョンが古すぎたようです.\n\n`brew unlink openssl && brew link openssl --force` を実行したところ新しいバージョンにリンクされたようで,\nその後は `$ sudo pip install MySQL-Python` でインストールに成功しました.\n\n[error installing psycopg2, library not found for\n-lssl](http://stackoverflow.com/questions/26288042/error-installing-\npsycopg2-library-not-found-for-lssl)\n\n* * *\n\n_この投稿は[@david_0717\nさんのコメント](https://ja.stackoverflow.com/questions/33938/macos-\nsierra-10-12-4%e3%81%a7mysql-\npython%e3%81%8c%e3%82%a4%e3%83%b3%e3%82%b9%e3%83%88%e3%83%bc%e3%83%ab%e3%81%a7%e3%81%8d%e3%81%aa%e3%81%84-pip#comment33475_33938)\nの内容を元に コミュニティwiki として投稿しました。_", "comment_count": 0, "content_license": "CC BY-SA 4.0", "creation_date": "2020-09-02T02:10:16.427", "id": "70067", "last_activity_date": "2020-09-02T02:10:16.427", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "3060", "parent_id": "33938", "post_type": "answer", "score": 1 } ]
33938
null
70067
{ "accepted_answer_id": "33947", "answer_count": 1, "body": "buildrootで生成したlinuxをqemuで実行したところ、ホスト-ゲスト間のネットワークが疎通しません。 \nホスト環境は、ubuntu 16.04 LTS。 qemuは、ubuntuのパッケージをそのまま使用しており\n\n```\n\n qemu-system-arm -version\n QEMU emulator version 2.5.0 (Debian 1:2.5+dfsg-5ubuntu10.10), Copyright (c) 2003-2008 Fabrice Bellard\n \n```\n\nです。 \nqemuの起動は、以下のコマンドで起動しています。\n\n```\n\n sudo qemu-system-arm -machine vexpress-a9 -smp cores=4 -kernel output/images/zImage \\\n -drive file=output/images/rootfs.ext2,if=sd,format=raw -append \"root=/dev/mmcblk0 rw console=ttyAMA0\" \\\n -dtb output/images/vexpress-v2p-ca9.dtb -m 512 -serial mon:stdio -nographic \\\n -net nic -netdev tap,id=guest0,ifname=tap0\n \n```\n\n起動後、ホストOSの別ターミナルで\n\n```\n\n $sudo ifconfig tap0 inet 192.168.0.1\n \n```\n\nとし、ゲストOSで\n\n```\n\n #ifconfig eth0 inet 192.168.0.2\n \n```\n\nとしてます。 \nここで、ゲストOSから\n\n```\n\n #ping 192.168.0.1\n \n```\n\nとしても、応答が帰ってきません。\n\n気になる点として、qemuの起動時に\n\n> Warning: vlan 0 is not connected to host network \n> Warning: netdev tap0 has no peer\n\nというwarningがでます。\n\nゲストOSのNICがホストOSのtap0につながっていると考えているのですが、 \nなにか根本的に勘違いしているのでしょうか?\n\nホスト-ゲスト間のネットワークを疎通させるにはどうすればいいのでしょうか?", "comment_count": 2, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-12T02:14:29.070", "favorite_count": 0, "id": "33939", "last_activity_date": "2017-04-12T08:36:25.703", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "7844", "post_type": "question", "score": 1, "tags": [ "linux" ], "title": "qemuでホスト-ゲスト間のネットワークが疎通しない", "view_count": 2663 }
[ { "body": "自己回答です。 \nqemu-system-arm のオプション`-net nic`を`-net nic,netdev=guest0`とすることで解決しました。", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-12T08:36:25.703", "id": "33947", "last_activity_date": "2017-04-12T08:36:25.703", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "7844", "parent_id": "33939", "post_type": "answer", "score": 2 } ]
33939
33947
33947
{ "accepted_answer_id": "33943", "answer_count": 2, "body": "pdfファイルをダウンロードするのではなくブラウザのタブ表示をしたいのですが、以下同じコードで、pdfファイルをブラウザ表示できるサイトとどうしてもダウンロードしてしまうサイトがあります。 \nサーバ環境によるのでしょうか?\n\n```\n\n <p><a href=\"/pdf/abc.pdf\" target=\"_blank\"><font>&nbsp&nbsp</font> pdfのダウンロード</a></p>\n \n```\n\nサーバ移行でlaravelに移し換えようとして、この事象が発生しました。 \n旧本番サイトだとできるのに、開発環境だとできない事象です。 \nlinux(centOS)のバージョン違い、ファイルの権限、webサーバの違いなど考えられるでしょうか?", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-12T06:20:58.393", "favorite_count": 0, "id": "33941", "last_activity_date": "2017-04-12T06:47:58.717", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "15167", "post_type": "question", "score": 2, "tags": [ "html", "linux", "laravel", "pdf" ], "title": "webサーバにあるpdfをブラウザで表示したいです。", "view_count": 17361 }
[ { "body": "WEBサーバの設定を確認するとよいと思います。 \n応答するPDFファイルの`Content-Type`が`application/pdf`だとWEBブラウザで直接表示しませんか?\n(`application/octet-stream`あたりだと、WEBブラウザが「保存」する動作する場合が多いと思います) \nあと、`Content-Disposition`の有無でWEBブラウザの挙動が変わったと思います。\n\n(いずれにせよ、WEBブラウザの設定にもよるので、そちらも確認したほうがよいと思います)", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-12T06:46:20.433", "id": "33942", "last_activity_date": "2017-04-12T06:46:20.433", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "20098", "parent_id": "33941", "post_type": "answer", "score": 6 }, { "body": "pdfファイルをプレビューするのはあくまでブラウザの実装です。これを含めこうしたブラウザ側の挙動を強要する権限も手法もサーバー側には存在しないとする解釈が一般的です。 \nそのうえでのお話ですが、私も利用しているfirefoxなんかはデフォルトプロファイルだとpdfをプレビューしてくれます。便利です。この機能について言及していると仮定して述べると、私見ではサーバー側のレスポンス、すなわちサイトの設定に依存すると思われます。\n\n例: \n\\- プレビューが開く:[MISRA-C:2004から2012への移行の課題 -\nIPA](https://www.ipa.go.jp/files/000043914.pdf) \n\\- ダウンロードダイアログが開く:[AMENDMENT\nC99](http://www.southgippsland.vic.gov.au/download/downloads/id/496/c99_new_eso8_map.pdf)\n\n両者のサーバーレスポンスを見ると、\n\n```\n\n HTTP/1.1 200 OK\n Date: Wed, 12 Apr 2017 06:38:06 GMT\n Server: Apache\n Last-Modified: Wed, 08 Mar 2017 06:21:47 GMT\n Etag: \"14712e-15a5ff-54a3224a51291\"\n Accept-Ranges: bytes\n Content-Length: 1418751\n Connection: close\n Content-Type: application/pdf\n \n HTTP/1.1 200 OK\n Date: Wed, 12 Apr 2017 06:36:41 GMT\n Server: Apache\n Expires: Mon, 26 Jul 1997 05:00:00 GMT\n Cache-Control: must-revalidate, post-check=0, pre-check=0\n Content-Disposition: attachment; filename=\"Amendment_C99_ESO8_Map_for_adoption.pdf\"\n Pragma: public\n Set-Cookie: TestCookie=Test; path=/; domain=www.southgippsland.vic.gov.au; httponly\n X-Frame-Options: SAMEORIGIN\n Content-Length: 114417\n Keep-Alive: timeout=5, max=100\n Connection: Keep-Alive\n Content-Type: application/pdf\n \n```\n\nという状況です。注目するのは後者の[Content-Disposition](https://developer.mozilla.org/en-\nUS/docs/Web/HTTP/Headers/Content-Disposition)ヘッダです。MDNを引用しますと\n\n> The first parameter in the HTTP context is either inline (default value,\n> indicating it can be display inside the Web page, or as the Web page) or\n> **attachment (indicating it should be downloaded; most browsers presenting a\n> 'Save as' dialog** , prefilled with the value of the filename parameters if\n> present\n\nということで、`Content-Disposition:\nattachment`ヘッダが指定されたレスポンス時には、プレビューではなくダウンロード用のダイアログを表示するのが理想的な実装とされています。おそらく(少なくともfirefoxは)これに従った挙動をしますので、ご指摘のような結果が生ずるものと思われます。\n\n本回答での結論として、\n\n 1. プレビューするかはブラウザ依存、サーバーでは基本的に制御できない。\n 2. `Content-Disposition`ヘッダで挙動を指定することができる **かもしれない** 。\n 3. 必ず表示したいならば、独自にクライアントサイドで実装する必要がある。\n\nとさせていただきます。以上、参考になれば幸いです。", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-12T06:47:58.717", "id": "33943", "last_activity_date": "2017-04-12T06:47:58.717", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": null, "parent_id": "33941", "post_type": "answer", "score": 6 } ]
33941
33943
33942
{ "accepted_answer_id": "33967", "answer_count": 2, "body": "お世話になっております。\n\n現在、AndroidのGmail側でHTMLタイプのメールに、URLスキームのリンクを貼ってアプリ起動できないかを試しております。\n\nしかし、なぜかリンクがテキスト形式になってしまい、タップできない状態です。 \n※iphoneのGmailアプリだとリンクタップでアプリが起動できる。\n\n具体的にはHTMLタイプのメールを以下にして、送信しております。\n\n```\n\n <html>\n <body>\n <a href='comgooglemaps:'>アプリ起動</a>\n </body>\n </html>\n \n```\n\n解決方法がありましたら、ご教示ください。", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-12T08:33:44.903", "favorite_count": 0, "id": "33946", "last_activity_date": "2017-04-14T03:14:23.457", "last_edit_date": "2017-04-14T03:14:23.457", "last_editor_user_id": "3510", "owner_user_id": "22519", "post_type": "question", "score": 0, "tags": [ "android", "gmail" ], "title": "AndroidのGmailアプリにおける、URLスキーム利用について", "view_count": 5297 }
[ { "body": "推測ですが、Gmailアプリがリンクだと認識できないためテキスト形式の表示になっていると考えられます。\n\n下記のように`//`を追加してみてはどうでしょうか?\n\n```\n\n <a href='comgooglemaps://'>アプリ起動</a>\n \n```\n\nまたは、ホスト部を追加してみてください。\n\n```\n\n <a href='comgooglemaps://host/'>アプリ起動</a>\n \n```\n\n余談ですが、上記のリンクの場合、アプリがインストールされていない場合はエラーページが表示される可能性があるので、[こちらの回答](https://ja.stackoverflow.com/a/32082/21081)を参考にしてみてください。", "comment_count": 3, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-12T09:49:07.123", "id": "33951", "last_activity_date": "2017-04-12T09:55:27.767", "last_edit_date": "2017-04-13T12:52:38.920", "last_editor_user_id": "-1", "owner_user_id": "21081", "parent_id": "33946", "post_type": "answer", "score": 0 }, { "body": "URLスキームをリンクとして認識させる方法ではありませんが、下記のようなサービスを利用することでGmailから任意のアプリを起動させるという目的は達成できるかもしれません。 \n<https://branch.io/>\n\n参考 \n<https://stackoverflow.com/questions/38778618/cant-get-gmail-for-android-to-\nopen-a-custom-url-scheme-or-an-intent-url>", "comment_count": 1, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-13T00:55:23.077", "id": "33967", "last_activity_date": "2017-04-13T00:55:23.077", "last_edit_date": "2017-05-23T12:38:56.083", "last_editor_user_id": "-1", "owner_user_id": "14540", "parent_id": "33946", "post_type": "answer", "score": 0 } ]
33946
33967
33951
{ "accepted_answer_id": "33959", "answer_count": 1, "body": "初めてAWSでEC2の設定をしています。 \nPHPとImageMagickをインストールしたのですが、PNGが変換できません。\n\nPHPのログを見ると、\n\n```\n\n [0] => convert: no decode delegate for this image format `PNG' @ error/constitute.c/ReadImage/509.\n \n```\n\nと出ていましたので、色々調べて、「libpng 」をインストールしました。 \nしかし、何度やってもPNGが使えるようになりません。\n\nImageMagickのディレクトリで、`sudo ./configure` と打つと、\n\n```\n\n PNG --with-png=yes no\n \n```\n\nと出ています。\n\nインストールしたものは以下となります。\n\n```\n\n [ec2-user@ip-XXX-XX-XX-XX src]$ ls\n autoconf-latest ImageMagick.tar.gz m4-1.4.18.tar.gz\n autoconf-latest.tar.gz libpng-1.6.29 zlib-1.2.11\n download libpng-1.6.29.tar.gz zlib-1.2.11.tar.gz\n ImageMagick-7.0.5-4 m4-1.4.18\n \n```\n\nImageMagickのパスにlibpngが通っていない気がするのですが、 \nどこをどうチェックすればいいのかわかりません。\n\nどなたか、どこをどうチェックすれば、何が足りないのかわかるようになるか、 \n教えていただけないでしょうか?\n\nどうぞよろしくお願い致します。\n\n※追記です。 \nlibpng のインストールの具体的な手順は以下です。\n\n```\n\n cd /usr/local/src/\n sudo wget http://prdownloads.sourceforge.net/libpng/libpng-1.6.29.tar.gz\n sudo tar zxvf libpng-1.6.29.tar.gz\n cd libpng-1.6.29\n sudo ./configure --enable--shared\n sudo make\n sudo make install\n \n```\n\n`./configure --enable--shared` のところは、よくわかっていません。 \n(編集者注: `--enable--shared` は必要ありません) \n<http://d.hatena.ne.jp/orz---orz/20070329> のサイトを参考にしました。", "comment_count": 8, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-12T09:15:48.007", "favorite_count": 0, "id": "33948", "last_activity_date": "2017-04-12T15:04:31.677", "last_edit_date": "2017-04-12T14:59:05.573", "last_editor_user_id": "3054", "owner_user_id": "18800", "post_type": "question", "score": 1, "tags": [ "linux", "imagemagick" ], "title": "自分で make した ImageMagick が PNG を扱えません", "view_count": 2531 }
[ { "body": "質問者さんは、ディストリビューションのパッケージ管理ツールである `yum` で libpng をインストールし解決されています。 \n以下は雑多な参考情報です。\n\n* * *\n\nまずは、`config.log` を \"png\" などのキーワードで検索し、状況を調査するのがよいです。\n\n### ライブラリのチェック\n\n例えば、libpng がインストール出来ているかのチェックには `pkg-config` コマンドが使えます。 \n以下は実際に、ImageMagick の configure が行なっている方法です。\n\n```\n\n # インストール出来ていれば何も出力されないはず\n pkg-config --exists --print-errors \"libpng >= 1.0.0\"\n \n```\n\n* * *\n\n`pkg-config` がライブラリの情報を探す場所(`search path`)は、やはり `pkg-config` コマンドで確認出来ます。\n\n```\n\n pkg-config --variable pc_path pkg-config\n # 私の環境では以下が出力されます\n # /usr/local/lib/x86_64-linux-gnu/pkgconfig:/usr/local/lib/pkgconfig:/usr/local/share/pkgconfig:/usr/lib/x86_64-linux-gnu/pkgconfig:/usr/lib/pkgconfig:/usr/share/pkgconfig\n \n```\n\n野良ビルドしたライブラリは大抵 `/usr/local/` 以下にインストールしますから、上記のパスに `/usr/local/`\n以下が含まれている必要があります。 \nもし含まれていなければ、\n\n```\n\n # 例: 常に必要ならば ~/.profile などに記入\n export PKG_CONFIG_PATH=/usr/local/lib/pkgconfig\n \n```\n\nのように、追加する事になります。\n\n### コンパイルのやり直し\n\nコンパイルを `./configure` からやり直す場合には、`make clean` も行なった方がよいです。 \n(これが必要なのに忘れた場合、make が「やる事がない」と言ってくるので気付くとは思いますが)\n\n```\n\n # 例えば ImageMagick のコンパイル・インストールをやり直すなら、たぶんこんな感じ\n ./configure\n make clean\n make\n sudo make install\n \n```\n\n### sudo を使う箇所\n\n全てのコマンドに `sudo` をつけるのは危険です。 \nこれだと `root` で作業するのと変わりません。 \nファイルの所有者を気にされているようですが、コンパイルは一般ユーザで進めて大丈夫です。 \nコンパイルなどは一般ユーザの権限で、 **一般ユーザが書き込めるディレクトリで** 行ない、インストール(`make install`)にだけ `sudo`\nを用いるのが定石です。\n\n### パッケージシステムの利用\n\n必要な物を全てパッケージシステム外でコンパイルしてインストールなさっているようですが、これをやるならば、結構な作業量を覚悟する必要があります。 \n学習目的でないならば、こういった野良ビルドは最小限にした方がよいです。\n\n例えば、ディストリビューションが提供する ImageMagick のパッケージが古すぎるとしても、他のパッケージ(autoconf、libpng\nなど)は大丈夫かも知れません。 \nまた、ImagiMagick 公式の RPM パッケージもありますね。 \n楽はしておいた方がよいと思います。", "comment_count": 5, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-12T13:08:19.970", "id": "33959", "last_activity_date": "2017-04-12T15:04:31.677", "last_edit_date": "2017-04-12T15:04:31.677", "last_editor_user_id": "3054", "owner_user_id": "3054", "parent_id": "33948", "post_type": "answer", "score": 1 } ]
33948
33959
33959
{ "accepted_answer_id": "33988", "answer_count": 1, "body": "GTKでテキストウィジェットのテキストのスタイルを変えられますか?\n\n 1. 色\n 2. フォント\n 3. 書体\n\nリファレンスなどで探したのですが最新のバージョンで使えるものがありません。", "comment_count": 1, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-12T09:44:31.460", "favorite_count": 0, "id": "33950", "last_activity_date": "2017-04-13T15:48:21.163", "last_edit_date": "2017-04-13T15:41:27.007", "last_editor_user_id": "3054", "owner_user_id": "21169", "post_type": "question", "score": 1, "tags": [ "c", "gtk", "gui" ], "title": "GTKでTextViewウィジェットのテキストのスタイルを変える", "view_count": 984 }
[ { "body": "## 概要\n\nまずは、[Text Widget\nOverview](https://developer.gnome.org/gtk3/stable/TextWidget.html)\nで概要をつかむのがよさそうです。 \nスタイルの変更に関係が深そうな前半は、ざっと次のような内容です。\n\n### バッファとビュー\n\n`GtkTextBuffer` は編集中のテキストを表現する(バッファ)。 \nウィジェット `GtkTextView` は `GtkTextBuffer` を表示する(ビュー)。 \nバッファは任意の数のビューで表示出来る。\n\n### エンコーディング、文字のカウント\n\nGTK+ におけるテキストのエンコーディングは UTF-8。 \nつまり、1文字が2バイト以上になり得る。 \n何文字目か、のカウントはオフセット(offsets)と呼ばれる。 \n何バイト目か、のカウントはインデックス(indexes)と呼ばれる。\n\n### タグ\n\nバッファ内のテキストはタグ(tag)でマーク(mark)する事が出来る。 \nタグとはテキストのある範囲に付与する属性。 \n例えば、あるタグを \"bold\" と名付け、そのタグ内のテキストを太字にする、といった事が出来る。 \nただし、タグはテキストの外観に影響を与えるためだけにあるのではない。 \nマウスやキーボードでの操作への影響、テキストの一定範囲を編集不可にする、など様々な用途に使用される。 \nタグは `GtkTextTag` オブジェクトで表現される。 \n一つの `GtkTextTag` を、任意の数のバッファ内の任意の数のテキスト範囲に付与出来る。\n\n各タグは `GtkTextTagTable` (タグテーブル)に格納される。 \nタグテーブルは一緒に使用できるタグの集合を定義する。 \n各バッファには、一つのタグテーブルが関連付けられ、そのタグテーブルのタグのみがそのバッファで使用出来る。 \nただし、タグテーブルは複数のバッファ間で共有出来る。\n\nタグには名前を付けてもよい。 \nこれは例えば、\"bold\" と名付けたタグでテキストを太字にする、などの利便性のため。 \n名前を付けない、匿名のタグもある。 \nこれは、その場(on-the-fly)でタグを作るのに便利。\n\n### 操作\n\nほとんどのテキスト操作は `GtkTextIter` で表現されるイテレータを使用して成される。 \nイテレータはテキストバッファ内の2文字間の位置を表現する。\n\n* * *\n\nその他、マークなどの説明が続きます。\n\n## 公式のリファレンス、デモ\n\nGtk3 のリファレンスは [developer.gnome.org\nにあります](https://developer.gnome.org/gtk3/stable/index.html)。 \nまた、`gtk3-demo` というデモアプリケーションがあり、 これは Ubuntu であれば、`gtk-3-examples`\nというパッケージに含まれていますが、以下のようにソースコードも閲覧出来るようになっています。\n\n![gtk3-demo screen shot](https://i.stack.imgur.com/u1pJ5.png)\n\n## 簡単な例\n\nPython ですが、一応タグを使う例です。\n\n```\n\n #!/usr/bin/python3\n import gi\n gi.require_version('GLib', '2.0')\n gi.require_version('Gtk', '3.0')\n from gi.repository import GLib\n from gi.repository import Gtk\n \n # イベントループ\n loop = GLib.MainLoop()\n \n # メインウィンドウ\n win = Gtk.Window.new(Gtk.WindowType.TOPLEVEL)\n win.set_title(\"TextView のテスト\")\n win.connect(\"delete-event\", lambda *x: loop.quit())\n \n # バッファ\n buf = Gtk.TextBuffer.new(None)\n buf.set_text(\"今日は、世界!\\n\")\n \n # 文字を大きくするタグ\n big_tag = buf.create_tag(\n \"big\",\n background=\"#fff\",\n foreground=\"#000\",\n family=\"Serif\",\n scale=2)\n \n # バッファの0~2文字目(オフセット)にタグを設定\n buf.apply_tag(big_tag, buf.get_iter_at_offset(0), buf.get_iter_at_offset(3))\n \n # バッファにテキストを追加\n buf.insert(buf.get_end_iter(), \"Hello, \")\n \n # バッファにテキストをタグを指定して追加\n buf.insert_with_tags(buf.get_end_iter(), \"world!\\n\", big_tag)\n \n # ビュー\n view = Gtk.TextView.new_with_buffer(buf)\n view.set_editable(False)\n view.set_cursor_visible(False)\n win.add(view)\n \n # スタート\n win.show_all()\n loop.run()\n \n```\n\n![例の実行結果](https://i.stack.imgur.com/2H2TW.png)", "comment_count": 2, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-13T15:30:38.243", "id": "33988", "last_activity_date": "2017-04-13T15:48:21.163", "last_edit_date": "2017-04-13T15:48:21.163", "last_editor_user_id": "3054", "owner_user_id": "3054", "parent_id": "33950", "post_type": "answer", "score": 1 } ]
33950
33988
33988
{ "accepted_answer_id": "34026", "answer_count": 1, "body": "rails初心者で、困り果てています\n\n検索機能をつけるため、ransackというgemを実装して、キーワード検索を自分のサイト内で行いたいと思っています。 \nしかし、なかなかrails5で実装を紹介しているサイトが見つからず、 \n古いバージョンのものでtryすると上手く動きません。\n\nもし、rails5での実装方法や使用方法が紹介されているサイトを知ってる方いたら助けてください。\n\nちなみに、サイト内検索をするフォームで、キーワードを打つと1文字や2文字くらい打つと \n予測を表示することはできるでしょうか??\n\n自分が使っているのは \nMac os 10.12.3 \nrails 5.0.2 \nです。", "comment_count": 1, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-12T10:44:09.807", "favorite_count": 0, "id": "33952", "last_activity_date": "2017-04-15T03:06:27.443", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "21416", "post_type": "question", "score": 0, "tags": [ "ruby-on-rails", "ruby" ], "title": "Rails5 で Ransackを実装する方法", "view_count": 1281 }
[ { "body": "> なかなかrails5で実装を紹介しているサイトが見つからず\n\nたしかに日本語のサイトは今のところないかもしれないですね。 \n英語のサイトですが、rails5でransackの実装を紹介しているサイトを見つけました。 \n(コードが多いので英語が苦手でも大丈夫そうです) \n<https://richonrails.com/articles/basic-search-using-ransack>\n\n一度これを参考に実装してみて、エラーなどで詰まったら再度質問してみるのはいかがでしょうか?", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-15T03:06:27.443", "id": "34026", "last_activity_date": "2017-04-15T03:06:27.443", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "22531", "parent_id": "33952", "post_type": "answer", "score": 1 } ]
33952
34026
34026
{ "accepted_answer_id": null, "answer_count": 1, "body": "ファイルサーバのようなものを作っています。 \nPDF ファイルのサムネイルを ImageMagick を使って生成しているのですが、ImageMagick でエラーが出る PDF ファイルがあります。 \nそのファイルの場合、単にサムネイルを使わないようにしたいのですが、try::tiny で囲んでも期待する結果になりません。\n\nコード\n\n```\n\n try{\n my $image = Image::Magick->new;\n $image->Read(\"${file}[0]\");\n $image->Transform(geometry => $imgsize);\n $image->Write($thumbnail);\n undef($image);\n $image = Image::Magick->new;\n $image->Read($thumbnail);\n $image->Resize($imgsize);\n $image->Write($thumbnail);\n undef($image);\n }\n catch{\n $ret = \"<div class = \\\"misc\\\">$ext</div>\";\n return $ret;\n }\n \n```\n\n出力 HTML ファイル\n\n```\n\n <div class = \"item\"><div class = \"misc\"><a href = \"_postcard.pdf\">.pdf</a></dError: /undefined in findresource\n Operand stack:\n --dict:5/14(L)-- F1 9.0 --dict:5/5(L)-- --dict:5/5(L)-- MSGothic-90msp-RKSJ-H --dict:10/12(ro)(G)-- --nostringval-- CIDFontObject --dict:6/6(L)-- --dict:6/6(L)-- Adobe-Japan1\n Execution stack:\n %interp_exit .runexec2 --nostringval-- --nostringval-- --nostringval-- 2 %stopped_push --nostringval-- --nostringval-- --nostringval-- false 1 %stopped_push 1862 1 3 %oparray_pop 1861 1 3 %oparray_pop 1845 1 3 %oparray_pop --nostringval-- --nostringval-- 2 1 1 --nostringval-- %for_pos_int_continue --nostringval-- --nostringval-- --nostringval-- --nostringval-- %array_continue --nostringval-- false 1 %stopped_push --nostringval-- %loop_continue --nostringval-- --nostringval-- --nostringval-- --nostringval-- --nostringval-- --nostringval-- %array_continue --nostringval-- --nostringval-- --nostringval-- --nostringval-- --nostringval-- %loop_continue\n Dictionary stack:\n --dict:1156/1684(ro)(G)-- --dict:1/20(G)-- --dict:75/200(L)-- --dict:75/200(L)-- --dict:106/127(ro)(G)-- --dict:286/300(ro)(G)-- --dict:22/25(L)-- --dict:4/6(L)-- --dict:25/40(L)--\n Current allocation mode is local\n Last OS error: 2\n Error: /undefined in findresource\n Operand stack:\n --dict:5/14(L)-- F1 9.0 --dict:5/5(L)-- --dict:5/5(L)-- MSGothic-90msp-RKSJ-H --dict:10/12(ro)(G)-- --nostringval-- CIDFontObject --dict:6/6(L)-- --dict:6/6(L)-- Adobe-Japan1\n Execution stack:\n %interp_exit .runexec2 --nostringval-- --nostringval-- --nostringval-- 2 %stopped_push --nostringval-- --nostringval-- --nostringval-- false 1 %stopped_push 1862 1 3 %oparray_pop 1861 1 3 %oparray_pop 1845 1 3 %oparray_pop --nostringval-- --nostringval-- 2 1 1 --nostringval-- %for_pos_int_continue --nostringval-- --nostringval-- --nostringval-- --nostringval-- %array_continue --nostringval-- false 1 %stopped_push --nostringval-- %loop_continue --nostringval-- --nostringval-- --nostringval-- --nostringval-- --nostringval-- --nostringval-- %array_continue --nostringval-- --nostringval-- --nostringval-- --nostringval-- --nostringval-- %loop_continue\n Dictionary stack:\n --dict:1156/1684(ro)(G)-- --dict:1/20(G)-- --dict:75/200(L)-- --dict:75/200(L)-- --dict:106/127(ro)(G)-- --dict:286/300(ro)(G)-- --dict:22/25(L)-- --dict:4/6(L)-- --dict:25/40(L)--\n Current allocation mode is local\n Last OS error: 2\n iv><input type = \"checkbox\" name = \"cb[]\" value = \"_postcard.pdf\" /><a href = \"_postcard.pdf\">_postcard.pdf</a></div>\n \n```\n\n単に、catch ブロックのみを返したいのですが・・・。\n\n## 追記\n\nernix さん、回答ありがとうございます。 \n以下のように書き換えました。\n\n```\n\n if(!(-f $thumbnail) or ((-M $thumbnail) > $elapsedtime)){\n $ret = eval{\n my $image = Image::Magick->new;\n $image->Read(\"${file}[0]\");\n $image->Transform(geometry => $imgsize);\n $image->Write($thumbnail);\n undef($image);\n $image = Image::Magick->new;\n $image->Read($thumbnail);\n $image->Resize($imgsize);\n #$image->Resize(\"120x\");\n $image->Write($thumbnail);\n undef($image);\n return \"<div class = \\\"img\\\"><a href = \\\"$file\\\"><img src = \\\"thumbnail\\\" class = \\\"img\\\" /></a></div>\";\n } || do {\"<div class = \\\"misc\\\">$ext</div>\";\n };\n return $ret;\n }\n if(-f $thumbnail){\n $ret = \"<div class = \\\"img\\\"><a href = \\\"$file\\\"><img src = \\\"$thumbnail\\\" class = \\\"img\\\" /></a></div>\";\n }\n else{\n $ret = \"<div class = \\\"misc\\\">$ext</div>\";\n }\n \n```\n\n同じエラーが出ます。 \n教えていただいた回答が私には難しすぎるようです…。", "comment_count": 1, "content_license": "CC BY-SA 4.0", "creation_date": "2017-04-12T11:16:30.797", "favorite_count": 0, "id": "33955", "last_activity_date": "2019-03-29T02:01:41.580", "last_edit_date": "2019-02-26T13:53:44.167", "last_editor_user_id": "19110", "owner_user_id": "9674", "post_type": "question", "score": 1, "tags": [ "perl", "imagemagick" ], "title": "Try::Tiny で ImageMagick の例外を処理するには", "view_count": 276 }
[ { "body": "```\n\n #!/usr/bin/perl\n use 5.022;\n use strict;\n use warnings;\n use Try::Tiny;\n \n sub wrong {\n try {\n die \"ERROR\";\n }\n catch {\n my $ret = \"CATCH\";\n return $ret;\n }; # 最後の\";\"を忘れずに\n \n return \"try/catch からの `return` はサブルーチンを抜けない。\";\n }\n \n sub right {\n return try { # ここにreturnが入るとサブルーチンから抜ける。\n die \"ERROR\";\n }\n catch {\n my $ret = \"CATCH\";\n return $ret;\n };\n \n return \"この行には到達しない。\";\n }\n \n sub using_eval {\n my $ret = eval {\n die \"ERROR\";\n \n #\n # 上のコードが死ななかった場合に、\n # `|| do`以下のブロックを評価しないよう1を返す。\n #\n # ブロック内でreturnを書くとサブルーチンのreturnと混同しやすいので、\n # returnは書かず単に最後に評価させるのが望ましい。\n #\n 1;\n } || do {\n \"ブロックでは、returnが無い場合最後に評価された値が返る。\";\n };\n \n return $ret;\n }\n \n say wrong();\n say right();\n say using_eval();\n \n 1;\n \n```", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-14T04:11:09.440", "id": "33998", "last_activity_date": "2017-04-14T04:11:09.440", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "62", "parent_id": "33955", "post_type": "answer", "score": -1 } ]
33955
null
33998
{ "accepted_answer_id": null, "answer_count": 1, "body": "vue.jsなどは主にSPAといった、データ志向な動的ページなど向いていると思うのですが、 \n一般的な静的サイトになんとかvue.js(vue-loader)の下記のメリットを持ち込めないか、 \nを考えています。\n\n* * *\n\n**単一コンポーネント** \n→CSS/HTML/JSを1つのファイルで管理 \n→scoped cssが扱える\n\n* * *\n\nやはり静的サイトとはいえど、ページ数が増え、コンテンツが拡張されていくと \nJSやCSSの管理が非常に大変になってくると思います。 \n(CSSでいえばclassのバッティングなど)\n\nこの単一コンポーネントを使えば\n\n・HTML/CSS/JSの距離が近くなり、見通しが良くなるのでは \n・scoped cssである程度cssが楽になるのでは\n\nと考えました。\n\n具体的に知りたいことは、\n\nこのような **同じ目的で静的サイトを構築したことがある** 方がいらっしゃったら、 \nその際のメリット(良かった点)・デメリットなどを教えてください。 \nもしくは、「そもそもこのためにvueを利用しない方がいい」という場合は、 \n他になにか同じようなことを実現できるものがあれば教えてください。", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-12T11:51:45.400", "favorite_count": 0, "id": "33957", "last_activity_date": "2017-09-15T04:11:26.597", "last_edit_date": "2017-04-17T04:06:46.457", "last_editor_user_id": "22525", "owner_user_id": "22525", "post_type": "question", "score": 6, "tags": [ "javascript", "html", "css", "vue.js" ], "title": "Vue.jsの静的サイトでの利用について", "view_count": 2562 }
[ { "body": "はじめまして。Vue.jsを静的サイトの構築において使用するのが適しているかいないのか、という件について意見を伺いたいということですが、個人的な観点から行くと、質問者さんのケースでは十分にVue.jsを使用するメリットがあると言ってもよろしいかと思います。\n\n一般に静的サイトで動きをもたせようと場合にはjQueryのなどのような単純なDOM操作のためのモジュールを使いがちですが、規模が大きくなってくると結局は操作が複雑になり、jQueryの限界を超えて頑張らざるをえないという苦難に立ち向かう羽目になります。今後、ご自身のサイトがどの程度スケールする可能性があるか(この場合ではサイトが持つページの数や、ひとつの画面の中でどの程度JavaScriptを使った操作を行う可能性があるのかという点)を考慮した上で、jQueryを使うという選択をするのであればよいのですが、先を見据えてVue.jsを使うという選択は多いにありです。どうしてもある操作のためにjQueryを使う必要がある、という場合にはVue.jsのコンポーネントの中でjQueryラップしてDOM操作を行うことをおすすめします。Vue.jsは自身のコンポーネント・ライフサイクルの中でDOM操作を受け付けるためのフック(イベント)をもっているため、jQueryとの統合が容易です。\n\nScoped\nCSSの観点に関しても概ね同意です。Vue.jsであればvueifyなどを用いることに寄って、単一ファイルコンポーネントとしてHTML/JS/CSSをまるごと隔離できるため、CSS命名規則などの制約を厳しく設けることなく構築できる可能性が広がります。とはいえ、コンポーネントの粒度によっては、コンポーネント内でのクラス命名に気をつける必要がありますが、それほどの規模のサイトではないと想定しております。\n\nデメリットに関してですが、どうしても開発当初の段階ではラーニング・カーブがペライチのHTML+jQueryと比較して少し大きくなってしまうというところかもしれません。開発が進むに連れて、必ず開発効率や保守性が上回りますが、最初はどうしてもオーバーキル気味に感じてしまうケースはあります。また、Vue.jsは比較的ブラウザサポートが厳しいという特性があり、もしもバージョンの古いブラウザやIEなどへの対応が必要になる場合には、polyfillを試したり、その他後方互換性のあるフレームワークを検討する必要がでてくるかもしれません。このようなケースではVue.jsを使うべきではないと思います。\n\n長くなりましたが、静的サイトにおいてVue.jsを使用するという事自体について、さほど躊躇するデメリットはないと思われます。長文失礼しました。", "comment_count": 1, "content_license": "CC BY-SA 3.0", "creation_date": "2017-09-15T04:11:26.597", "id": "37958", "last_activity_date": "2017-09-15T04:11:26.597", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "13444", "parent_id": "33957", "post_type": "answer", "score": 3 } ]
33957
null
37958
{ "accepted_answer_id": null, "answer_count": 1, "body": "[WordPress を専用ディレクトリに配置する - WordPress Codex\n日本語版](https://wpdocs.osdn.jp/WordPress_%E3%82%92%E5%B0%82%E7%94%A8%E3%83%87%E3%82%A3%E3%83%AC%E3%82%AF%E3%83%88%E3%83%AA%E3%81%AB%E9%85%8D%E7%BD%AE%E3%81%99%E3%82%8B)\n\n上記ページを参考に`wp`ディレクトリにwordpressを置きました。(本当は別名ですが説明上参考資料と合わせて`wp`とします。下記`example.com`も参考資料に合わせた仮の値です)\n\nそして下記の通り行いました。\n\n### サイトアドレス変更\n\n`サイトアドレス (URL) > http://example.com`\n\n### index.phpと.htaccessをコピー\n\n`WordPress ディレクトリにある index.php と .htaccess ファイルを、サイトのルートディレクトリへコピー`\n\n### index.php編集\n\n`ルートディレクトリの index.php ファイルを編集する`\n\nさて、こうすると目的通り\n\n`http://example.com` の形式でアクセスすることができましたが、`http://example.com/wp`\n形式のほうもアクセス可能です。\n\n`http://example.com/wp`の方は不要なので404を返すのがよいと思っているのですが、どのようにすればよいでしょうか?\nそれともwordpressの作法的に`http://example.com/wp`形式もアクセス可能でよいものなのでしょうか?", "comment_count": 0, "content_license": "CC BY-SA 4.0", "creation_date": "2017-04-12T23:46:21.910", "favorite_count": 0, "id": "33966", "last_activity_date": "2021-12-27T18:04:50.417", "last_edit_date": "2020-03-13T04:06:29.800", "last_editor_user_id": "3060", "owner_user_id": "9008", "post_type": "question", "score": 1, "tags": [ "wordpress" ], "title": "サブディレクトリにもhttpアクセスできてしまう", "view_count": 717 }
[ { "body": ".htaccessということはapacheですね。\n\nwpのディレクトリへのアクセスを拒否したいのであれば、以下のURLを参考にwpのディレクトリに対して、Allowを書かずに設定してあげればいいと思います。 \n<http://blog.shinkaku.co.jp/archives/45972397.html>\n\nwordpressの作法はわかりませんが、不要なものは公開すべきではないと思いますので、アクセスできないようにしておいた方がよいでしょう。", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-13T07:46:58.337", "id": "33980", "last_activity_date": "2017-04-13T07:46:58.337", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "17014", "parent_id": "33966", "post_type": "answer", "score": 1 } ]
33966
null
33980
{ "accepted_answer_id": null, "answer_count": 1, "body": "初めての投稿になります。よろしくお願いします。 \nPHPのプログラミングで良く \n「eval関数はセキュリティ上問題があるので、使用不可」 \nといったようなコメントを見かけるのですが、eval関数と同様の事は例えば下記のような事を行えば出来てしまいます。 \n「ソースコードを一時テキストファイルに保存してincludeする」\n\neval関数は推奨されないけれども、上記のような処理は問題無いのでしょうか?それともそもそもコードテキスト等をPHPコードとして読み込むこと自身がいけない事なのでしょうか?\n\n使い方を誤った時のセキュリティの課題はもちろんあると思いますが、結局はどれだけシステム全体がセキュリティを考慮した作りになっているかでは無いかと思っております。\n\nテンプレートHTML等の関係からシステム内で生成したコードの読み込みの必要があり、一番良い解決方法を模索しています。ご意見をお持ちの方がおられましたらお願いいたします。", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-13T02:16:16.987", "favorite_count": 0, "id": "33968", "last_activity_date": "2017-04-13T05:46:34.630", "last_edit_date": "2017-04-13T05:46:34.630", "last_editor_user_id": "19110", "owner_user_id": "22529", "post_type": "question", "score": 0, "tags": [ "php" ], "title": "eval関数やその他類似処理の使用について", "view_count": 315 }
[ { "body": "「evalは何が何でも危険」なのではなく「evalはコードインジェクション等の危険性がある為危険」であると私は理解しています。 \n例えばevalの引数に変数を含まず固定値ならば(指定するPHPコードにもよりますが)基本的に安全であると考えています。\n\n同様にincludeはディレクトリトラバーサルや同じようにコードインジェクションの危険性があります。 \nこちらも動的な値が使われていない場合は危険性はない認識です。 \n(相対パスで指定する場合は、includeパスに余計なファイルが置き得ないか注意する必要がありますが。)\n\n動的な値を指定する場合もサニタイズ(特殊文字の無効化)を行えば問題ありませんが。 \nその際の処理漏れを懸念して、初心者の方向けに「とりあえずevalは危険」と言っているサイトさんが多いのだと思います。\n\n> システム内で生成したコードの読み込み\n\nこちらの処理ですが \n「htmlコードを生成し文字列変数で渡すようなモジュールをinclude」 \nであれば問題ありませんが \n「モジュールがhtmlコードを生成しファイル化、そのファイルをinclude」であれば \nincludeに変数を使う必要が出てくると思いますのでサニタイズ処理等の考慮が必要になって来るかと思います。", "comment_count": 3, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-13T04:49:44.413", "id": "33974", "last_activity_date": "2017-04-13T05:05:31.910", "last_edit_date": "2017-04-13T05:05:31.910", "last_editor_user_id": "19716", "owner_user_id": "19716", "parent_id": "33968", "post_type": "answer", "score": 2 } ]
33968
null
33974
{ "accepted_answer_id": "33977", "answer_count": 1, "body": "[DjangoGirlsTutorial](https://djangogirlsjapan.gitbooks.io/workshop_tutorialjp/content/)を進めていたのですが、データベースのあたりでエラーが出てしまいます。 \n具体的には、[クエリセット1のページ](https://djangogirlsjapan.gitbooks.io/workshop_tutorialjp/content/django_orm/)でコンソール画面を開いてデータベースのデータを表示させようとした時に以下のエラーが出ました。\n\n```\n\n $ python manage.py shell\n /Users/you_mac/.pyenv/versions/3.5.2/lib/python3.5/site-\n packages/IPython/core/interactiveshell.py:724: UserWarning: Attempting \n to work in a virtualenv. If you encounter problems, please install \n IPython inside the virtualenv.\n warn(\"Attempting to work in a virtualenv. If you encounter problems, \n please \"\n Python 3.5.2 (default, Nov 1 2016, 17:50:43)\n Type \"copyright\", \"credits\" or \"license\" for more information.\n \n IPython 5.2.0 -- An enhanced Interactive Python.\n ? -> Introduction and overview of IPython's features.\n %quickref -> Quick reference.\n help -> Python's own help system.\n object? -> Details about 'object', use 'object??' for extra details.\n \n In [1]: from blog.models import Post\n In [2]: Post.objects.all()\n \n Out[2]: ---------------------------------------------------------------\n ImproperlyConfigured Traceback (most recent call last)\n \n …\n \n /Users/you_mac/.pyenv/versions/3.5.2/lib/python3.5/site-\n packages/django/db/backends/dummy/base.py in complain(*args, **kwargs)\n 19\n 20 def complain(*args, **kwargs):\n ---> 21 raise ImproperlyConfigured(\"settings.DATABASES is \n improperly configured. \"\n 22 \"Please supply the ENGINE value. Check \"\n 23 \"settings documentation for more details.\")\n \n ImproperlyConfigured: settings.DATABASES is improperly configured. \n Please supply the ENGINE value. Check settings documentation for more \n details.\n \n```\n\nmysite/setting.pyのデータベース設定はチュートリアルと同じく以下のようにしています。\n\n```\n\n DATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),\n }\n }\n \n```\n\nエラーを見る限り、sqlite3を正しく起動できていないように思います。どのようにすればデータベースを読み込むようにできますでしょうか。 \n解決方法がありましたら、ご教授ください。", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-13T03:34:06.443", "favorite_count": 0, "id": "33970", "last_activity_date": "2017-04-13T06:50:20.757", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "22480", "post_type": "question", "score": 0, "tags": [ "python", "django", "database", "sqlite" ], "title": "Djangoのデータベース設定について", "view_count": 3512 }
[ { "body": "> mysite/setting.pyのデータベース設定はチュートリアルと同じく以下のようにしています。\n\n正しくは `mysite/settings.py` ではないでしょうか?(末尾のsが抜けている) \nもし、質問上の記載間違いで、settings.pyに正しく設定できている場合、以下の内容を確認してみてください。\n\n```\n\n from django.conf import settings\n print(settings.DATABASES)\n \n```\n\nこれで、Djangoがどのsettingsファイルをどのように読み込んでいるのかが分かります。 \nこの実行結果が、設定した値と異なっている場合、ファイルを間違えているか、settings.pyに複数設定があって後勝ちになっているか、何らかの問題があるのだと思います。", "comment_count": 5, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-13T06:50:20.757", "id": "33977", "last_activity_date": "2017-04-13T06:50:20.757", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "806", "parent_id": "33970", "post_type": "answer", "score": 1 } ]
33970
33977
33977
{ "accepted_answer_id": "33973", "answer_count": 1, "body": "ES6でclassにチャレンジしてみたい。\n\nclassもプロトタイプもほとんど同じと聞いたので \nせっかくこれからやるのでES6でclassにチャレンジしてみたいと思いますが、初心者用の情報が見つかりません。\n\nここ以上の情報がないです。 \n<http://js-next.hatenablog.com/entry/2014/11/01/034607>\n\nこれを使うとスコープ内の変数も使えるようになるようですね。 \nいつも関数内の変数を使えずに困っているのでこれで解決したいです。\n\nクラスは設計図、インスタンスは具現化した物のようですが、 \nコンストラクターはクラスどう違うのでしょうか?難しくてよくわかりませんね。\n\n・具体的な話 \n<http://js-next.hatenablog.com/entry/2014/11/01/034607> \nのたとえですと\n\n```\n\n class Cat {\n \n constructor(name) {\n this.name = name\n }\n \n meow() {\n alert( this.name + 'はミャオと鳴きました' )\n }\n \n }\n \n```\n\nの\n\n```\n\n constructor(name) {\n this.name = name\n }\n \n```\n\nがコンストラクターで関数とそっくりなのですが、 \nコンストラクターとはクラス内に作れる関数の事なんですか? \nでもそれだと下記のメソッドとかぶりますよね?\n\n```\n\n meow() {\n alert( this.name + 'はミャオと鳴きました' )\n }\n \n```\n\nがおそらくメソッドなのでしょうが、メソッドはオブジェクト内の関数のことですよね? \nクラス内の関数もメソッドという事ことでしょうか? \nもしそうなら文法や使い方も全く変わらないのですね。\n\n結局クラスとは設計図という抽象的な言葉ではよくわからないので、 \nメソッドやコンストラクターを入れられるオブジェクトのようなものなのでしょうか?", "comment_count": 4, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-13T03:48:53.007", "favorite_count": 0, "id": "33972", "last_activity_date": "2017-04-21T03:14:57.157", "last_edit_date": "2017-04-21T03:14:57.157", "last_editor_user_id": "20834", "owner_user_id": "20834", "post_type": "question", "score": -7, "tags": [ "javascript" ], "title": "ES6でclassとは?", "view_count": 907 }
[ { "body": "コンストラクタとはクラスをnewする際に呼ばれるクラス用の初期化関数のことです。 \n例題で言うと実際の使用は下記のような感じでしょうか。 \nクラス内のオブジェクトを初期化したいなどですかね。\n\n```\n\n var clsObj = null;\r\n \r\n class Cat {\r\n \r\n constructor(name) {\r\n this.name = name\r\n }\r\n \r\n meow() {\r\n alert( this.name + 'はミャオと鳴きました' )\r\n }\r\n \r\n }\r\n \r\n function bootClass(){\r\n //クラス初期化、初期化時にコンストラクタが呼ばれ初期化される\r\n clsObj = new Cat(\"my cat\");\r\n clsObj.meow();\r\n }\r\n \r\n function bootClass2(){\r\n //クラス初期化はオブジェクト単位で出来る\r\n var work = new Cat(\"2nd cat\");\r\n work.meow();\r\n //勿論前のオブジェクトが残っていれば前のも呼び出せる\r\n clsObj.meow();\r\n }\n```\n\n```\n\n <button onclick=\"bootClass()\">クラスの初期化</button>\r\n \r\n <button onclick=\"bootClass2()\">クラスの初期化2</button>\n```\n\n* * *\n\n> javaの情報はありました。JSと変わらないのでこちらを理解すればよいでしょうか?\n\nクラスの考え方や構造としてであれば参考になるかと思いますのでそちらを読み進めても問題は無いかと思います。 \nただ、言語毎に記述方法が違うのもあり、例えば、 \nデストラクタ(ファイナライザとも呼ぶ、Classを破棄する際に実行される関数)がES6には無かったはずなので、 \nそういったところで微妙に差異はあるかと思います。 \n※蛇足ですが、構造の考え方の1つとして\"カプセル化\"で調べると幸せになれるかもしれません。\n\n> つまりクラスという設計図を具現化したインスタンスにする際に、newを使うのですね。\n\nはい概ねその考え方でいいかと思います。\n\n> varとおなじ宣言のクラス番という事ですね。\n\n\"new\"に限って言えばそうです。\n\n> クラスをインスタンス化する際に、使われるクラスでしか使わないクラス専用の関数のことをコンストラクタというのですね?\n\n上手く読み砕けませんが、違う認識かと思います。 \n1.\"new\"でクラスオブジェクト(インスタンス)を作成する \n2.インスタンス作成時にコンストラクタの関数が呼び出される \n(インスタンス作成時に呼び出されない関数についてはコンストラクタとは呼ばない) \n3.インスタンスを使用してクラス内の関数を呼び出したり、値を参照したり色々処理する。\n\n> ただ初期化とはどういう事でしょうか?\n\nそもそもクラスとは…の話になるのですが、 \nクラスは関数と変数をラッピングした雛形のようなものになるでしょうか\n\n例えばサンプルだと\"meow()\"という関数を処理するためには名前が必要です。 \nクラス内の関数で処理をする準備として名前を初期化する必要があります。 \n雛形からインスタンスを作成した場合にそのままmeowを実行したいけど名前をつけてから処理したい。\n\nそういった処理をする前準備のための関数ですね。 \n大体がクラスの中で処理をする前準備をするので初期化といいました。\n\n> 良くvar i = 0;という初期化を行いますが、どう違うのでしょうか?\n\nクラスと変数は別物なのでそもそも比較できるものではないですが、 \nクラスのインスタンス作成の処理にたとえて言うとこうでしょうか? \n1.変数\"i\"を宣言する \n2.変数\"i\"に初期値0を代入する \n3.変数を使用する\n\n> {}で作る一般的なオブジェクトと同じものがクラス内にある場合があり、 \n> それを初期化?するときに使う関数をコンストラクタというのですね。\n\nコンストラクタの発動タイミングはクラスのインスタンスを作成する時の一回だけです。 \nそれ以降で別の初期化関数を作って実行しても、それはコンストラクタとは呼びません。\n\n> functionかわりにconstructorと記載する関数という事ですね。\n\nはい、それをコンストラクタと呼びます。\n\n> thisはclass名catの事でしょうか?\n\nはい、内包しているオブジェクトの事を指しますので\"Cat\"を指します。\n\n> nameが初期の値なのでnameをcatの中に代入して初期化しているのでしょうか?\n\nCatのプロパティ名nameに代入して初期化を行っています。\n\n* * *\n\n> JSにはないようですが、つまり使えないようにdelするという事ですかね。\n\n実際蛇足気味なのでアレですが、インスタンスは雛形からの複製のような感じに当たりますので破棄する状況も出てきます。 \nデータ1の処理を行ったインスタンスを破棄してデータ2の処理をする。などの際に \nデータ1を参照しないように削除しておいたり…インスタンス展開しすぎてメモリ圧迫するから解放しとこうとか…。\n\n> 同じ関数でも利用のされ方の違いを認識できるのでわざわざ別名を用意したという事ですね。\n\n後述のメソッドもそうですが、そういうことですね。\n\n> 気になるのは、メソッドという関数がクラスにありますが、これはオブジェクト内だけと聞いていましたが、 \n> 厳密にはオブジェクト内とクラス内の関数のことをそれ以外の関数と区別するためにつけた別名という事でしょうか?\n\n前述のカプセル化をご存知でしたら話は早いかと思いますが、 \n外から関数を直接参照されないように別の関数からのアクセスさせないように関数の区別があります。 \nメソッドの種類はconstructorメソッド、staticメソッド、prototypeメソッドの3つあります。\n\n・constructorメソッド:\"new\"時に実行される関数 \n・staticメソッド:インスタンスを作成せず呼び出せる関数 \n・prototypeメソッド:インスタンスから呼び出すことが出来る関数\n\nそれぞれの使い方は下記になります。\n\n```\n\n class Cat {\n constructor(name) { this.name = name }\n \n meow() { alert( this.name + 'はミャオと鳴きました' ) }\n \n static growl() { alert( 'フシャー!' ) }\n }\n \n Cat.growl();//static実行\n var clsObj = new Cat(\"my cat\");//constructor実行\n clsObj.meow();//prototype実行\n \n```\n\n> 関数と変数をなかに入れるオブジェクトのようなもので、 \n> オブジェクトとの違いはひな形の役割もあるという事でしょうか?\n\nstaticメソッドのようなものもあるので一概には言えませんが、概ねそうです。\n\n> meowが関数名かと思ったのですが、また、なぜfunctionが省略されているのでしょうか?\n\nprototypeメソッドの宣言方法だからです。扱いはほぼ関数と変わりませんが上記を参照してください。\n\n> `内包しているオブジェクトの事を指しますので\"Cat\"を指します。` \n> class.catとなるのでしょうか?\n\nこちら失礼しました。`Cat`と記載したのですが、 \n`Cat`ではなくインスタンスの下で実行されているので、 \n`this`が指すのは実際にはインスタンスを指します。\n\n下記のスニペットを見ていただければ分かるかと思います。\n\n```\n\n class Cat {\r\n constructor(name) {this.name = name}\r\n meow() {alert( this.name + 'はミャオと鳴きました' )}\r\n }\r\n \r\n //インスタンス作成\r\n var clsObj = new Cat(\"my cat\");\r\n //インスタンス(オブジェクト)の中身を出力\r\n console.log(clsObj);\n```", "comment_count": 7, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-13T04:01:33.677", "id": "33973", "last_activity_date": "2017-04-14T09:56:50.917", "last_edit_date": "2017-04-14T09:56:50.917", "last_editor_user_id": null, "owner_user_id": null, "parent_id": "33972", "post_type": "answer", "score": 1 } ]
33972
33973
33973
{ "accepted_answer_id": "33982", "answer_count": 1, "body": "お世話になります。\n\n今回、初めてGIFファイルの勉強をしようと、lzwの圧縮、解凍をC#で組んでみたのですが、 \nどうもうまくいきません。\n\n圧縮まではうまくいっているようなのですが、解凍しようとすると、余計なところに『0』が \n入ってしまい、正しく解凍されません。\n\nほかサイト様など、さまざまなところを拝見させていただいているのですが、どうも \n原因がわかりません。\n\n原因と対策をお教えいただけますでしょうか。\n\n尚、まだ勉強中のため、バイト単位でなく、0から255までのテキストデータの \nパターンで練習していますのでご了承ください。\n\n下記にソースコードを記述します。\n\n```\n\n private Dictionary<string, int> hsDic = new Dictionary<string, int>();\n private Dictionary<string,string > hsDec = new Dictionary< string,string>();\n private List<int> arch = new List<int>();\n \n private string[] stBuff = null;\n \n // 圧縮\n public int[] enc(string[] values)\n {\n for (int d0 = 0; d0 < 8; d0++)\n {\n this.hsDic.Add(\"\" + d0, d0);\n this.hsDec.Add(\"\" + d0,\"\" + d0);\n }\n bool eof = false;\n \n this.stBuff = values;\n \n string w = \"\";\n string k = \"\";\n \n int skip = 0;\n \n int idx = 0;\n \n while (true)\n {\n // idxで指定した文字を取得\n w = stBuff[idx];\n \n // skipはidxの一文字後から開始\n skip = 0;\n if (this.hsDic.Count == 20)\n {\n int a = 0;\n }\n \n while (true)\n {\n skip++;\n \n if(idx + skip >= stBuff.Length)\n {\n eof = true;\n break;\n }\n k = stBuff[idx + skip];\n if (this.hsDic.ContainsKey(w + \",\" + k))\n {\n w = w + \",\" + k;\n }\n else\n {\n break;\n }\n }\n \n if(eof)\n {\n break;\n }\n this.hsDic.Add(w + \",\" + k, this.hsDic.Count);\n this.arch.Add(this.hsDic[w]);\n idx += skip;\n }\n // 最後の一文字\n \n this.arch.Add(this.hsDic[w]);\n return this.arch.ToArray();\n }\n \n // 解凍\n public string[] dec2(int[] pattern)\n {\n for (int d0 = 0; d0 < 8; d0++)\n {\n this.hsDic.Add(\"\" + d0, d0);\n this.hsDec.Add(\"\" + d0,\"\" + d0);\n }\n \n bool eof = false;\n \n int w = -1;\n int k = -1;\n \n string ww = \"\";\n string kk = \"\";\n int skip = 0;\n \n int idx = 0;\n \n List<string> lst = new List<string>();\n \n while (true)\n {\n // idxで指定した文字を取得\n w = pattern[idx];\n ww = this.hsDec[\"\" + w];\n // skipはidxの一文字後から開始\n skip = 1;\n \n if (this.hsDec.Count == 20)\n {\n int a = 0;\n }\n \n if (idx + skip >= pattern.Length)\n {\n eof = true;\n break;\n }\n \n k = pattern[idx + skip];\n kk = this.hsDec[\"\" + k];\n \n this.hsDec.Add(\"\" + this.hsDec.Count, ww + \",\" + kk);\n lst.Add(this.hsDec[\"\" + w]);\n idx += skip;\n }\n //// 最後の一文字\n \n lst.Add(ww);\n return lst.ToArray();\n }\n \n```\n\nテストパターン\n\n```\n\n 7,6,3,5,2,3,0,2,0,0,3,6,5,4,0,7,2,1,4,4,1,1,2,4,0,6,3,6,1,4,7,3,5,2,3,5,7,7,5,3,3,4,3,3,2,4,5,0,1,0,0,7,7,2,2,6,4,2,0,3,4,7,2,0,5,5,4,4,0,0,3,1,2,2,1,1,7,0,0,6,5,1,0,7,6,\n \n```\n\n上記のパターンを使用しています。\n\nここまでですらうまくいっていないため、解凍時に辞書に登録されていないものは、 \nwとwの最初の一文字を足したものを辞書に追加する…などといったこともまだ行っていません。\n\nまだテスト中のため、コードも汚くて申し訳ありませんが、ぜひご教授いただけますよう、 \nお願いいたします。", "comment_count": 3, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-13T07:09:19.333", "favorite_count": 0, "id": "33978", "last_activity_date": "2017-04-13T08:47:52.257", "last_edit_date": "2017-04-13T08:38:28.207", "last_editor_user_id": "19110", "owner_user_id": "9374", "post_type": "question", "score": 0, "tags": [ "c#", "アルゴリズム" ], "title": "lzwの圧縮、解凍について", "view_count": 642 }
[ { "body": "主要な原因として`dec2`の下記の個所に2点誤りがあります。\n\n>\n```\n\n> k = pattern[idx + skip];\n> kk = this.hsDec[\"\" + k];\n> this.hsDec.Add(\"\" + this.hsDec.Count, ww + \",\" + kk);\n> \n```\n\nまず3行目で登録している値ですが、`kk`は先頭の文字のみを使用しなくてはなりません。ですので`kk[0]`のようにしてください。\n\n次に2行目ですが、ここでキー`k`が登録されているとは限りません。\n\nたとえば`0,0,0`というデータを圧縮すると、まずコード`8`に`0,0`が登録されて`0,8`が出力されます。これを復号しようとした場合、`0`の次のコード`8`が登録される前に`8`を参照しようとして例外が発生します。\n\nこのためディクショナリに後続のコードが登録されていない場合の処理を行わなくてはなりませんが、圧縮時に直前に追加したコードが使用されているため両コードは平文の先頭が一致していると判断できます。ですのでキーがない場合は`kk`として`ww`を使用します。\n\nあともう一点あげると`ww`はカンマ区切りなので`lst.Add(ww)`\n(二か所)は`lst.AddRange(ww.Split(','))`が正しいです。ここを直せば少なくとも質問のデータについてはラウンドトリップします。", "comment_count": 1, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-13T08:39:20.683", "id": "33982", "last_activity_date": "2017-04-13T08:47:52.257", "last_edit_date": "2017-04-13T08:47:52.257", "last_editor_user_id": "5750", "owner_user_id": "5750", "parent_id": "33978", "post_type": "answer", "score": 2 } ]
33978
33982
33982
{ "accepted_answer_id": null, "answer_count": 0, "body": "Shift-JISのページをIMPORTXML関数で情報取得しようとすると \n日本語は文字化けしてしまいます。 \nSpreadsheetがUTF-8正直使えない関数だなと思いました。\n\n何かしらの回避方法は無いのでしょうか? \nShitJis→UTF-8に変換するような方法とか \n(apps scriptは多少使えるのでそれで出来ないかと)", "comment_count": 2, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-13T07:18:36.837", "favorite_count": 0, "id": "33979", "last_activity_date": "2017-04-25T05:48:58.030", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "21256", "post_type": "question", "score": 0, "tags": [ "google-apps-script", "google-chrome", "google-spreadsheet" ], "title": "google SpreadsheetのIMPORTXML関数の文字化け", "view_count": 1726 }
[]
33979
null
null
{ "accepted_answer_id": null, "answer_count": 0, "body": "CentOS7を使っています。\n\nホストサーバから\n\n> /mnt/test1 -> 192.168.1.101:/hdd01 \n> /mnt/test2 -> 192.168.1.102:/hdd01 \n> /mnt/test3 -> 192.168.1.103:/hdd01\n\nでNFSマウントをしています。\n\nホスト側で\n\n```\n\n $ more /etc/auto.master\n /mnt /etc/auto.var bg,intr --timeout=120 --ghost\n $ more /etc/auto.var_dtv\n test1 -rw 192.168.1.101:/hdd01\n test2 -rw 192.168.1.102:/hdd01\n test3 -rw 192.168.1.103:/hdd01\n \n```\n\nというautofsの設定を行なっていてマウントはもちろんのことアクセスができるようになっています。\n\n以下のようなdockerを作成しました。\n\n```\n\n sudo docker run -d --restart=always --privileged --name test -h test -v /mnt/:/mnt/ docker.io/centos /sbin/init\n sudo docker exec -it test bash\n \n```\n\nでコンテナの中に入り\n\n```\n\n $ cd /mnt\n $ ls\n test1 test2 test3\n \n```\n\nという状況ですが、\n\n```\n\n $ cd test1\n bash: cd: test1: Too many levels of symbolic links\n \n```\n\nというエラーが発生します。\n\nマウント先の192.168.1.101:/hdd01配下にはそれぞれcontentsというディレクトリがあります。\n\n```\n\n sudo docker run -d --restart=always --privileged --name test -h test -v /mnt/test1/contents/:/mnt/test1/contents/ -v /mnt/test2/contents/:/mnt/test2/contents/ -v /mnt/test3/contents/:/mnt/test3/contents/ docker.io/centos /sbin/init\n \n```\n\nとすればコンテナーの中に入って\n\n```\n\n $ ls /mnt/test1\n \n```\n\nで中身を見ることができます。\n\nしかし、今後マウント先が増えることを考えるとその都度dockerを再構成する必要があり、それは避けたいと思っています。 \nホスト側でautofsを使ったものが再起動しなくてもコンテナー内で使用(マウント)できるようにするにはどうしたらいいのでしょうか?\n\nご存知の方、ご教示お願いします。", "comment_count": 5, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-13T09:09:40.990", "favorite_count": 0, "id": "33983", "last_activity_date": "2017-04-13T09:09:40.990", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "8593", "post_type": "question", "score": 0, "tags": [ "docker" ], "title": "dockerコンテナからホストのautofsでマウント場所にアクセスできない", "view_count": 695 }
[]
33983
null
null
{ "accepted_answer_id": "34001", "answer_count": 1, "body": "sequelize初心者です。 \nTwitterやFacebookのoAuth認証をして、ユーザー情報をデータベースに保存したいと思っています.しかし、oAuth認証を複数サイトで行うとデータベースに登録したuseridなど情報が他サイトと重複してしまう問題があります。 \nそれを回避するために、指定したuseridが既にデータベースに存在しない時のみ、データベースを更新するような処理を行いたいと思っています。 \nそのような処理を行うためにはsequelizeのfindOrCreateを使えばいいということは分かったのですが、findOrCreateの使い方がよく分かりません。 \nupsertの使い方は分かっていて、下のupsertの記述のようにfindOrCreateを行いたいと思っています。ただ、if(userid!=\"○○○\"\n&& username!=\"○○○\")というような条件分岐を行いたいです。\n\n```\n\n User.upsert\n ({\n userid: profile.id,\n username: profile.username,\n accountid: c+1\n }).then\n (() => {\n done(null, profile);\n });\n \n```\n\nどのようにしたら良いでしょうか。", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-13T13:09:29.680", "favorite_count": 0, "id": "33984", "last_activity_date": "2017-04-14T05:39:43.640", "last_edit_date": "2017-04-14T01:47:14.207", "last_editor_user_id": "5793", "owner_user_id": "22541", "post_type": "question", "score": -1, "tags": [ "database" ], "title": "sequelizeのfindOrCreateの使い方について", "view_count": 1232 }
[ { "body": "実際に試してはいませんが、[ドキュメント](http://docs.sequelizejs.com/en/latest/docs/models-\nusage/#findorcreate-search-for-a-specific-element-or-create-it-if-not-\navailable)には次のようなコードが例示されているので、\n\n```\n\n User\n .findOrCreate({where: {username: 'sdepold'}, defaults: {job: 'Technical Lead JavaScript'}})\n .spread(function(user, created) {\n console.log(user.get({\n plain: true\n }))\n console.log(created)\n })\n \n```\n\nこういう感じになるのではないでしょうか。\n\n```\n\n User.findOrCreate({\n where: { userid: profile.id, username: profile.username },\n defaults: { accountid: c + 1 }\n }).spread((user, created) => {\n done(null, profile);\n });\n \n```\n\naccountid をどのように生成しているのかわかりませんが、cがカウンタ的なものなら、`created === true`\nの場合のみインクリメントする等した方がいいかもしれません。", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-14T05:39:43.640", "id": "34001", "last_activity_date": "2017-04-14T05:39:43.640", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "8000", "parent_id": "33984", "post_type": "answer", "score": 1 } ]
33984
34001
34001
{ "accepted_answer_id": "33986", "answer_count": 2, "body": "jsfiddle で公開されているサンプルソースがあるのですが、 \nライブラリのinclude方法や、onloadでの呼び出しなど、詳細まで \n理解しておきたいので、 \nHTML全文をみたいのですが、どのようにすれば、そのような内容を見ることができるでしょうか?\n\njsfiddle には、まだアカウント登録していませんが、 \nアカウント登録すれば可能でしょうか?\n\nよろしくおねがいします。", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-13T14:00:31.037", "favorite_count": 0, "id": "33985", "last_activity_date": "2017-04-14T09:18:16.683", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "21047", "post_type": "question", "score": 0, "tags": [ "javascript" ], "title": "jsfiddle で、HTML などの全文が欲しいのですが、どのようにすればよいでしょうか", "view_count": 575 }
[ { "body": "JSFiddle自体にそのような機能は用意されていませんが、実行結果を表示している部分はインラインフレームなので、例えばChromeだと\n\n * 結果が表示されている部分を右クリックして「フレームのソースを表示」\n * 結果が表示されている部分を右クリック→検証などとして開発者ツールを開き、iframeタグまでさかのぼり、その直下にあるhtmlタグを右クリック→Copy→Copy outerHTML\n\n[![画像の説明をここに入力](https://i.stack.imgur.com/ftM0f.png)](https://i.stack.imgur.com/ftM0f.png)\n\nなどの方法でHTMLを取得することができます。JSFiddle用に若干CSSやスクリプトが追加されているようですが、まあ見ればわかると思います。\n\n一応スクリプトの読み込むタイミングなども指定はできますが、動けばいいというぐらいで書かれている可能性もあります。JSFiddleのサンプルの本命はHTML/JS/CSSのコード本体と考え、それ以外の部分はライブラリのドキュメントや、HTML形式で公開されているサンプルがないか確認してみるといいかもしれません。何もなければ、自由に読み込めばよいのでしょうし。\n\n* * *\n\nおまけ。URLのドメインを `jsfiddle.net` から `fiddle.jshell.net`\nに変更して、以下のコードを開発者ツールのコンソールで実行すると、HTMLをコピーできます。やってることは上で説明したのと同じです。やっつけなのでいつまで動くかわかりませんが。\n\n```\n\n copy(document.querySelector('iframe').contentDocument.documentElement.innerHTML)\n \n```", "comment_count": 4, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-13T14:19:23.280", "id": "33986", "last_activity_date": "2017-04-13T14:30:01.627", "last_edit_date": "2017-04-13T14:30:01.627", "last_editor_user_id": "8000", "owner_user_id": "8000", "parent_id": "33985", "post_type": "answer", "score": 1 }, { "body": "* jsfiddleにログイン\n * fiddleを閲覧\n * Run\n * <https://jsfiddle.net/draft/> にアクセス\n\nとすると、RESULT のみが表示されます", "comment_count": 2, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-14T07:19:09.683", "id": "34006", "last_activity_date": "2017-04-14T09:18:16.683", "last_edit_date": "2017-04-14T09:18:16.683", "last_editor_user_id": "9796", "owner_user_id": "9796", "parent_id": "33985", "post_type": "answer", "score": 1 } ]
33985
33986
33986
{ "accepted_answer_id": "35112", "answer_count": 1, "body": "4.62365962451697,78.0246928153624,0 \n↑のような形式で99行あるex2data1.txtを読み込んで、このファイルに対してロジスティック回帰分析をpythonで行いたいのですが、学習率α等を変えても何故か図のような結果になってしまいます。間違っているところがありましたら指摘していただきたく存じます。\n\n```\n\n import numpy as np\n import matplotlib.pyplot as plt\n import pandas as pd\n \n def sigmoid(X):\n return 1/(1 + np.exp(-X))\n data = pd.read_csv(\"ex2data1.txt\", header=None)\n X = np.array([data[0],data[1]]).T\n y = np.array(data[2])\n \n O = np.ones(len(y))\n m = float(len(y))\n Xm = X/m\n X1 = np.c_[O,Xm]\n \n pos = (y==1)\n neg = (y==0)\n plt.scatter(X[pos,0], X[pos,1], marker='+', c='b')\n plt.scatter(X[neg,0], X[neg,1], marker='o', c='y')\n plt.legend(['Admitted', 'Not admitted'], scatterpoints=1)\n plt.xlabel(\"Exam 1 Score\")\n plt.ylabel(\"Exam 2 Score\")\n \n alpha = 0.5\n theta = np.array([1,1,1])\n \n for i in range(1000): #gradient\n h = sigmoid(np.inner(theta, X1))\n theta1_tmp = 1/m * np.sum((h-y)*X1[:, 0])\n theta2_tmp = 1/m * np.sum((h-y)*X1[:, 1])\n theta3_tmp = 1/m * np.sum((h-y)*X1[:, 2])\n theta = theta - alpha*np.array([theta1_tmp, theta2_tmp, theta3_tmp])\n \n theta0 = theta[0]\n theta1 = theta[1]\n theta2 = theta[2]\n \n plot_x = np.array([min(X[:,0])-2, max(X[:,0])+2])\n plot_y = - (theta0 + theta1*plot_x) / theta2\n plt.plot(plot_x, plot_y, 'b')\n \n plt.show()\n \n```\n\n[![出力結果](https://i.stack.imgur.com/g5MNK.png)](https://i.stack.imgur.com/g5MNK.png)", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-13T15:23:34.933", "favorite_count": 0, "id": "33987", "last_activity_date": "2017-05-31T12:46:04.303", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "22545", "post_type": "question", "score": 0, "tags": [ "python", "機械学習" ], "title": "Logistic Regression実装について", "view_count": 134 }
[ { "body": "```\n\n theta1_tmp = 1/m * np.sum((h-y)*X1[:, 0])\n \n```\n\nの式から下記のステートメントは\n\n```\n\n O = np.ones(len(y))\n m = float(len(y))\n Xm = X/m #後で1/mが出るので不要\n X1 = np.c_[O,Xm]\n \n```\n\nこうかと思います。\n\n```\n\n O = np.ones(len(X)) #入力の数分1初期化テンソルを作成(yとXは同じ数だと思うので元の式でも良いが一応定義としてXに修正)\n m = float(len(X)) #入力データ数\n X1 = np.c_[O,X] #1初期化テンソルおよび入力データ\n \n```\n\nまた手元で試してみましたが学習回数1000回ではエントロピー(下記クロスエントロピーのコスト関数の値をループ分の箇所に挿入してprint)が収束しませんでした。\n\n```\n\n 1/m * np.sum((-y*np.log(h) - (1-y)*np.log(1-h)))\n \n```\n\n上記の値が1000回程度では0.8(これはかなり悪い値)でした。\n\nデータも私が自前で用意したものになりますのである程度結果も異なってくるかと思いますが、 \n訓練回数50000回/学習率は0.001(これ以上にしたら発散した)でエントロピーの値が0.3(これもあまり良くない値0.1以下にしたい)になりましたが、plot上の境界線は「それなりに」分類できている状態となりました。 \n[![結果](https://i.stack.imgur.com/4GwTl.png)](https://i.stack.imgur.com/4GwTl.png)", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-05-29T13:20:40.493", "id": "35112", "last_activity_date": "2017-05-31T12:46:04.303", "last_edit_date": "2017-05-31T12:46:04.303", "last_editor_user_id": "19716", "owner_user_id": "19716", "parent_id": "33987", "post_type": "answer", "score": 1 } ]
33987
35112
35112
{ "accepted_answer_id": "33990", "answer_count": 1, "body": "WndProcについての質問です。 \nプロセスA → \nプロセスC \nプロセスB →\n\n(A,B,Cは別々のアプリです)\n\nプロセスCにWndProcのプロシージャを起動させておきます。 \nプロセスA,BはプロセスCにプロセス間通信にてwinメッセージを送ります。 \nプロセスCは受け取ったWinメッセージによって、処理を変えます。\n\n1.プロセスAのメッセージを受信後、すぐにプロセスBからメッセージが来たとします。 \nプロセスAのメッセージに対しての処理はまだ終わっていません。 \nこの場合、プロセスBのメッセージはどうなるのでしょうか?\n\n2.一度、プロセスCでメッセージを受信をしたら、MessageBox.Showを出すプログラムを作成し試しました。プロセスAのメッセージを受信後、メッセージボックスが表示され、OKボタンを押さずにそのままにしておきます。プロセスBのメッセージ受信後、2つ目のメッセージボックスが表示されました。これは、各メッセージに対して、スレッドが立っているということなのでしょうか。\n\n提示できるコードがなく大変恐縮なのですが、 \nご回答いただけると幸いです。 \nよろしくお願い致します。", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-13T15:37:38.523", "favorite_count": 0, "id": "33989", "last_activity_date": "2017-05-14T13:55:14.460", "last_edit_date": "2017-05-14T13:55:14.460", "last_editor_user_id": "19213", "owner_user_id": "19213", "post_type": "question", "score": 1, "tags": [ "c#", "winapi" ], "title": "C# WndProcについて", "view_count": 783 }
[ { "body": "> 1.プロセスAのメッセージを受信後、すぐにプロセスBからメッセージが来たとします。 プロセスAのメッセージに対しての処理はまだ終わっていません。\n> この場合、プロセスBのメッセージはどうなるのでしょうか?\n\nメッセージキューに入っています。\n\n>\n> 2.一度、プロセスCでメッセージを受信をしたら、MessageBox.Showを出すプログラムを作成し試しました。プロセスAのメッセージを受信後、メッセージボックスが表示され、OKボタンを押さずにそのままにしておきます。プロセスBのメッセージ受信後、2つ目のメッセージボックスが表示されました。これは、各メッセージに対して、スレッドが立っているということなのでしょうか。\n\n違います。 \nプロセスCは1つ目のメッセージボックスを表示したあとすぐにモーダルループといわれるメッセージループに入ります。そこでプロセスBからのメッセージを受けるとウィンドウプロシージャにディスパッチされ、2つ目のメッセージボックスが表示されることになります。 \nこれらは1つのスレッドの中で行われます。", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-13T17:57:34.030", "id": "33990", "last_activity_date": "2017-04-13T17:57:34.030", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "4765", "parent_id": "33989", "post_type": "answer", "score": 5 } ]
33989
33990
33990
{ "accepted_answer_id": "33995", "answer_count": 1, "body": "httpを80番から変更したものを内部LANで使用したいと思っています。 \nよく使われるのは8080番ですが、一般的に複数ポート番号を用意したいとき何番を使うのが一般的なのでしょうか?\n\ndockerを使って100ポート数の違う番号でhttpを使用したいと思っています。 \nあまりにも変な番号をつけて不具合や一般的には違うという事になりたくないなと思いまして質問させていただいています。\n\nよろしくお願いします。", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-14T01:28:53.573", "favorite_count": 0, "id": "33992", "last_activity_date": "2017-04-14T03:00:50.913", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "8593", "post_type": "question", "score": 0, "tags": [ "http" ], "title": "内部LANで使用するhttpのポート番号", "view_count": 282 }
[ { "body": "8080の他に、10080もよく使われます。複数必要な場合は8081,8082...のように採番するのが一般的だと思います。\n\nただ、100というと数が多すぎるので、ポートだけでなく複数のIPアドレスに分割することを検討した方がいいように思います。まさか1コンテナということはないでしょうから、コンテナを複数ホストに分割するときにも楽になります。", "comment_count": 1, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-14T03:00:50.913", "id": "33995", "last_activity_date": "2017-04-14T03:00:50.913", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "5793", "parent_id": "33992", "post_type": "answer", "score": 1 } ]
33992
33995
33995
{ "accepted_answer_id": null, "answer_count": 1, "body": "プロパティ名に変数を入れたいと思っているのですが、エラーになります。 \nコードは以下です。 \n何か良い方法はないでしょうか。 \nよろしくお願いします。\n\n```\n\n var overrideCtx = {};\n overrideCtx.Templates = {};\n \n for (var i = 1; i <= 127; i++) {\n var hoge = \"\";\n hoge += \"Test\";\n hoge += i\n \n overrideCtx.Templates.Fields = {\n hoge: { 'DisplayForm': ConvertIcon }\n };\n \n```", "comment_count": 2, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-14T02:18:29.007", "favorite_count": 0, "id": "33993", "last_activity_date": "2017-04-14T09:03:06.537", "last_edit_date": "2017-04-14T09:03:06.537", "last_editor_user_id": "5044", "owner_user_id": "22552", "post_type": "question", "score": 1, "tags": [ "javascript", "sharepoint" ], "title": "プロパティ名に変数を入れたい", "view_count": 893 }
[ { "body": "オブジェクトのプロパティに`[プロパティ名]`を使用してアクセスします。\n\n```\n\n var overrideCtx = {};\n overrideCtx.Templates = {};\n overrideCtx.Templates.Fields = {};\n for (var i = 1; i <= 127; i++) {\n var hoge = \"\";\n hoge += \"Test\";\n hoge += i\n \n overrideCtx.Templates.Fields[hoge] = { value: hoge };\n }\n \n```", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-14T04:06:57.357", "id": "33997", "last_activity_date": "2017-04-14T04:06:57.357", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "20272", "parent_id": "33993", "post_type": "answer", "score": 3 } ]
33993
null
33997
{ "accepted_answer_id": null, "answer_count": 1, "body": "掲題の通りです。\n\nExcelのテーブルをJSONに変換する記事は見つけられるのですがYamlに変換する情報は見つけられませんでした。 \nご存知の方がいらしたらご教示頂きたいです。", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-14T05:57:18.030", "favorite_count": 0, "id": "34002", "last_activity_date": "2017-04-14T07:39:59.353", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "2675", "post_type": "question", "score": 0, "tags": [ "excel", "vba" ], "title": "VBAを使いExcelのテーブルからYamlを出力することはできますか?", "view_count": 2837 }
[ { "body": "JSONはYAMLのサブセットなので、JSON出力ができるならYAML出力もできているのでは?と言いたいところですが、YAMLらしい(?)YAMLを出力したいということですね。\n\nJSON同様YAMLもただの文字列ですから、「出力することができない」なんてことはありません。ひたすら文字列結合を行うだけです。\n\nごく簡単な例を挙げると、例えば次のようになります。\n\n```\n\n Sub ToYAML()\n Dim r As Integer, c As Integer\n Dim result As String\n \n For r = 2 To 6\n result = result & \"- \"\n For c = 1 To 3\n result = result & Cells(1, c).Value & \": \" & Cells(r, c).Value & vbCrLf & \" \"\n Next c\n result = Left(result, Len(result) - 2) ' 末尾の余分な \" \" を取り除く\n Next r\n \n Debug.Print result\n End Sub\n \n```\n\n[![画像の説明をここに入力](https://i.stack.imgur.com/4BIoN.png)](https://i.stack.imgur.com/4BIoN.png)\n\n対象とする範囲、ValueなのかTextなのか、クォートの有無、出力方法、等は質問に書かれていないので適当です。必要に応じて調整してください。", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-14T07:39:59.353", "id": "34007", "last_activity_date": "2017-04-14T07:39:59.353", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "8000", "parent_id": "34002", "post_type": "answer", "score": 1 } ]
34002
null
34007
{ "accepted_answer_id": "34005", "answer_count": 1, "body": "```\n\n function func1 () {\n \n return Array(3).fill({}).map((item, index) => {\n \n return Object.assign(item, {index: index});\n });\n };\n \n```\n\n私はこのfunctionの返り値が以下のようになるのを期待していました。\n\n```\n\n console.log( func1() ); // [ { index: 0 }, { index: 1 }, { index: 2 } ]\n \n```\n\nしかし実際は以下のような結果になりました。\n\n```\n\n console.log( func1() ); // [ { index: 2 }, { index: 2 }, { index: 2 } ]\n \n```\n\nこれはObject.assign()の評価のタイミングの問題なのでしょうか? \nこのことについて詳しく説明できる方がいれば教えていただきたいです。\n\nちなみに以下のようにObject.assignの評価を強制的にmap内で済ませることで期待する結果を返すことはできました。\n\n```\n\n function func2 () {\n \n return Array(3).fill({}).map((item, index) => {\n \n return JSON.parse(JSON.stringify(Object.assign(item, {index: index})));\n });\n }\n \n console.log( func2() ) // [ { index: 0 }, { index: 1 }, { index: 2 } ]\n \n```", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-14T06:45:32.310", "favorite_count": 0, "id": "34004", "last_activity_date": "2017-04-14T08:54:54.627", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "14401", "post_type": "question", "score": 4, "tags": [ "javascript" ], "title": "Object.assign()の評価タイミング(?)について", "view_count": 191 }
[ { "body": "[Array.prototype.fill()](https://developer.mozilla.org/en-\nUS/docs/Web/JavaScript/Reference/Global_Objects/Array/fill)の実装は単純な代入ですので、参照型の値を渡した場合、同じオブジェクトを各要素が参照することになります。\n\n```\n\n const fillObj = {};\n const arr = Array(3).fill(fillObj);\n /* is equal to...\n for (let i = 0; i < 3; i++) {\n arr[i] = fillObj; // NOT arr[i] = {};\n }*/\n \n console.assert(arr.every(el => el === fillObj));\n \n```\n\nこれを回避する方法としては、[Spread syntax](https://developer.mozilla.org/en-\nUS/docs/Web/JavaScript/Reference/Operators/Spread_operator)と[Array.prototype.map()](https://developer.mozilla.org/en-\nUS/docs/Web/JavaScript/Reference/Global_Objects/Array/map)を使用した方法があります。要素数を指定した配列初期化処理としても有用です。\n\n```\n\n const arr = [...Array(3)].map((v, i) => ({ index: i }));\n \n console.assert(arr.every((el, i) => el.index === i));\n \n```", "comment_count": 1, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-14T07:03:20.217", "id": "34005", "last_activity_date": "2017-04-14T08:54:54.627", "last_edit_date": "2017-04-14T08:54:54.627", "last_editor_user_id": null, "owner_user_id": null, "parent_id": "34004", "post_type": "answer", "score": 1 } ]
34004
34005
34005
{ "accepted_answer_id": "34034", "answer_count": 1, "body": "GTK+でTextViewのウェジット全体の背景を \n最新のバージョンで変えられるものはありますか?", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-14T08:38:20.180", "favorite_count": 0, "id": "34008", "last_activity_date": "2017-04-15T08:06:23.373", "last_edit_date": "2017-04-15T08:06:23.373", "last_editor_user_id": "3054", "owner_user_id": "21169", "post_type": "question", "score": 1, "tags": [ "c", "gtk", "gui" ], "title": "GTKでTextViewウィジェットの全体の背景を変える", "view_count": 928 }
[ { "body": "## 概要\n\nGtk3 ではウィジェットの外観を CSS で設定出来ます。 \nこれは HTML で行なわれている事と同じ考え方です。 \nただし、CSS などの仕様に厳密に従っているわけではありません。 \nリファレンスの関連箇所は [Part IV. Theming in\nGTK+](https://developer.gnome.org/gtk3/stable/theming.html) です。\n\nCSSの概要は [Overview of CSS in\nGTK+](https://developer.gnome.org/gtk3/stable/chap-css-\noverview.html)で、サポートされている CSS プロパティは [Supported CSS\nProperties](https://developer.gnome.org/gtk3/stable/chap-css-properties.html)\nで説明されています。\n\n## 流れ\n\nまずは変更したいウィジェットの CSS ノードを確認します。 \n[GtkTextView](https://developer.gnome.org/gtk3/stable/GtkTextView.html#GtkTextView.description)\nは下記のノードを持ちます。\n\n```\n\n CSS nodes\n \n textview.view\n ├── border.top\n ├── border.left\n ├── text\n │ ╰── [selection]\n ├── border.right\n ├── border.bottom\n ╰── [window.popup]\n \n```\n\nこれを見て、CSS のセレクタを決めます。 \n通常のテキスト部分は `textview.view text` で、選択中のテキスト部分は `textview.view text selection`\nかな、などとあたりを付けておいて、試行する事になります。\n\nそのセレクタにスタイルを当てるのですが、背景色を変更するならば、前景色(文字などの色)やカーソルの色なども同時に指定する必要があります。 \nユーザーがどのようなテーマを使用しているか分からないからです。 \n背景色だけ指定すると、その色がユーザーが使用している前景色と近く、文字などが読めなくなる可能性があります。\n\n```\n\n textview.view text {\n color: white;\n caret-color: green;\n background-color: black;\n }\n textview.view text selection {\n color: red;\n background-color: blue;\n }\n \n```\n\n作ったCSS は\n[GtkCssProvider](https://developer.gnome.org/gtk3/stable/GtkCssProvider.html)\nにロードします。 \nその GtkCssProvider を何らかの\n[GtkStyleContext](https://developer.gnome.org/gtk3/stable/GtkStyleContext.html)\nに追加する事で外観が変わります。 \nスタイルをアプリケーション全体に適用するならば、\"screen\" に対して\n[`gtk_style_context_add_provider_for_screen()`](https://developer.gnome.org/gtk3/stable/GtkStyleContext.html#gtk-\nstyle-context-add-provider-for-screen) で追加します。 \n特定のウィジェットに適用するならば、そのウィジェットから\n[`gtk_widget_get_style_context()`](https://developer.gnome.org/gtk3/stable/GtkWidget.html#gtk-\nwidget-get-style-context) で取得した GtkStyleContext に\n[`gtk_style_context_add_provider()`](https://developer.gnome.org/gtk3/stable/GtkStyleContext.html#gtk-\nstyle-context-add-provider) で追加します。\n\n## 例\n\nPython になりますがスタイルの設定を数パターン使用している例です。\n\n```\n\n #!/usr/bin/python3\n import gi\n gi.require_version('GLib', '2.0')\n gi.require_version('Gtk', '3.0')\n from gi.repository import GLib\n from gi.repository import Gtk\n \n # イベントループ\n loop = GLib.MainLoop()\n \n # メインウィンドウ\n win = Gtk.Window.new(Gtk.WindowType.TOPLEVEL)\n win.set_title(\"スタイル変更\")\n win.connect(\"delete-event\", lambda *x: loop.quit())\n \n # コンテナ\n box = Gtk.VBox.new(True, 10)\n win.add(box)\n \n # バッファ\n buf = Gtk.TextBuffer.new(None)\n buf.set_text(\"今日は、世界!\\n Hello, world!\\n\")\n \n # ビュー\n view_01 = Gtk.TextView.new_with_buffer(buf)\n view_01.set_name(\"top\")\n box.add(view_01)\n \n view_02 = Gtk.TextView.new_with_buffer(buf)\n box.add(view_02)\n \n view_03 = Gtk.TextView.new_with_buffer(buf)\n box.add(view_03)\n \n # テキストビューの背景を黒くする CSS\n # top と名付けたテキストビューには個別のスタイルを指定\n # デフォルトのフォントは text ノードではなくテキストビューのトップレベルに指定する模様\n black_css = Gtk.CssProvider.new()\n black_css.load_from_data(\n b\"\"\"\n textview.view text {\n color: white;\n caret-color: green;\n background-color: black;\n }\n textview.view text selection {\n color: red;\n background-color: blue;\n }\n \n textview.view#top text {\n color: orange;\n }\n textview.view#top {\n font: 1.5em serif;\n }\n \"\"\")\n \n # 上の CSS を全体に設定\n Gtk.StyleContext.add_provider_for_screen(\n win.get_property(\"screen\"),\n black_css,\n Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION\n )\n \n # 背景を灰色にする CSS\n gray_css = Gtk.CssProvider.new()\n gray_css.load_from_data(\n b\"\"\"\n textview.view text {\n background-color: gray;\n }\n \"\"\")\n \n # 上の CSS をテキストビュー 02 に設定\n style_context = view_02.get_style_context();\n style_context.add_provider(gray_css, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)\n \n \n # スタート\n win.show_all()\n loop.run()\n \n```\n\n![スタイル変更の例](https://i.stack.imgur.com/kK9Ae.png)", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-15T08:04:53.360", "id": "34034", "last_activity_date": "2017-04-15T08:04:53.360", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "3054", "parent_id": "34008", "post_type": "answer", "score": 0 } ]
34008
34034
34034
{ "accepted_answer_id": null, "answer_count": 4, "body": "TDM-GCC 5.1.0 で以下のソースを `gcc -std=c99 -pedantic test.c` のように `c99`\nを指定してコンパイルを実行すると、`%lf` 指定した方の出力が `0.000000` になってしまいます。\n\n**対象のソースコード:**\n\n```\n\n #include <stdio.h>\n \n int main(void){\n double v = 3.1415926;\n printf(\"%f\\n\", v);\n printf(\"%lf\\n\", v);\n }\n \n```\n\n**実行結果 (c99 オプションありでコンパイル):**\n\n```\n\n 3.141593\n 0.000000\n \n```\n\n一方、オプション指定なし(`gcc test.c`)でコンパイルした場合には、期待通りの結果が得られます。\n\n**実行結果 (c99 オプションなしでコンパイル):**\n\n```\n\n 3.141593\n 3.141593\n \n```\n\n![screen shot](https://i.stack.imgur.com/lU5yX.png)\n\n`printf` での `%lf` の使用は C99 では適合なはずなので、おかしな結果です。\n\n以前使用していた古いバージョンの GCC (MinGw gcc3.2) では`c99`オプション使用時に`%lf`は使用できていたので、この GCC\nでの固有バグではないかと思いますが、当面(バグフィックスされるまで)困るので回避方法を探しています。\n\n`C99` オプションなしでコンパイルした場合は問題ないので、なんらかの方法で回避できるのではないかと思っています。", "comment_count": 10, "content_license": "CC BY-SA 4.0", "creation_date": "2017-04-14T12:12:52.837", "favorite_count": 0, "id": "34013", "last_activity_date": "2022-11-06T07:23:27.633", "last_edit_date": "2022-11-06T07:23:27.633", "last_editor_user_id": "4236", "owner_user_id": "5044", "post_type": "question", "score": 5, "tags": [ "c", "windows", "gcc", "mingw", "c99" ], "title": "TDM-GCC 5.1.0 で c99 オプションを指定したコンパイル時、printf の %lf で出力される結果が想定と異なる", "view_count": 1723 }
[ { "body": "[@nekketsuuu\nさんのコメント](https://ja.stackoverflow.com/questions/34013/printf-%E3%81%AE-\nlf-%E3%81%AB%E3%81%A4%E3%81%84%E3%81%A6/34023?noredirect=1#comment33587_34013)の[リンク先の回答](https://stackoverflow.com/questions/27363795/mingw-\ndoesnt-produce-warnings)で指摘されているように、どうやらTDM での元になっているMinGW4.8からのバグ(`%lf`が`long\ndouble`への指定だと解釈される)のようです。\n\n```\n\n printf(\"%lf\\n\", (long double)v);\n \n```\n\nとすると期待する値が表示されました。(つまり`long double`への指定だと解釈されていた) \n(本来`long double`を意味する`%Lf`は期待通り動作します)\n\n別の場所で`__USE_MINGW_ANSI_STDIO` マクロを指定するというような情報もあったのですが、 \n少なくとも現状は機能しないようです。 \n([sayuriさんの回答](https://ja.stackoverflow.com/a/34023/19110)から、機能しないというより`-std=c99`の場合既に指定された状態)\n\nMinGW-w64ではこのような問題はないらしいのでコンパイラを切り替えるか\n\n`-std=c99` の代わりに `-std=gnu99`を使用するのが簡易な解決のようです。 \n(しかし、その場合`%zu`が使用できなくなる)\n\n`-std=c99` のような(`-std=c11` でも)標準規格指定がされた時に参照ヘッダが切り替わることが動作が異なる理由らしいですが、 \nそこら辺の切り替えをユーザーから問題を起こすことなしにうまく切り替えることができたらいいんですが、多分色々絡み合ってて難しいんでしょうね。\n\n* * *\n\n * 関連しそうなリンク (コメント参照) \n * mingw.orgにあるwiki上の[C99についてのページ](http://www.mingw.org/wiki/c99)。ここにMSVCRTとMinGWのC99についての歴‌​史が短く書いてあります。\n * MinGWのバグトラッカーにあった「`%lf`の表示がおかしい」というissueに対して、「ISO-C99では`printf(‌​)`の \"l\" は単に無視されるので無駄だ。また、Microsoftは`%lf`は`%Lf` (double long) になると言っている。`%f`を使おう」というコメントがついているところ: <https://sourceforge.net/p/mingw/bugs/2253/>\n * Microsoftでの[サイズ指定解釈](https://msdn.microsoft.com/ja-jp/library/tcxf1dw6.aspx)\n * `__USE_MINGW_ANSI_STDIO`を使ったら?と言っている[Stack Overflowでの回答](https://stackoverflow.com/questions/26296058/cant-print-correctly-a-long-double-in-c)", "comment_count": 8, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-14T13:48:39.190", "id": "34015", "last_activity_date": "2017-04-15T15:50:16.237", "last_edit_date": "2017-05-23T12:38:55.307", "last_editor_user_id": "-1", "owner_user_id": "5044", "parent_id": "34013", "post_type": "answer", "score": 0 }, { "body": "`-std=c99`指定の時は、`\"%Lf\"`と同じ扱いをされてしまっているのかな? \n`printf()`は可変長引数で`float`は`double`に拡張されるため、昔は`\"%lf\"`は間違いでした。 \n[C99で`\"%lf\"`が許されるようになった](http://seclan.dll.jp/c99d/c99d0a2.htm#appendix_printf)とはいえ、敢えて`\"%lf\"`にしなくても良いのではないでしょうか。\n\n```\n\n #include <stdio.h>\n \n int main(void)\n {\n double v = 3.1415926;\n printf(\"sizeof(double) = %u\\n\", (unsigned)sizeof(double));\n printf(\"sizeof(long double) = %u\\n\", (unsigned)sizeof(long double));\n printf(\"%%f - double :%f\\n\", v);\n printf(\"%%lf - double :%lf\\n\", v);\n printf(\"%%Lf - double :%Lf\\n\", v);\n printf(\"%%f - (long double):%f\\n\", (long double)v);\n printf(\"%%lf - (long double):%lf\\n\", (long double)v);\n printf(\"%%Lf - (long double):%Lf\\n\", (long double)v);\n }\n \n```\n\nコンパイル結果:\n\n```\n\n d:\\tmp>gcc -Wall -pedantic -std=c99 double.c\n \n```\n\n実行結果:\n\n```\n\n d:\\tmp>a.exe\n sizeof(double) = 8\n sizeof(long double) = 12\n %f - double :3.141593\n %lf - double :0.000000\n %Lf - double :0.000000\n %f - (long double):-88793646155857547477275137080339417618448384.000000\n %lf - (long double):3.141593\n %Lf - (long double):3.141593\n \n```\n\nコンパイル結果:\n\n```\n\n d:\\tmp>gcc -Wall -pedantic double.c\n double.c: In function 'main':\n double.c:10:12: warning: unknown conversion type character 'L' in format [-Wformat=]\n printf(\"%%Lf - double :%Lf\\n\", v);\n ^\n double.c:10:12: warning: too many arguments for format [-Wformat-extra-args]\n double.c:11:12: warning: format '%f' expects argument of type 'double', but argument 2 has type 'long double' [-Wformat=]\n printf(\"%%f - (long double):%f\\n\", (long double)v);\n ^\n double.c:12:12: warning: format '%lf' expects argument of type 'double', but argument 2 has type 'long double' [-Wformat=]\n printf(\"%%lf - (long double):%lf\\n\", (long double)v);\n ^\n double.c:13:12: warning: unknown conversion type character 'L' in format [-Wformat=]\n printf(\"%%Lf - (long double):%Lf\\n\", (long double)v);\n ^\n double.c:13:12: warning: too many arguments for format [-Wformat-extra-args]\n \n```\n\n実行結果:\n\n```\n\n d:\\tmp>a.exe\n sizeof(double) = 8\n sizeof(long double) = 12\n %f - double :3.141593\n %lf - double :3.141593\n %Lf - double :3.141593\n %f - (long double):-88793646155857547000000000000000000000000000.000000\n %lf - (long double):-88793646155857547000000000000000000000000000.000000\n %Lf - (long double):-88793646155857547000000000000000000000000000.000000\n \n```\n\n参考:\n\n * [プログラミング言語 C の新機能 - A.2.5 長さ修飾子](http://seclan.dll.jp/c99d/c99d0a2.htm#appendix_printf \"プログラミング言語 C の新機能\")", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-14T14:32:38.333", "id": "34021", "last_activity_date": "2017-04-15T05:46:09.870", "last_edit_date": "2017-04-15T05:46:09.870", "last_editor_user_id": "7291", "owner_user_id": "7291", "parent_id": "34013", "post_type": "answer", "score": 0 }, { "body": "# `-std=c99`と`-std=gnu99`で動作が変わる理由\n\nTDM-GCCがベースにしているMinGWにはMinGW stdioとMSVCRT\nstdioの2種類のstdioが存在します。`__mingw_printf()`と`__msvcrt_printf()`の名前でアクセスできます。\n\n```\n\n #include <stdio.h>\n \n int main(void){\n double v = 3.1415926;\n printf(\"%f\\n\", v);\n printf(\"printf(): %lf\\n\", v);\n __mingw_printf(\"__mingw_printf(): %lf\\n\", v);\n __msvcrt_printf(\"__msvcrt_printf(): %lf\\n\", v);\n }\n \n```\n\nMSVCRT stdioの実体は`MSVCRT.dll`ですがこれは1998年にリリースされたVisual C++\n6.0のものですので、C99やC11といった仕様とは無縁です。[Format Specification Fields: printf and\nwprintf Functions](https://msdn.microsoft.com/en-\nus/library/aa246400\\(v=vs.60\\).aspx)に`printf()`のドキュメントがありましたが、[`%zu`](https://msdn.microsoft.com/en-\nus/library/aa272936\\(v=vs.60\\).aspx)という指定も存在しません。\n\nさてMinGW stdioとMSVCRT\nstdioは`<stdio.h>`の次の記述により`__USE_MINGW_ANSI_STDIO`の値により動作が切り替わります。\n\n```\n\n #if __USE_MINGW_ANSI_STDIO\n /*\n * User has expressed a preference for C99 conformance...\n */\n (略)\n \n __mingw_stdio_redirect__\n int printf (const char *__format, ...)\n {\n register int __retval;\n __builtin_va_list __local_argv; __builtin_va_start( __local_argv, __format );\n __retval = __mingw_vprintf( __format, __local_argv );\n __builtin_va_end( __local_argv );\n return __retval;\n }\n \n (略)\n \n #else\n /*\n * Default configuration: simply direct all calls to MSVCRT...\n */\n _CRTIMP int __cdecl __MINGW_NOTHROW fprintf (FILE*, const char*, ...);\n _CRTIMP int __cdecl __MINGW_NOTHROW printf (const char*, ...);\n _CRTIMP int __cdecl __MINGW_NOTHROW sprintf (char*, const char*, ...);\n _CRTIMP int __cdecl __MINGW_NOTHROW vfprintf (FILE*, const char*, __VALIST);\n _CRTIMP int __cdecl __MINGW_NOTHROW vprintf (const char*, __VALIST);\n _CRTIMP int __cdecl __MINGW_NOTHROW vsprintf (char*, const char*, __VALIST);\n \n #endif\n \n```\n\nここで`__USE_MINGW_ANSI_STDIO`は`<_mingw.h>`で設定されています。\n\n```\n\n /* Activation of MinGW specific extended features:\n */\n #ifndef __USE_MINGW_ANSI_STDIO\n /*\n * If user didn't specify it explicitly...\n */\n # if defined __STRICT_ANSI__ || defined _ISOC99_SOURCE \\\n || defined _POSIX_SOURCE || defined _POSIX_C_SOURCE \\\n || defined _XOPEN_SOURCE || defined _XOPEN_SOURCE_EXTENDED \\\n || defined _GNU_SOURCE || defined _BSD_SOURCE \\\n || defined _SVID_SOURCE\n /*\n * but where any of these source code qualifiers are specified,\n * then assume ANSI I/O standards are preferred over Microsoft's...\n */\n # define __USE_MINGW_ANSI_STDIO 1\n # else\n /*\n * otherwise use whatever __MINGW_FEATURES__ specifies...\n */\n # define __USE_MINGW_ANSI_STDIO (__MINGW_FEATURES__ & __MINGW_ANSI_STDIO__)\n # endif\n #endif\n \n```\n\nコンパイルオプション`-std=c99`や`-ansi`を付けると`__STRICT_ANSI__`が定義されることに連動して`__USE_MINGW_ANSI_STDIO`も定義されます。 \nその結果、MinGW stdioとMSVCRT stdioとが切り替わります。\n\n# 回避策\n\n原理がわかれば明快です。\n\n * `-std=gnu99`を指定する(`-std=c99`や`-ansi`を指定しない)\n * `-D__USE_MINGW_ANSI_STDIO=0`を指定する\n * `printf()`ではなく`__msvcrt_printf()`を使用する\n\nぐらいでしょうか。\n\n# `-std=c99`で使われるMinGW stdioが`%lf`を正しく扱えない原因\n\nTDM-\nGCCのソースコード`mingwrt-3.21-mingw32-src.tar.xz`を確認しました。`printf()`は最終的に`mingwex/stdio/pformat.c`で定義されている`__pformat()`に辿り着きます。\n\n```\n\n case 'l':\n /*\n * Interpret the argument as explicitly of a\n * `long' or `long long' data type.\n */\n if( *fmt == 'l' )\n {\n /* Modifier is `ll'; data type is `long long' sized...\n * Skip the second `l', and set length accordingly.\n */\n ++fmt;\n length = PFORMAT_LENGTH_LLONG;\n }\n \n else\n /* Modifier is `l'; data type is `long' sized...\n */\n length = PFORMAT_LENGTH_LONG;\n \n # ifndef _WIN32\n /*\n * Microsoft's MSVCRT implementation also uses `l'\n * as a modifier for `long double'; if we don't want\n * to support that, we end this case here...\n */\n state = PFORMAT_END;\n break;\n \n /* otherwise, we simply fall through...\n */\n # endif\n \n case 'L':\n /*\n * Identify the appropriate argument as a `long double',\n * when associated with `%a', `%A', `%e', `%E', `%f', `%F',\n * `%g' or `%G' format specifications.\n */\n stream.flags |= PFORMAT_LDOUBLE;\n state = PFORMAT_END;\n break;\n \n```\n\nとなっていて、`_WIN32`が定義されていない環境ではC99相当の`l`フラグを無視しますが、`_WIN32`が定義されている環境ではMSVCRTと動作を合わせるために`L`フラグへfall\nthroughすることで`long double`と見なすようになっています。\n\nなお、MSVCRTについてですが、歴史的に16bit時代は`float` 32bit、`double` 64bit、`long double`\n80bitとしていました。そのため`long double`を`printf()`する際に`%lf`を使用していました。Windows\n95・32bit化の際これを改め`long double` 64bitと変更しました。その結果、`printf()`の`%lf`が`long\ndouble`を表していても`double`を表していてもどの道64bitであり影響がなく`printf()`の使い方としては曖昧になってしまいました。 \nしかし **MinGWでは`long double`を独自に96bitとしてしまっています(本来はVisual\nC++に合わせて64bitとすべきところ)。これは仕様バグとしか言いようがありません。**\nしかも前述のように`printf()`は16bit時代のVisual C++の動作を引きずって`%lf`を`long\ndouble`とみなしてしまっています。\n\nこの食い違いに対処するには`printf(\"%lf\\n\", (long double)v);`等、明示的なキャストを行い正しく引数を与える必要があります。\n\n別の根本的な解決方法としてはgccのコンパイルオプション`-mlong-\ndouble-64`を使うことです。しかし、これを実現するには`printf()`を含むランタイムすべてをビルドし直す必要があります。というかgccからビルドし直す方が早いでしょうか。\n\n# `__USE_MINGW_ANSI_STDIO`マクロについて\n\n`<_mingw.h>`には次のコメントがあります。\n\n```\n\n /* These are defined by the user (or the compiler)\n to specify how identifiers are imported from a DLL.\n \n __DECLSPEC_SUPPORTED Defined if dllimport attribute is supported.\n __MINGW_IMPORT The attribute definition to specify imported\n variables/functions.\n _CRTIMP As above. For MS compatibility.\n __MINGW32_VERSION Runtime version.\n __MINGW32_MAJOR_VERSION Runtime major version.\n __MINGW32_MINOR_VERSION Runtime minor version.\n __MINGW32_BUILD_DATE Runtime build date.\n \n Macros to enable MinGW features which deviate from standard MSVC\n compatible behaviour; these may be specified directly in user code,\n activated implicitly, (e.g. by specifying _POSIX_C_SOURCE or such),\n or by inclusion in __MINGW_FEATURES__:\n \n __USE_MINGW_ANSI_STDIO Select a more ANSI C99 compatible\n implementation of printf() and friends.\n \n```\n\n_These are defined by the user_ とか _these may be specified directly in user\ncode_ とありますから、指定しても構わないと思います。 \nそもそも、MinGW stdioとMSVCRT\nstdioとの切り替え選択という内部実装に強く依存した行為ですから、指定するには細心の注意を払うべきですし、注意して行うのであればためらう必要はないかと。\n\n> たとえば、先の‌​メールで指摘されているように`_POSIX‌​_C_SOURCE`、`_XOPEN_SOURCE`\n> (または`_GNU_SOURCE`) を使うとどうなるのでしょうか?\n\nこれに関しては本回答及びコードをよく確認してください。`#if\n__USE_MINGW_ANSI_STDIO`を不成立させたいのですから、いずれを`#define`しても期待する結果は得られません。", "comment_count": 11, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-14T23:47:56.663", "id": "34023", "last_activity_date": "2017-04-17T01:24:22.470", "last_edit_date": "2017-04-17T01:24:22.470", "last_editor_user_id": "4236", "owner_user_id": "4236", "parent_id": "34013", "post_type": "answer", "score": 9 }, { "body": "[質問者さんのコメントの記述](https://ja.stackoverflow.com/questions/34013/printf-%E3%81%AE-\nlf-%E3%81%AB%E3%81%A4%E3%81%84%E3%81%A6/34028#comment33610_34013)より\n\n> (TDM-GCCを)C99での動作をさせたい\n\nとのことですが、[snprintf\nの返値について](https://ja.stackoverflow.com/q/31646/4236)でもコメントしましたが、規格・仕様と実装は別問題です。GCCはコンパイラーの責任範囲にてC99に準拠しているのかもしれませんが、TDM-\nGCCが実行環境に利用しているMinGWやVisual C++ 6.0はC99準拠を謳っていないはずです。総じてTDM-GCCはC99に準拠していません。\n\nC99を使用したいのであれば、C99に準拠した環境を選択すべきです。", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-15T03:13:07.830", "id": "34028", "last_activity_date": "2017-04-15T04:04:53.170", "last_edit_date": "2017-04-15T04:04:53.170", "last_editor_user_id": "4236", "owner_user_id": "4236", "parent_id": "34013", "post_type": "answer", "score": 1 } ]
34013
null
34023
{ "accepted_answer_id": "34016", "answer_count": 1, "body": "Visual Studio\nCodeにてHTML、JavaScriptはタブスペース2、Pythonでは4といったようにファイル種別ごとに設定を行うことは可能でしょうか?", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-14T13:23:16.150", "favorite_count": 0, "id": "34014", "last_activity_date": "2017-04-14T13:49:10.130", "last_edit_date": "2017-04-14T13:47:29.273", "last_editor_user_id": "8000", "owner_user_id": "20552", "post_type": "question", "score": 3, "tags": [ "vscode" ], "title": "Visual Studio Codeで言語ごとにインデントの設定をしたい", "view_count": 30641 }
[ { "body": "[Language specific editor settings - Visual Studio Code User and Workspace\nSettings](https://code.visualstudio.com/docs/getstarted/settings#_language-\nspecific-editor-settings)で紹介されている言語ごとのエディタ構成からタブスペースサイズをそれぞれ指定すれば可能かと思います。\n\n 1. Ctrl+Shift+Pで開くコマンドパレットに`Preferences: Configure language specific settings`を入力/選択してユーザー用設定を開く。\n 2. 編集対象の言語を入力/選択する。\n 3. スペースサイズは`editor.tabSize`プロパティから設定できます。\n\n参考:\n\n```\n\n {\n \"[javascript]\": {\n \"editor.tabSize\": 2\n },\n \"[python]\": {\n \"editor.tabSize\": 4\n }\n }\n \n```", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-14T13:49:10.130", "id": "34016", "last_activity_date": "2017-04-14T13:49:10.130", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": null, "parent_id": "34014", "post_type": "answer", "score": 7 } ]
34014
34016
34016
{ "accepted_answer_id": null, "answer_count": 1, "body": "レンタルサーバ上に配置されているJavaScriptを実行しているのですが、JavaScript実行により取得した値をサーバ上のログに出力したいと考えています。 \nレンタルサーバなので制限があり、JavaScriptかHTMLしか利用できないと思っています。\n\n * サーバはFC2ホームページです\n * CGIは利用不可です\n * アクセスログも閲覧不可です\n\n何か良い方法があれば教えていただきたく宜しくお願いします。", "comment_count": 3, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-14T13:49:52.763", "favorite_count": 0, "id": "34017", "last_activity_date": "2017-04-14T17:06:56.553", "last_edit_date": "2017-04-14T16:18:34.003", "last_editor_user_id": "3054", "owner_user_id": "22562", "post_type": "question", "score": 1, "tags": [ "javascript", "html" ], "title": "ブラウザ側のJavaScriptから静的サイトホスティングのサーバにログを書き込みたい", "view_count": 577 }
[ { "body": "不可能です。 \nサーバー側に仕組みが用意されていないと、クライアント側(ウェブブラウザ)からサーバーのファイルに書き込んだり、サーバーでプログラムを実行したりは出来ません。\n\nJavaScript や HTML を置いてあるサーバーとは別にサーバーを用意して、JavaScript\nからその別のサーバーに何がしかのリクエストをする事は可能です。 \nこうすれば、今公開しているサーバーの引越し作業などはいりません。 \nしかし、結局の所この別のサーバーを用意するために、今お使いのレンタルサーバより自由度が高いサーバーをレンタルしたり、PaaS\nのようなサービスを利用したりといった事が必要になる事には変わりません。\n\n* * *\n\nログに残したい事の詳細は分かりませんが、もしかしたら [Google\nAnalytics](https://www.google.com/intl/ja_ALL/analytics/index.html)\nなどのサービスで取得出来る内容かも知れませんね。", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-14T16:40:43.817", "id": "34022", "last_activity_date": "2017-04-14T17:06:56.553", "last_edit_date": "2017-04-14T17:06:56.553", "last_editor_user_id": "3054", "owner_user_id": "3054", "parent_id": "34017", "post_type": "answer", "score": 2 } ]
34017
null
34022
{ "accepted_answer_id": null, "answer_count": 1, "body": "以下のコードを実行したいのですがエラーが出てしまいます。 \n解決方法を教えていただけると幸いです。 \n元のコードは[data-science-from-\nscratch/nearest_neighbors.py](https://github.com/joelgrus/data-science-from-\nscratch/blob/master/code/nearest_neighbors.py)にあります。 \n現在Pythonを学び始めたばかりなのですが、したいこととしてはk近傍方でk=1,3,5,7でどのような結果になるのか示したいと認識しています。\n\n```\n\n import math\n \n def knn_classify(k, labeled_points, new_point):\n \"\"\"each labeled point should be a pair (point, label)\"\"\"\n # order the labeled points from nearest to farthest\n by_distance = sorted(labeled_points,\n key=lambda point_label: distance(point_label, new_point))\n # find the labels for the k closest\n k_nearest_labels = [label for _, label in by_distance[:k]]\n return majority_vote(k_nearest_labels)\n \n cities = [(-86.75,33.5666666666667,'Python'),(-88.25,30.6833333333333,'Python'),(-112.016666666667,33.4333333333333,'Java')]\n cities = [([longitude, latitude], language) for longitude, latitude, language in cities]\n \n for k in [1,3,5,7]:\n num_correct = 0 \n for city in cities:\n location,actual_language = city\n other_cities = [other_city for other_city in cities\n if other_city != city]\n predicted_language = knn_classify(k, other_cities, location) \n if predicted_language == actual_language:\n num_correct += 1\n print (k, \"neighbor[s]\", num_correct, \"correct out of\", len(cities) )\n \n```\n\n上記のコードを実行した時に以下のようにエラーが表示されてしまいます。\n\n```\n\n NameError Traceback (most recent call last)\n <ipython-input-32-1bab7195f6b1> in <module>()\n 26 if other_city != city]\n 27 \n ---> 28 predicted_language = knn_classify(k, other_cities, location)\n 29 \n 30 if predicted_language == actual_language:\n \n <ipython-input-32-1bab7195f6b1> in knn_classify(k, labeled_points, new_point)\n 6 # order the labeled points from nearest to farthest\n 7 by_distance = sorted(labeled_points,\n ----> 8 key=lambda point_label: distance(point_label, new_point))\n 9 \n 10 # find the labels for the k closest\n \n <ipython-input-32-1bab7195f6b1> in <lambda>(point_label)\n 6 # order the labeled points from nearest to farthest\n 7 by_distance = sorted(labeled_points,\n ----> 8 key=lambda point_label: distance(point_label, new_point))\n 9 \n 10 # find the labels for the k closest\n \n NameError: name 'distance' is not defined\n \n```", "comment_count": 1, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-14T14:04:35.477", "favorite_count": 0, "id": "34020", "last_activity_date": "2017-04-17T13:26:37.947", "last_edit_date": "2017-04-16T15:27:09.400", "last_editor_user_id": "19110", "owner_user_id": "22563", "post_type": "question", "score": -6, "tags": [ "python" ], "title": "NameErrorが出る", "view_count": 766 }
[ { "body": "python は詳しくないのですが…\n\n`distance` メソッドは\n\n```\n\n from linear_algebra import distance\n \n```\n\nここで宣言されているように、`linear_algebra.py` が必要です。 \n(で、`linear_algebra.py` を読み込もうとすると、また他のものが芋づる式に必要になってくるのでしょうけど)\n\nまた、`majority_vote` メソッドも不足しているようですね。 \nこれは元のコード `nearest_neighbors.py` に含まれていますね。", "comment_count": 2, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-17T13:26:37.947", "id": "34076", "last_activity_date": "2017-04-17T13:26:37.947", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "5288", "parent_id": "34020", "post_type": "answer", "score": 2 } ]
34020
null
34076
{ "accepted_answer_id": null, "answer_count": 1, "body": "python初心者です。\n\nインタフェース2017/3月号で60page記載の \nJupyter Notebookで \nimport tensorflow as tf \nとすると、 \nImportError: No module named 'tensorflow' \nのエラーで実行できませんでした。 \n[![画像の説明をここに入力](https://i.stack.imgur.com/bxaDX.png)](https://i.stack.imgur.com/bxaDX.png)\n\ntensorflow / ipythonはconda install済みです。 \n[![画像の説明をここに入力](https://i.stack.imgur.com/LoNRs.png)](https://i.stack.imgur.com/LoNRs.png)\n\n試しに、tensor.pyのある、フォルダパスを下記で追加して試しましたが、相変わらず問題は解決しませんでした。 \nsys.path.append(\"c:\\tmp\\AI\\Anaconda3\\Lib\\site-packages\\sympy\\tensor\")\n\n何が問題か教えて下さい。\n\n環境:Windows10 64bit \nAnaconda 4.3.1ダウンロード", "comment_count": 2, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-15T02:07:28.910", "favorite_count": 0, "id": "34024", "last_activity_date": "2018-01-21T14:38:57.993", "last_edit_date": "2017-04-15T02:14:33.927", "last_editor_user_id": "22571", "owner_user_id": "22571", "post_type": "question", "score": 1, "tags": [ "python", "anaconda" ], "title": "Jupyter notebookで、import tensorflow でImportError: No moduleになる。", "view_count": 6354 }
[ { "body": "env tensorflow に jupyter をインストールしていないので、jupyterコマンドが env tensorflow にないのでしょう。 \nAnacondaのデフォルト環境の方のjupyterコマンドが実行されているのではないかと思います。\n\nactivate tensorflow \nconda install jupy", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-17T11:41:33.257", "id": "34073", "last_activity_date": "2017-04-17T11:41:33.257", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "12274", "parent_id": "34024", "post_type": "answer", "score": 2 } ]
34024
null
34073
{ "accepted_answer_id": "34035", "answer_count": 1, "body": "記事についたコメントを編集出来るようにしたいのです。 \nコメントをformに持っていき編集して更新ボタンをクリックすると \nNo route matches [PATCH] \"/articles/1/comments\" \nのようなエラーが出てきてrotesなどを色々変えて見たのですが全然、治らないので見ていただけないでしょうか? \n_form.html.erb\n\n```\n\n <%= form_for(comment, url: article_comments_path) do |f| %>\n <% if comment.errors.any? %>\n <div id=\"error_explanation\">\n <h2><%= pluralize(comment.errors.count, \"error\") %></h2>\n <ul>\n <% comment.errors.full_messages.each do |message| %>\n <li><%= message %></li>\n <% end %>\n </ul>\n </div>\n <% end %>\n <div class=\"field\">\n <%= f.label :content %>\n <%= f.text_area :content %>\n </div>\n <div class=\"field\">\n <%= f.label :article_id %>\n <%= f.number_field :article_id %>\n </div>\n <div class=\"actions\">\n <%= f.submit %>\n </div>\n <% end %>\n \n```\n\nroutes.rb\n\n```\n\n rails.application.routes.draw do\n \n get '/users' => 'users#index'\n get '/users/:id' => 'users#show'\n devise_for :users\n resources :articles do\n resources :comments\n end\n \n # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html\n end\n \n```\n\ncomments_controller.rb\n\n```\n\n class CommentsController < ApplicationController\n before_action :set_comment, only: [:show, :edit, :update, :destroy]\n \n # GET /comments\n # GET /comments.json\n def index\n @comments = Comment.all\n end\n \n # GET /comments/1\n # GET /comments/1.json\n def show\n end\n \n # GET /comments/new\n def new\n @comment = Comment.new\n end\n \n # GET /comments/1/edit\n def edit\n end\n \n # POST /comments\n # POST /comments.json\n def create\n @article = Article.find(params[:article_id])\n @comment = Comment.new(comment_params)\n redirect_to article_path(@article)\n \n respond_to do |format|\n if @comment.save\n format.html { redirect_to @article, notice: 'Comment was successfully created.'}\n format.json { render :show, status: :created, location: @article } and return\n \n else\n format.html { render :new }\n format.json { render json: @comment.errors, status: :unprocessable_entity }\n end\n end\n end\n \n # PATCH/PUT /comments/1\n # PATCH/PUT /comments/1.json\n def update\n respond_to do |format|\n if @comment.update(comment_params)\n format.html { redirect_to @comment, notice: 'Comment was successfully updated.' }\n format.json { render :show, status: :ok, location: @comment }\n else\n format.html { render :edit }\n format.json { render json: @comment.errors, status: :unprocessable_entity }\n end\n end\n end\n \n # DELETE /comments/1\n # DELETE /comments/1.json\n def destroy\n @comment.destroy\n respond_to do |format|\n format.html { redirect_to comments_url, notice: 'Comment was successfully destroyed.' }\n format.json { head :no_content }\n end\n end\n \n private\n # Use callbacks to share common setup or constraints between actions.\n def set_comment\n @comment = Comment.find(params[:id])\n end\n \n # Never trust parameters from the scary internet, only allow the white list through.\n def comment_params\n params.require(:comment).permit(:content, :article_id)\n end\n end\n \n```", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-15T04:37:28.513", "favorite_count": 0, "id": "34031", "last_activity_date": "2017-04-15T08:52:21.360", "last_edit_date": "2017-04-15T06:45:02.290", "last_editor_user_id": "5288", "owner_user_id": "22565", "post_type": "question", "score": 0, "tags": [ "ruby-on-rails", "ruby" ], "title": "エラーが取れないです。No route matches [PATCH] \"/articles/1/comments\"", "view_count": 2297 }
[ { "body": "まず、`new` で、`@comment` が article と関連付けられていません。 \n以下のようにすると関連付けられます。\n\n```\n\n def new\n @article = Article.find(params[:article_id])\n @comment = @article.comments.build\n end\n \n```\n\n同様に `edit` でも `@article` を設定しておきます。\n\n```\n\n def edit\n @article = @comment.article\n end\n \n```\n\nで、`No route matches [PATCH] \"/articles/1/comments\"` については、\n\n```\n\n <%= form_for([article, comment]) do |f| %>\n \n```\n\nで治ります。 \nただし、article も渡してやる必要があります。これは、`new.html.erb` や `edit.html.erb` で\n\n```\n\n <%= render 'form', comment: @comment %>\n \n```\n\nといった感じになっていると思いますので、以下のように追加します。\n\n```\n\n <%= render 'form', comment: @comment, article: @article %>\n \n```\n\n最後に、`update` メソッドの\n\n```\n\n format.html { redirect_to @comment, notice: 'Comment was successfully updated.' }\n \n```\n\nでエラーが出ますので、\n\n```\n\n format.html { redirect_to article_comment_path(@comment), notice: 'Comment was successfully updated.' }\n \n```\n\nと修正すると解決します。", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-15T08:52:21.360", "id": "34035", "last_activity_date": "2017-04-15T08:52:21.360", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "5288", "parent_id": "34031", "post_type": "answer", "score": 0 } ]
34031
34035
34035
{ "accepted_answer_id": "34043", "answer_count": 1, "body": "いろいろやっても動きませんでしたので、 \n質問させてください。\n\nJavaScriptには慣れていませんので、 \n常識的な変なこと聞いていたら申し訳ないです。\n\nこちらのサイトのReact.jsのサンプルを動かしました。\n\nBackbone.JSからAngular2まで、全9大JavaScriptフレームワークを書き比べた! - paiza開発日誌 \n<http://paiza.hatenablog.com/entry/2015/03/11/Backbone_JS%E3%81%8B%E3%82%89Angular2%E3%81%BE%E3%81%A7%E3%80%81%E5%85%A89%E5%A4%A7JavaScript%E3%83%95%E3%83%AC%E3%83%BC%E3%83%A0%E3%83%AF%E3%83%BC%E3%82%AF%E3%82%92%E6%9B%B8%E3%81%8D%E6%AF%94%E3%81%B9>\n\njsfiddle で掲載されていたものから、HTML全体を取得して \nローカルに保存し動作を確認してから\n\njQueryMobileのデザインを対応させようとして\n\n```\n\n <link rel=\"stylesheet\" href=\"https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css\">\n <script src=\"https://code.jquery.com/jquery-2.1.4.min.js\"></script>\n <script src=\"https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js\"></script>\n \n```\n\nこのように記載ました。\n\nしかし、HTMLが、JavaScriptから出力されるためなのか、 \nJQueryMobileのデザインにはなってくれませんでした。\n\n次のサイトをみると、class定義をすればいいとありましたが、\n\nA Software Engineer Blog: react.jsとjquery mobile \n<http://kentandx.blogspot.jp/2015/07/reactjsjquery-mobile.html>\n\ninput タグのclass定義がわからず、 \njQueryMoblieでは、inputタグは \n`<div class=\"ui-field-contain\">` \nで囲って指定するようですが、 \nReact.js側で、divタグを指定したところで、 \nやはり、JQueryMoblieのデザインにはなりませんでした。\n\n何か、React.jsの出力を、jQueryMobileに対応させる方法など \nありますでしょうか?\n\n一応、試しているソースをのせておきます。 \nよろしくおねがいします。\n\n```\n\n <html><head>\n <meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">\n <link rel=\"stylesheet\" href=\"https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css\">\n <script src=\"https://code.jquery.com/jquery-2.1.4.min.js\"></script>\n <script src=\"https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js\"></script>\n <script type=\"text/javascript\" src=\"http://fb.me/react-with-addons-0.12.0.js\"></script>\n <script type=\"text/javascript\" src=\"http://fb.me/JSXTransformer-0.12.0.js\"></script>\n <script type=\"text/jsx;harmony=true\" language=\"JavaScript 1.7\">\n var MyApp = React.createClass({\n getInitialState: function(){\n return {\n firstName: this.props.firstName,\n lastName: this.props.lastName,\n }\n },\n handleChange: function(){\n var firstName = this.refs.firstName.getDOMNode().value;\n var lastName = this.refs.lastName.getDOMNode().value;\n this.setState({\n firstName: firstName,\n lastName: lastName,\n });\n },\n render: function() {\n var fullName = this.state.firstName + this.state.lastName;\n return (\n <div class=\"ui-field-contain\">\n First name: <input ref=\"firstName\" onChange={this.handleChange} value={this.state.firstName}/><br/>\n Last name: <input ref=\"lastName\" onChange={this.handleChange} value={this.state.lastName}/><br/>\n Full name: {fullName}\n </div>);\n }\n });\n React.render(<MyApp firstName=\"Taro\" lastName=\"Yamada\" />, document.body);\n //]]> \n </script>\n </head>\n <body>\n </body></html>\n \n```", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-15T07:06:39.153", "favorite_count": 0, "id": "34032", "last_activity_date": "2019-09-09T12:59:18.860", "last_edit_date": "2019-09-09T12:59:18.860", "last_editor_user_id": "32986", "owner_user_id": "21047", "post_type": "question", "score": 0, "tags": [ "reactjs", "jquery-mobile" ], "title": "jQueryMobileとReact.jsは組み合わせられませんか?", "view_count": 228 }
[ { "body": "```\n\n render: function() {\n var fullName = this.state.firstName + this.state.lastName;\n return (\n <div className=\"ui-field-contain\">\n First name: <input className=\"name\" ref=\"firstName\" onChange={this.handleChange} value={this.state.firstName}/><br/>\n Last name: <input className=\"name\" ref=\"lastName\" onChange={this.handleChange} value={this.state.lastName}/><br/>\n Full name: {fullName}\n </div>);\n },\n componentDidMount: function() {\n $(\".name\").textinput().textinput(\"refresh\");\n }\n \n```\n\njQueryMobile は動的に生成した要素に適用したい場合 refresh しなければなりませんので、componentDidMount() 内で\nrefresh させれば期待する動きになると思います。 \nまた React.jsのJSXでは class は className で指定します。", "comment_count": 1, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-15T16:54:03.417", "id": "34043", "last_activity_date": "2017-04-16T12:31:50.700", "last_edit_date": "2017-04-16T12:31:50.700", "last_editor_user_id": "5047", "owner_user_id": "5047", "parent_id": "34032", "post_type": "answer", "score": 1 } ]
34032
34043
34043
{ "accepted_answer_id": null, "answer_count": 1, "body": "素数を使って整数の素因数分解を行うプログラムを考えています。\n\n関数p_flagは、整数I(2<=i<=n)について、iが素数であるとき、配列要素flag[i]に1を代入し、そうでないときに0を代入するプログラムです。素数でないものは、それより小さい素数の整数倍としてふるい落とします。\n\nMain関数では、 \n変数mに2以上の整数を読み込み、その値を小さい素数で順に割っていき、商が1になるまで繰り返します。\n\nこれを実行するとキーボードからmの値を聞かれて入力したところで、プログラムが進まなくなってしまいます。お助けください><\n\n```\n\n #include <stdio.h>\n \n void p_flag(int flag[], int n){\n int i,j;\n for (i =2; i <= n; i++){\n flag[i] = 1;\n printf(\"~~%d~~\",i); \n if(i <= 3){\n for (int k = 2; k <=i-1; k++ ){\n if(flag[k] != 0){\n int check = i % k;\n printf(\"%d\",k); \n if (check == 0){\n flag[i] = 0; \n }\n }\n }\n }\n }\n \n }\n \n int main(void){\n /*void p_flag();*/\n int flag[10000], m, md, i;\n printf(\"integer 2 or above: \\n\");\n scanf(\"%d\", &m);\n \n p_flag(flag, m);\n \n md = m;\n for (i = 2; i < m/*flag[i]の要素数*/;i++){\n if(flag[i] != 0){\n while(m / flag[i] != 1){\n printf(\"%d\",flag[i]);\n md = m / flag[i];\n }\n }\n }\n }\n \n```", "comment_count": 2, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-15T07:30:07.773", "favorite_count": 0, "id": "34033", "last_activity_date": "2017-04-15T15:27:31.573", "last_edit_date": "2017-04-15T15:27:31.573", "last_editor_user_id": "5044", "owner_user_id": "22573", "post_type": "question", "score": 0, "tags": [ "c" ], "title": "素数を使って整数の素因数分解を行うプログラムを考えています。", "view_count": 1919 }
[ { "body": "この箇所で`i`が増加しないのでループが抜けられないように見受けます。\n\n```\n\n while(m / flag[i] != 1){\n printf(\"%d\",flag[i]);\n md = m / flag[i];\n }\n \n```\n\nなお、`flag[i]`が0だと「0除算」で異常終了するので、ロジックを見直す必要もあるかと思います。", "comment_count": 1, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-15T13:13:25.350", "id": "34040", "last_activity_date": "2017-04-15T13:13:25.350", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "20098", "parent_id": "34033", "post_type": "answer", "score": 3 } ]
34033
null
34040
{ "accepted_answer_id": "34069", "answer_count": 2, "body": "下記のコードは、文字列がマウスポインタに追従するものですが、これをトグルボタンを使ってマウスポインタと追従する文字列を切り離したり(off)、再び追従させたり(on)したいのですが、文を組み立てられません。スクリプトの一番下にある \nif (window.addEventListener){} \nelse if (window.attachEvent){}; \nに鍵があるのは何となく分かるのですが、どのように書き加えればいいでしょうか。\n\n```\n\n <!DOCTYPE html>\n <html lang=\"ja\">\n <head>\n <meta http-equiv=\"Content-type\" content=\"text/html; charset=Shift_JIS\">\n <meta http-equiv=\"Content-Script-Type\" content=\"text/javascript\">\n <meta http-equiv=\"Content-Style-Type\" content=\"text/css\">\n <title>文字列の追従(ON⇔OFF)</title>\n \n \n <style type=\"text/css\">\n \n #myText {\n /* Optional - DO NOT SET FONT-SIZE HERE, SET IT IN THE SCRIPT */\n font-style: italic;\n font-weight: bold;\n font-family: 'comic sans ms', verdana, arial;\n color: #ff0000;\n \n position: absolute;top: 0;left: 0;z-index: 3000;cursor: default;}\n #myText div {position: relative;}\n #myText div div {position: absolute;top: 0;left: 0;text-align: center;}\n \n </style>\n \n <script type=\"text/javascript\">\n <!--\n \n ;(function(){\n \n // Your message here (QUOTED STRING)\n var msg = \"文字列の追従(ON⇔OFF)\"; \n var size = 24;\n var circleY = 0.75; \n var circleX = 2;\n var letter_spacing = 5;\n var diameter = 10;\n var rotation = 0.4;\n var speed = 0.3;\n \n \n if (!window.addEventListener && !window.attachEvent || !document.createElement) return;\n \n msg = msg.split('');\n var n = msg.length - 1, a = Math.round(size * diameter * 0.208333), currStep = 20,\n ymouse = a * circleY + 20, xmouse = a * circleX + 20, y = [], x = [], Y = [], X = [],\n o = document.createElement('div'), oi = document.createElement('div'),\n b = document.compatMode && document.compatMode != \"BackCompat\"? document.documentElement : document.body,\n \n mouse = function(e){\n e = e || window.event;\n ymouse = !isNaN(e.pageY)? e.pageY : e.clientY; // y-position\n xmouse = !isNaN(e.pageX)? e.pageX : e.clientX; // x-position\n },\n \n makecircle = function(){ // rotation/positioning\n if(init.nopy){\n o.style.top = (b || document.body).scrollTop + 'px';\n o.style.left = (b || document.body).scrollLeft + 'px';\n };\n currStep -= rotation;\n for (var d, i = n; i > -1; --i){ // makes the circle\n d = document.getElementById('iemsg' + i).style;\n d.top = Math.round(y[i] + a * Math.sin((currStep + i) / letter_spacing) * circleY - 15) + 'px';\n d.left = Math.round(x[i] + a * Math.cos((currStep + i) / letter_spacing) * circleX) + 'px';\n };\n },\n \n drag = function(){ // makes the resistance\n y[0] = Y[0] += (ymouse - Y[0]) * speed;\n x[0] = X[0] += (xmouse - 20 - X[0]) * speed;\n for (var i = n; i > 0; --i){\n y[i] = Y[i] += (y[i-1] - Y[i]) * speed;\n x[i] = X[i] += (x[i-1] - X[i]) * speed;\n };\n makecircle();\n },\n \n init = function(){ // appends message divs, & sets initial values for positioning arrays\n if(!isNaN(window.pageYOffset)){\n ymouse += window.pageYOffset;\n xmouse += window.pageXOffset;\n } else init.nopy = true;\n for (var d, i = n; i > -1; --i){\n d = document.createElement('div'); d.id = 'iemsg' + i;\n d.style.height = d.style.width = a + 'px';\n d.appendChild(document.createTextNode(msg[i]));\n oi.appendChild(d); y[i] = x[i] = Y[i] = X[i] = 0;\n };\n o.appendChild(oi); document.body.appendChild(o);\n setInterval(drag, 25);\n },\n \n ascroll = function(){\n ymouse += window.pageYOffset;\n xmouse += window.pageXOffset;\n window.removeEventListener('scroll', ascroll, false);\n };\n \n o.id = 'myText'; o.style.fontSize = size + 'px';\n \n if (window.addEventListener){\n window.addEventListener('load', init, false);\n document.addEventListener('mouseover', mouse, false);\n document.addEventListener('mousemove', mouse, false);\n if (/Apple/.test(navigator.vendor))\n window.addEventListener('scroll', ascroll, false);\n }\n else if (window.attachEvent){\n window.attachEvent('onload', init);\n document.attachEvent('onmousemove', mouse);\n };\n \n })();\n // -->\n </script>\n \n \n </head>\n <body bgcolor=\"#ccffff\">\n \n </body>\n </html>\n \n```", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-15T09:29:33.100", "favorite_count": 0, "id": "34036", "last_activity_date": "2017-04-27T09:15:22.543", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "20431", "post_type": "question", "score": -1, "tags": [ "javascript" ], "title": "トグルボタンを使って、マウスポインタと追従する文字列を制御するには", "view_count": 230 }
[ { "body": "init\n内でsetIntervalを呼び出してdragを繰り返し行うようになっているので、これに変数を付けてやりclearIntervalで止めてやればいいと思います。以下サンプルになります。\n\n```\n\n <!DOCTYPE html>\n <html lang=\"ja\">\n <head>\n <meta http-equiv=\"Content-type\" content=\"text/html; charset=Shift_JIS\">\n <meta http-equiv=\"Content-Script-Type\" content=\"text/javascript\">\n <meta http-equiv=\"Content-Style-Type\" content=\"text/css\">\n <title>文字列の追従(ON⇔OFF)</title>\n \n \n <style type=\"text/css\">\n \n #myText {\n /* Optional - DO NOT SET FONT-SIZE HERE, SET IT IN THE SCRIPT */\n font-style: italic;\n font-weight: bold;\n font-family: 'comic sans ms', verdana, arial;\n color: #ff0000;\n \n position: absolute;top: 0;left: 0;z-index: 3000;cursor: default;\n }\n #myText div {position: relative;}\n #myText div div {position: absolute;top: 0;left: 0;text-align: center;}\n \n </style>\n \n <script type=\"text/javascript\">\n <!--\n \n ;(function(){\n \n // Your message here (QUOTED STRING)\n var msg = \"文字列の追従(ON⇔OFF)\";\n var size = 24; // font-size\n var circleY = 0.75;\n var circleX = 2;\n var letter_spacing = 5;\n var diameter = 10;\n var rotation = 0.4;\n var speed = 0.3;\n var timer;\n \n \n if (!window.addEventListener && !window.attachEvent || !document.createElement) return;\n \n msg = msg.split('');\n var n = msg.length - 1, // 文字列長\n a = Math.round(size * diameter * 0.208333), // 文字の入るdivのwidth、heightサイズ\n currStep = 20,\n ymouse = a * circleY + 20,\n xmouse = a * circleX + 20,\n y = [],\n x = [],\n Y = [],\n X = [],\n o = document.createElement('div'),\n oi = document.createElement('div'),\n b = document.compatMode && document.compatMode != \"BackCompat\"? document.documentElement : document.body,\n \n mouse = function(e){\n e = e || window.event;\n ymouse = !isNaN(e.pageY)? e.pageY : e.clientY; // y-position\n xmouse = !isNaN(e.pageX)? e.pageX : e.clientX; // x-position\n },\n \n makecircle = function(){ // rotation/positioning\n if(init.nopy){\n o.style.top = (b || document.body).scrollTop + 'px';\n o.style.left = (b || document.body).scrollLeft + 'px';\n };\n currStep -= rotation;\n for (var d, i = n; i > -1; --i){ // makes the circle\n d = document.getElementById('iemsg' + i).style;\n d.top = Math.round(y[i] + a * Math.sin((currStep + i) / letter_spacing) * circleY - 15) + 'px';\n d.left = Math.round(x[i] + a * Math.cos((currStep + i) / letter_spacing) * circleX) + 'px';\n };\n },\n \n drag = function(){ // makes the resistance\n y[0] = Y[0] += (ymouse - Y[0]) * speed;\n x[0] = X[0] += (xmouse - 20 - X[0]) * speed;\n for (var i = n; i > 0; --i){\n y[i] = Y[i] += (y[i-1] - Y[i]) * speed;\n x[i] = X[i] += (x[i-1] - X[i]) * speed;\n };\n makecircle();\n },\n \n init = function(){ // appends message divs, & sets initial values for positioning arrays\n if(!isNaN(window.pageYOffset)){\n ymouse += window.pageYOffset; //スクロール量を加算\n xmouse += window.pageXOffset;\n } else init.nopy = true;\n for (var d, i = n; i > -1; --i){\n // 文字数に応じてdivを作成\n d = document.createElement('div');\n d.id = 'iemsg' + i;\n d.style.height = d.style.width = a + 'px';\n d.appendChild(document.createTextNode(msg[i]));\n oi.appendChild(d);\n y[i] = x[i] = Y[i] = X[i] = 0;\n };\n o.appendChild(oi);\n document.body.appendChild(o);\n timer = setInterval(drag, 25);\n },\n \n ascroll = function(){\n ymouse += window.pageYOffset;\n xmouse += window.pageXOffset;\n window.removeEventListener('scroll', ascroll, false);\n },\n \n toggle = function(){\n if(timer !== undefined){\n console.log(\"get\")\n clearInterval(timer);\n timer = undefined;\n } else {\n timer = setInterval(drag, 25);\n }\n };\n \n o.id = 'myText';\n o.style.fontSize = size + 'px';\n \n if (window.addEventListener){\n window.addEventListener('load', init, false);\n document.addEventListener('mouseover', mouse, false);\n document.addEventListener('mousemove', mouse, false);\n document.addEventListener(\"click\", toggle, false);\n if (/Apple/.test(navigator.vendor))\n window.addEventListener('scroll', ascroll, false);\n }\n else if (window.attachEvent){\n window.attachEvent('onload', init);\n document.attachEvent('onmousemove', mouse);\n };\n \n })();\n // -->\n </script>\n \n \n </head>\n <body bgcolor=\"#ccffff\">\n \n </body>\n </html>\n \n```", "comment_count": 1, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-17T08:57:15.707", "id": "34069", "last_activity_date": "2017-04-17T08:57:15.707", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "22602", "parent_id": "34036", "post_type": "answer", "score": 0 }, { "body": "クリックが”num == 0”でなければ、\n\n・addEventListener→removeEventListener \n・attachEvent→detachEvent\n\nに変えると、うまく行きます。スクリプトの一番下にある \nif (window.addEventListener){中略 \n}else if (window.attachEvent){中略 \n}; \nの下に、以下を付け加えればいいようです。\n\n```\n\n num = 0;\n function onoff(){\n num ^= 1;\n if(num == 0){document.getElementById(\"myText\").style.color=\"red\";\n if (window.addEventListener){\n window.addEventListener('load', init, false);\n document.addEventListener('mouseover', mouse, false);\n document.addEventListener('mousemove', mouse, false);\n document.addEventListener(\"click\", toggle, false);\n if (/Apple/.test(navigator.vendor))\n window.addEventListener('scroll', ascroll, false);\n }\n else if (window.attachEvent){\n window.attachEvent('onload', init);\n document.attachEvent('onmousemove', mouse);\n }\n }\n else {document.getElementById(\"myText\").style.color=\"blue\";\n if (window.removeEventListener){\n window.removeEventListener('load', init, false);\n document.removeEventListener('mouseover', mouse, false);\n document.removeEventListener('mousemove', mouse, false);\n document.removeEventListener(\"click\", toggle, false);\n if (/Apple/.test(navigator.vendor))\n window.removeEventListener('scroll', ascroll, false);\n }\n else if (window.detachEvent){\n window.detachEvent('onload', init);\n document.detachEvent('onmousemove', mouse);\n }\n }\n }\n window.onclick=onoff;\n \n```", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-27T08:35:43.223", "id": "34318", "last_activity_date": "2017-04-27T09:15:22.543", "last_edit_date": "2017-04-27T09:15:22.543", "last_editor_user_id": "20431", "owner_user_id": "20431", "parent_id": "34036", "post_type": "answer", "score": 0 } ]
34036
34069
34069
{ "accepted_answer_id": null, "answer_count": 1, "body": "CentOS7を使用しています。 \nDockerでZabbix Serverをセットアップしました。\n\n```\n\n sudo docker run -d --restart=always -e LANG=ja_JP.UTF-8 --privileged --name zabb\n ix -h zabbix -p 80:80 -p 10051:10051 docker.io/centos /sbin/init\n \n```\n\nセットアップ後、SNMPを使ったスイッチトラフィックなどは監視できています。\n\nサーバホストにZabbix Agentをインストールしました。Dockerをセットアップした同一サーバです。\n\n構成としては以下の通りです。\n\n> ・ホストサーバ IPアドレス: 192.168.1.130 \n> ・Dockerコンテナ(Agent)の内部IPアドレス: 172.17.0.4\n\nホスト側Agentの/etc/zabbix/zabbix_agentd.confの設定は、\n\n```\n\n Server=192.168.1.130\n \n```\n\nとしています。\n\nServer側ではホスト側Agentを監視するのに\n\n> 192.168.1.130 port 10050\n\nの設定を行っています。\n\nしかし、ホストのAgentは監視できなく、 \n/var/log/zabbix/zabbix_agentd.log では\n\n```\n\n 13935:20170415:153500.521 failed to accept an incoming connection: connection from \"172.17.0.4\" rejected, allowed hosts: \"192.168.1.130\"\n \n```\n\nのエラーが出ています。\n\nどうやらzabbix_agentd.confのServerは許可IPのようですが、この許可IPはdockerを作り直すたびにIPアドレスが変化します。\n\n> [container: Zabbix Server] -> 192.168.1.130:port10050 -> [host: Zabbix\n> Agent] \n> ※ Zabbix AgentへのSource IPは192.168.1.130 or 127.0.01\n\nのイメージを持っていましたが、containerのlocal IPのようです。\n\nこちらcontainerを作り直してもServerやzabbix_agentd.confを変えなくてもいいように設定するにはどうしたらいいのでしょうか?\n\nご存知の方、ご教示お願いします。", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-15T10:45:50.360", "favorite_count": 0, "id": "34037", "last_activity_date": "2018-02-09T09:30:09.537", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "8593", "post_type": "question", "score": 0, "tags": [ "docker", "zabbix" ], "title": "DockerでセットアップしたZabbix ServerからホストにあるZabbix agentの通信設定", "view_count": 2984 }
[ { "body": "私も同じ問題で悩んでいましたが、以下の方法で解決しました。 \n1.Dockerホスト上にブリッジネットワークを作成しする \n2.Zabbix Serverコンテナを起動する時に1で作成したネットワークを利用しかつIPアドレスを固定する \n3./etc/zabbix/zabbix_agentd.confのServerに2で指定したIPアドレスを記述する", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-10-19T05:42:38.647", "id": "38857", "last_activity_date": "2017-10-19T05:42:38.647", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "25829", "parent_id": "34037", "post_type": "answer", "score": 1 } ]
34037
null
38857
{ "accepted_answer_id": null, "answer_count": 1, "body": "androidでMIDIのNote ON、OFFメッセージを受信するアプリを作っています。 \nandroidの端末にはmicro USBを介してMIDIケーブルを接続しています。 \nそこで、\nandroid.media.midiのAPIを利用して開発しているのですが、MIDIケーブルを認識しません。ただ単に、MIDIケーブルを扱うドライバが入っていないからというのが理由なのかもしれないですが、MIDIを扱うアプリをインストールしたころ、そのアプリではMIDIメッセージを受け取ることができました。\n\n具体的な状況は以下の通りです。\n\n・開発環境:Android Studio \n・携帯端末:Zenfone 2 \n・端末の開発者オプション(USB Configration):MIDI \n・Androidのバージョン:6.01(APIレベル23) \n・接続MIDIケーブル:UX16(YAMAHA)\n\nAndroidManifest.xmlに以下を追加しました。\n\n```\n\n <uses-feature android:name=\"android.software.midi\" android:required=\"true\"/>\n \n```\n\nコードの一部示します。\n\n```\n\n MidiManager m = (MidiManager)context.getSystemService(Context.MIDI_SERVICE); \n if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_MIDI)) {\n MidiDeviceInfo[] infos = m.getDevices();\n }\n \n```\n\n現在の状況としてgetDevices()を実行した際ににinfosのlengthが0(infos[0]がnull)になってしまいます。\n\nまた、マニフェストに以下を記述してUSBホストのOTG機能としてアプリを起動した際には \nUSBデバイスとして、ケーブルを認識しました。\n\n```\n\n <uses-feature android:name=\"android.hardware.usb.host\"/> \n \n```\n\nandroid.media.midiの参考サイトです。 \nAndroid Developers: \n<https://developer.android.com/reference/android/media/midi/package-\nsummary.html#get_list_of_already_plugged_in_entities>\n\nMIDIケーブルが認識しない理由、また認識させる方法が分りましたらご教授しただけないでしょうか。よろしくお願いします。", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-15T14:41:41.563", "favorite_count": 0, "id": "34041", "last_activity_date": "2018-01-24T09:30:11.410", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "22579", "post_type": "question", "score": 1, "tags": [ "android", "usb" ], "title": "androidとMIDIケーブルの接続について", "view_count": 2517 }
[ { "body": "私もそれほどAndroid MIDIに詳しい訳ではないのですが…\n\n私が試した限りでは、以下の2製品はAndroid MIDI APIで認識されました。\n\n * Roland UM-ONEmk2 (<https://www.roland.com/jp/products/um-one_mk2/>)\n * Mugig UX-16 (<https://www.amazon.co.jp/Mugig-MIDI%E3%82%B1%E3%83%BC%E3%83%96%E3%83%AB-1-95m-USB-MIDI%E3%82%A4%E3%83%B3%E3%82%BF%E3%83%BC%E3%83%95%E3%82%A7%E3%83%BC%E3%82%B9-UX-16/dp/B074YYV8T5>) ※偶然YAMAHAのものと同じ名前ですが別物です。\n\nAndroidでMIDIデバイスを使用する方法には、Android 6.0で標準で搭載されたMIDI APIのほかに、kshojiさんが提供されているUSB\nMIDI Driver ( <https://github.com/kshoji/USB-MIDI-Driver>\n)があります。感覚的にこちらの方が対応しているデバイスは多く、恐らくインストールしたMIDIアプリはこちらを使っているのではと思われます。\n\n以上、参考までに。", "comment_count": 2, "content_license": "CC BY-SA 3.0", "creation_date": "2017-11-01T11:53:43.680", "id": "39216", "last_activity_date": "2017-11-01T11:53:43.680", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "26012", "parent_id": "34041", "post_type": "answer", "score": 1 } ]
34041
null
39216
{ "accepted_answer_id": "34046", "answer_count": 1, "body": "勝手に表記される無駄なtextを削除したいです。\n\nrailsで開発していたのですが、 \n一切表記していないのに以下のtextがweb上に書き出されます。\n\n```\n\n [#<Post id: 2, title: \"second\", body: \"2bannme\", \n created_at: \"2017-04-15 21:51:00\", \n updated_at: \"2017-04-15 21:51:00\">, \n #<Post id: 1, title: \"firsrt time!!\", body: \"my dairy \", \n created_at: \"2017-04-14 22:22:59\", \n updated_at: \"2017-04-14 22:22:59\">]\n \n```\n\nこれに対して適応されるindex.html.erbファイルはこちらです\n\n```\n\n <%= @posts.each do |post| %>\n <div class=\"post_wrapper\">\n <h2 class= \"title\" ><%= link_to post.title, post %></h2>\n <p class = \"date\" ><%= post.created_at.strftime(\"%B %d, %Y\") %></p>\n </div>\n <% end %>\n \n```\n\napplication.html.erbにはyieldタグしか特に書いてません。\n\n初心者なので、伝わるか分かりませんがもし足りない情報などがあれば教えてください。", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-16T00:38:03.007", "favorite_count": 0, "id": "34045", "last_activity_date": "2017-04-16T01:03:08.113", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "22584", "post_type": "question", "score": 0, "tags": [ "ruby-on-rails", "html" ], "title": "railsで出力されるhtmlに余分なtext", "view_count": 273 }
[ { "body": "`<%= @posts.each do |post| %>` \nの `=` が不要です。", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-16T01:03:08.113", "id": "34046", "last_activity_date": "2017-04-16T01:03:08.113", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "9008", "parent_id": "34045", "post_type": "answer", "score": 1 } ]
34045
34046
34046
{ "accepted_answer_id": null, "answer_count": 2, "body": "JSのクラスについての質問の続きとなります。\n\n>>>\n\n```\n\n class Cat {\n constructor(name) {this.name = name}\n meow() {alert( this.name + 'はミャオと鳴きました' )}\n }\n \n //インスタンス作成\n var clsObj = new Cat(\"my cat\");\n //インスタンス(オブジェクト)の中身を出力\n console.log(clsObj);\n \n```\n\n初心者なのでこの中のどの記述が必須で、 \nまたnameはどれと対になっているかがわかりません。\n\nインスタンスはnew クラス名 となっている所で作成されて変数に作られたインスタンスが代入されるというのは何となく分かったのですが、\n\n```\n\n console.log(clsObj);\n VM793:9\n Cat {name: \"my cat\"}\n \n```\n\nとなるのがいまいちわかりません。\n\n`new Cat(\"my cat\");`は\n\n```\n\n class Cat {\n constructor(name) {this.name = name}\n meow() {alert( this.name + 'はミャオと鳴きました' )}\n }\n \n```\n\nを実行するという事で、 \n引数は\n\n```\n\n constructor(name)\n new Cat(\"my cat\");\n \n```\n\nが対になっているのでnameがmycatに代わるという事でしょうか?\n\n`new Cat(\"my cat\");`が実行された結果がインスタンスという事ですが、 \nmycatがインスタンスなのですか?\n\n大変恐縮ですが、簡単に一連の流れを教えていただければ幸いです。\n\n```\n\n class Cat {\n constructor(name) {this.name = name}\n meow() {alert( this.name + 'はミャオと鳴きました' )}\n }\n \n```\n\nにどう渡されてどのように処理され何がインスタンスとして吐き出されるのでしょうか?\n\n[ES6でclassとは?](https://ja.stackoverflow.com/questions/33972/es6%e3%81%a7class%e3%81%a8%e3%81%af/33973?noredirect=1#comment33579_33973) \nの続き\n\n_____________ \n何度もご対応大変ありがとうございます。\n\n>>> \nClassがInstanceを作るための設計図だということは理解していただいているかと思います。\n\nクッキーの抜き型には、丸や四角、星型などいろいろな形があります。一度クッキーの抜け型を作っておけば、同じ形のクッキーを幾つでも作ることが出来ます。クッキーは実際に食べることが出来ますが、クッキーの型は食べることが出来ません。 \nという例えを見たのですが、 \nどうも型とは関数のように何度も再利用するための式などのまとまりの事で、関数とそっくりなもののようですね。 \nつまり関数の定義とほぼ同じだが、すべてがグローバルになるので、外からでも利用ができる関数の定義がクラスの作成という事になるのですかね?\n\nそしてインスタンス化とはクラスは作成定義しただけでは使えないので、関数の呼び出しのようにクラスのインスタンス化をnewで行い実際にクラスを使えるようにする、呼び出しできるようにする \nという事ですかね?\n\n```\n\n class Cat {\n constructor(name) {this.name = name}\n meow() {alert( this.name + 'はミャオと鳴きました' )}\n }\n \n```\n\nから\n\n```\n\n clsObj = {\n constructor:function(name) {this.name = name},\n meow:function() {alert( this.name + 'はミャオと鳴きました' )}\n };\n \n```\n\nが作成されるという事ですか?\n\n>>> \n上記のような感じですと実行されるときのthisがInstance(Object)を指すイメージが付きますでしょうか?\n\nthisはクラス名ではなくコンストラクタを実行した結果具現化されるインスタンスを示すようですが、 \n具体的にソースのどれでしょうか?\n\n>>> \nそして、このInstanceを作成した際にはコンストラクタが実行されるので下記のように変化します。\n\nconstructor:function(name) {this.name = name}, \nを実行した結果\n\n```\n\n clsObj = {\n name:\"my cat\",\n constructor:function(name) {this.name = name},\n meow:function() {alert( this.name + 'はミャオと鳴きました' )}\n };\n \n```\n\nとなるという事なのは分かったのですが、 \n変更されたのは、name:\"my cat\",だけのようですね。\n\nconstructor:function(name) {this.name = name}は結局 \nnameが引数の無名関数を定義して、内容はインスタンスの中のnameプロパティにnameを代入しているのでしょうか?\n\nまた、name引数はvar name = というローカル変数に何を代入した状態になるのでしょうか? \n実引数があればそれが入るとわかるのですが、これは見当たりません\n\nまたなせ代入作業がされただけで \nname:\"my cat\", \nというプロパティが生成されるのでしょうか?", "comment_count": 4, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-16T08:11:22.810", "favorite_count": 0, "id": "34047", "last_activity_date": "2017-04-17T12:27:19.530", "last_edit_date": "2017-04-17T06:16:24.087", "last_editor_user_id": "20834", "owner_user_id": "20834", "post_type": "question", "score": -2, "tags": [ "javascript" ], "title": "JSのクラスについて", "view_count": 352 }
[ { "body": "まず基本的なことですが、[クラス - JavaScript |\nMDN](https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Classes)より引用します。\n\n> ECMAScript 6 で導入された JavaScript クラスは、JavaScript にすでにあるプロトタイプベース継承の **糖衣構文**\n> です。クラス構文は、新しいオブジェクト指向継承モデルをJavaScript に導入しているわけ **ではありません** 。JavaScript\n> クラスは、オブジェクトを作成して継承を扱うためのシンプルで明確な構文を用意します。\n\n初心者さんということでprototypeがどうだとか言われてももしかしたらご存じないかもしれませんが、元来jsはprototypeベースの継承をコアにした言語で、クラスのようなものを作る際にはprototypeとよばれる特別なプロパティ/オブジェクトを拡張していました。\n\n最も一般的な方法は、[Function](https://developer.mozilla.org/en-\nUS/docs/Web/JavaScript/Reference/Global_Objects/Function)オブジェクトを生成し、そのprototypeを拡張します。このFunctionオブジェクトそれ自身はコンストラクタと呼ばれる特別な関数としても使用でき、これがご質問のコードでいうところの`constructor`に当たります。[\n_new_ キーワード](https://developer.mozilla.org/en-\nUS/docs/Web/JavaScript/Reference/Operators/new)を伴う呼び出しの場合、関数はコンストラクタ呼び出しとなり、\n**自身のprototypeを継承したあらたなオブジェクトを生成し** 、関数内の処理を適用してからこのオブジェクトを返す、という動作になります。\n\n```\n\n // class Cat {\n // constructor(name) {this.name = name}\n const Cat = function (name) {\n // var this = Object.create(Cat.prototype); // new をつけての呼び出しの場合、内部的に実行される\n this.name = name;\n // return this; // new をつけての呼び出しの場合、内部的に実行される\n };\n \n // メンバ変数/メソッドはFunctionオブジェクトのprototypeを拡張します\n // meow() {alert( this.name + 'はミャオと鳴きました' )}\n Cat.prototype.meow = function () {\n alert(this.name + 'はミャオと鳴きました');\n };\n // }\n \n // Functionオブジェクトはそれ自身はふつうの関数です。\n const dummy = {};\n console.assert(Cat.call(dummy, 'my cat') === undefined);\n console.assert(!(dummy instanceof Cat));\n console.assert(Object.getPrototypeOf(dummy) !== Cat.prototype);\n console.assert(dummy.name === 'my cat');\n \n // newキーワードを伴う呼び出しはコンストラクタとして働きます\n // コンストラクタ呼び出しは新たなインスタンスを生成しそれを返します。\n const clsObj = new Cat('your cat');\n console.assert(clsObj instanceof Cat);\n console.assert(Object.getPrototypeOf(clsObj) === Cat.prototype);\n console.assert(clsObj.name === 'your cat');\n \n // clsObjはCatクラスのインスタンス、すなわちCat.prototypeを継承したオブジェクトです\n clsObj.meow();// your catはミャオと鳴きました\n // この呼び出しは次の処理に等価です\n Cat.prototype.meow.call(clsObj);\n \n```\n\nこの内容を簡単に書けるようにしたのがES6のClassということになります。どれが必須、といわれれば必須なものは特にありません。次のコードも完全なクラス定義です。\n\n```\n\n // as Function object\n const myClass = function () {};\n \n // using ES6 class syntax\n class myClass {\n }\n \n```\n\nユーザー定義クラスmyClassはなにもしないコンストラクタを持ち、メンバ変数やメソッドはありません。\n\n少々難しいかもしれませんので、不明な点があればコメントからご指摘ください。", "comment_count": 3, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-16T09:08:03.700", "id": "34049", "last_activity_date": "2017-04-16T09:40:31.073", "last_edit_date": "2017-04-16T09:40:31.073", "last_editor_user_id": null, "owner_user_id": null, "parent_id": "34047", "post_type": "answer", "score": 2 }, { "body": "> `Cat {name: \"my cat\"}`となるのがいまいちわかりません。\n\nClassがInstanceを作るための設計図だということは理解していただいているかと思います。 \nあくまでイメージなので実際の型とは異なりますが`new`を行った場合、 \n設計図を元に下記のようなObjectが作られることを想像してみてください。 \n下記は`var clsObj = new Cat(\"my cat\");`を行ったときの流れのイメージになります。\n\n```\n\n clsObj = {\n constructor:function(name) {this.name = name},\n meow:function() {alert( this.name + 'はミャオと鳴きました' )}\n };\n \n```\n\n上記のような感じですと実行されるときの`this`がInstance(Object)を指すイメージが付きますでしょうか? \nそして、このInstanceを作成した際にはコンストラクタが実行されるので下記のように変化します。\n\n```\n\n clsObj = {\n name:\"my cat\",\n constructor:function(name) {this.name = name},\n meow:function() {alert( this.name + 'はミャオと鳴きました' )}\n };\n \n```\n\n上記のコンストラクタや関数は実際にはprototype宣言なので \nObjectをChromeなどでみても出力はされません。 \nですので、Consoleに出力した際の表示がこうなります。\n\n```\n\n Cat {name: \"my cat\"}\n \n```\n\n上記の応用として、例えばconstructorで引数を2つにして、 \n下記のように実行すると別のネームスペースが作られます。\n\n```\n\n //clsObj = new Cat(\"my cat\", \"owner\");\n clsObj = {\n name:\"my cat\",\n parent:\"owner\",\n constructor:function(name,par) {\n this.name = name;\n this.parent = par;\n },\n meow:function() {alert( this.parent + 'の' + this.name + 'はミャオと鳴きました' )}\n };\n \n```\n\nrio.irikamiさんが回答いただいている内容は、 \nこの`new`されてInstanceが作成されるまでの流れ(内部的な処理の内容)を \nもっと厳密に説明されている内容になります。", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-16T13:33:11.953", "id": "34053", "last_activity_date": "2017-04-17T12:27:19.530", "last_edit_date": "2017-04-17T12:27:19.530", "last_editor_user_id": null, "owner_user_id": null, "parent_id": "34047", "post_type": "answer", "score": 1 } ]
34047
null
34049
{ "accepted_answer_id": "34055", "answer_count": 1, "body": "```\n\n func uploadImageToStorage(image: UIImage) -> String? {\n \n let imageName = NSUUID().uuidString + \".jpg\"\n \n var url: String?\n \n if let complessionImage = UIImageJPEGRepresentation(image, 0.1) {\n \n let ref = FIRStorage.storage().reference().child(\"profileImages\").child(imageName)\n \n ref.put(complessionImage, metadata: nil, completion: { (metadata, error) in\n \n if error != nil {\n return\n }\n \n \n url = metadata?.downloadURL()?.absoluteString\n })\n }\n return url\n }\n \n```\n\nこれを実行するとref.putの中ではちゃんと変数urlにURLが代入されているのに、returnするときにはnilになっている。 \n変数urlにURLを代入してreturnするにはどうしたらいいのでしょうか?", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-16T14:40:10.057", "favorite_count": 0, "id": "34054", "last_activity_date": "2017-04-16T22:57:37.897", "last_edit_date": "2017-04-16T14:45:22.487", "last_editor_user_id": "22590", "owner_user_id": "22590", "post_type": "question", "score": 0, "tags": [ "ios", "xcode", "swift3", "firebase" ], "title": "FirebaseからStorageに画像をアップロードするときにURLが取得できない", "view_count": 507 }
[ { "body": "あなたが使用している`put(_:metadata:completion:)`は非同期処理であり、その`completion:`パラメータに渡したクロージャー`{(metadata,\nerror) in ... }`は、処理の完了後に起動されます。従って、`return\nurl`を実行した時点ではアップロード処理は完了していないはずですから、`uploadImageToStorage(image:)`は常に`nil`を返す、と言うことになります。\n\n「非同期処理の結果を戻り値として返したい」などのキーワードで検索すれば、様々な記事が見つかるかと思います。探し方によっては「一応動いているように見えるかもしれないが、酷いコード」が上位にヒットすることもあるので注意しないといけませんが、一番確実かつ一般的なのは、完了ハンドラーパターンにすることでしょう。\n\nメソッドに完了ハンドラー引数をもたせ、メソッドそのものからは戻り値を返さないようにします:\n\n```\n\n func uploadImageToStorageAsync(_ image: UIImage, completion: @escaping (String?, Error?)->Void) {\n \n let imageName = UUID().uuidString + \".jpg\"\n \n if let complessionImage = UIImageJPEGRepresentation(image, 0.1) {\n \n let ref = FIRStorage.storage().reference().child(\"profileImages\").child(imageName)\n \n ref.put(complessionImage, metadata: nil, completion: { (metadata, error) in\n \n if error != nil {\n completion(nil, error)\n }\n \n \n let urlString = metadata?.downloadURL()?.absoluteString\n completion(urlString, nil)\n })\n }\n }\n \n```\n\n使う場合は、こんな風に呼び出します。\n\n```\n\n uploadImageToStorageAsync(anImage) {urlString, _ in\n //`urlString`を使用した処理\n //...\n }\n \n```\n\n慣れるまでは少しわかりにくいかもしれませんが、非常によく使われているパターンなので、慣れてくればこの方が普通に感じられるようになるかと思います。\n\n(こちらでFirebaseの動作確認ができる環境までは作れていないので、コードについては若干修正していただく必要があるかもしれませんが、考え方は上記の形で問題ないはずです。)", "comment_count": 1, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-16T22:57:37.897", "id": "34055", "last_activity_date": "2017-04-16T22:57:37.897", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "13972", "parent_id": "34054", "post_type": "answer", "score": 0 } ]
34054
34055
34055
{ "accepted_answer_id": null, "answer_count": 1, "body": "Javascriptでどこでエラーが出ているのか、わからないので、try catchを実装したいと思っています。\n\nざっくりでいいので簡単なtry catchを教えていただけると助かります。 \n宜しくお願いします。", "comment_count": 3, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-17T00:37:53.877", "favorite_count": 0, "id": "34056", "last_activity_date": "2017-07-07T20:35:09.323", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "22593", "post_type": "question", "score": -3, "tags": [ "javascript" ], "title": "JavaScriptのtry catch", "view_count": 251 }
[ { "body": "ひとまず簡単には、\n\n```\n\n try {\n /* ここにコード全体 */\n } catch (e) {\n console.error(e);\n }\n \n```\n\nで良いと思います。つまり、コード全体において最初に出たエラーをcatchして、それをそのままコンソールに出力するということです。\n\nまた単にエラーの場所を探りたいだけで、かつブラウザ上で実行しているのでしたら、ブラウザのツール(たとえばGoogle\nchromeの「開発者ツール」のConsole)を使うと、出ているエラーと、そのエラーが出たファイルおよび行数が分かるはずです。\n\n\\-- [rio.irikamiさん](https://ja.stackoverflow.com/users/15182/rio-\nirikami)の[コメント](https://ja.stackoverflow.com/questions/34056/javascript%E3%81%AEtry-\ncatch#comment33642_34056)より。", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-17T09:29:22.250", "id": "34070", "last_activity_date": "2017-07-07T20:35:09.323", "last_edit_date": "2017-07-07T20:35:09.323", "last_editor_user_id": "19110", "owner_user_id": "19110", "parent_id": "34056", "post_type": "answer", "score": 2 } ]
34056
null
34070
{ "accepted_answer_id": null, "answer_count": 1, "body": "Dev C++で下記のソースコードを実行すると下記のエラーが出ます。 \nこのエラーメッセージを解決する方法を教えてください。\n\n```\n\n 27 11 C:\\Users\\patch\\Documents\\main.cpp [Error] cannot convert 'char**(MYSQL_RES*) {aka char**(st_mysql_res*)}' to 'MYSQL_ROW {aka char**}' in assignment\n 28 C:\\Users\\patch\\Documents\\Makefile.win recipe for target 'main.o' failed\n \n```\n\n`コードをここに入力`\n\n```\n\n #include <stdio.h>\n #include <stdlib.h>\n #include <string.h>\n #include <C:\\Program Files\\MySQL\\MySQL Server 5.7\\include/mysql.h>\n \n int main()\n //int res(const char *s)\n {\n MYSQL *m;\n MYSQL_RES *r;\n MYSQL_ROW w;\n MYSQL_STMT *s;\n MYSQL_BIND par[2];\n MYSQL_BIND res[2];\n char sd[4][60];\n unsigned long sdl[4];\n my_bool nl[4];\n char sql1[]= \"SELECT user, host FROM mysql.user WHERE host LIKE '%localhost%'\";\n char sql2[]= \"SELECT user, host FROM mysql.user WHERE host LIKE ?\";\n \n mysql_real_connect(m,\"localhost\",\"root\",\"\",\"test\",0,NULL,0);\n \n puts(\"Regular Execution\");\n mysql_real_query(m, sql1, strlen(sql1));\n \n r= mysql_store_result(m);\n while (w= mysql_fetch_row)\n {\n printf(\"%s@%s\\n\", w[0], w[1]);\n }\n \n puts(\"Prepared Statement\");\n mysql_stmt_prepare(s, sql2, strlen(sql2));\n // parameter\n par[0].buffer_type= MYSQL_TYPE_STRING;\n par[0].buffer= sd[0];\n par[0].is_null= 0;\n par[0].length= &sdl[0];\n mysql_stmt_bind_param(s,par);\n \n strncpy(sd[0],\"%localhost%\",60);\n sdl[0]= strlen(sd[0]);\n mysql_stmt_execute(s);\n res[0].buffer_type= MYSQL_TYPE_STRING;\n res[0].buffer= sd[1];\n res[0].buffer_length= 60;\n res[0].is_null= &nl[1];\n res[0].length= &sdl[1];\n res[1].buffer_type= MYSQL_TYPE_STRING;\n res[1].buffer= sd[2];\n res[1].buffer_length= 60;\n res[1].is_null= &nl[2];\n res[1].length= &sdl[2];\n mysql_stmt_bind_result(s,res);\n \n while(w= mysql_fetch_row(r))\n {\n printf(\"%s@%s\\n\", sd[1], sd[2]);\n }\n \n mysql_stmt_free_result(s);\n mysql_stmt_close(s);\n mysql_close(m);\n }\n \n```", "comment_count": 2, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-17T02:06:53.973", "favorite_count": 0, "id": "34057", "last_activity_date": "2020-06-03T07:01:00.117", "last_edit_date": "2017-04-17T02:25:31.123", "last_editor_user_id": "3249", "owner_user_id": "22556", "post_type": "question", "score": 0, "tags": [ "mysql", "c", "api" ], "title": "MySQL APIの実行時のエラーに関して", "view_count": 154 }
[ { "body": "プログラム中の\n\n```\n\n while (w= mysql_fetch_row)\n \n```\n\nの部分は\n\n```\n\n while (w= mysql_fetch_row(r))\n \n```\n\nではないかと思います。", "comment_count": 1, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-17T02:30:56.110", "id": "34059", "last_activity_date": "2017-04-17T02:30:56.110", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "3249", "parent_id": "34057", "post_type": "answer", "score": 0 } ]
34057
null
34059
{ "accepted_answer_id": "34063", "answer_count": 2, "body": "Python-FitbitというFitbit\nAPIをPythonから利用するモジュールで、Heroku上のプログラムからOAuth2認証をして、アクセストークン・リフレッシュトークンを取得したい。\n\nPython-Fitbit \n<https://github.com/orcasgit/python-fitbit>\n\n手順はこのサイトを参考にしました。 \n<http://blog.mr-but-dr.xyz/programming/fitbit-python-heartrate-howto/>\n\nローカルでhttp://127.0.0.1:8080をコールバックURLに指定しプログラムを実行すると、ブラウザが開き認証に成功するのですが、Heroku上でhttps://appname.herokuapp.com:443/をコールバックURLに指定し実行すると、認証に失敗します。\n\nHerokuにおけるhttp://127.0.0.1:8080が何にあたるのかを教えてください。 \nポート番号を8080や5000に変えてみましたが、同じエラーが発生しました。\n\ngather_keys_oauth2.py\n\n```\n\n import cherrypy\n cherrypy.config.update({'server.socket_host':'appname.herokuapp.com','server.socket_port':443})\n \n def __init__(self, client_id, client_secret,\n redirect_uri='https://appname.herokuapp.com:443'):\n \n```\n\nエラーメッセージ\n\n```\n\n raise socket.error(msg)\n OSError: No socket could be created -- (('IPアドレス', 443): [Errno 49] Can't assign requested address)\n \n```\n\nエラーメッセージ2\n\n```\n\n [17/Apr/2017:14:01:15] ENGINE Error in 'start' listener <bound method Server.start of <cherrypy._cpserver.Server object at 0x7f33e57b12e8>>\n Traceback (most recent call last):\n File \"/app/.heroku/python/lib/python3.6/site-packages/cherrypy/process/wspbus.py\", line 215, in publish\n output.append(listener(*args, **kwargs))\n File \"/app/.heroku/python/lib/python3.6/site-packages/cherrypy/_cpserver.py\", line 168, in start\n super(Server, self).start()\n File \"/app/.heroku/python/lib/python3.6/site-packages/cherrypy/process/servers.py\", line 177, in start\n portend.free(*self.bind_addr, timeout=Timeouts.free)\n File \"/app/.heroku/python/lib/python3.6/site-packages/portend.py\", line 143, in free\n raise Timeout(\"Port {port} not free on {host}.\".format(**locals()))\n portend.Timeout: Port 443 not free on appname.herokuapp.com.\n \n [17/Apr/2017:14:01:15] ENGINE Shutting down due to error in start listener:\n Traceback (most recent call last):\n File \"/app/.heroku/python/lib/python3.6/site-packages/cherrypy/process/wspbus.py\", line 253, in start\n self.publish('start')\n File \"/app/.heroku/python/lib/python3.6/site-packages/cherrypy/process/wspbus.py\", line 233, in publish\n raise exc\n cherrypy.process.wspbus.ChannelFailures: Timeout('Port 443 not free on appname.herokuapp.com.',)\n \n```", "comment_count": 3, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-17T04:44:58.933", "favorite_count": 0, "id": "34060", "last_activity_date": "2017-04-17T07:45:45.603", "last_edit_date": "2017-04-17T07:45:45.603", "last_editor_user_id": "18443", "owner_user_id": "18443", "post_type": "question", "score": 1, "tags": [ "python", "heroku" ], "title": "Herokuにおけるhttp://127.0.0.1:8080とは?", "view_count": 693 }
[ { "body": "リダイレクト先はOAuthのプロバイダにあらかじめ登録したCallback URLです。\n\n> 手順はこのサイトを参考にしました。\n\nそのサイトは、アプリをローカル環境で動かすことを前提にしているようです。 \nこのため、以下のようにかかれています。\n\n> ・Callback URL => <http://127.0.0.1:8080/> ※ここも重要です\n\ndev.fitbit.com に上記のように登録すると、OAuth認証後のリダイレクト先は当然 127.0.0.1:8080 になります。 \nherokuで動作刺せているのであれば、herokuのURL&portをdev.fitbit.comに登録する必要があると思います。", "comment_count": 1, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-17T05:31:05.307", "id": "34062", "last_activity_date": "2017-04-17T05:31:05.307", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "806", "parent_id": "34060", "post_type": "answer", "score": 0 }, { "body": "「認証に失敗します」との事ですが、そもそもサーバの起動に失敗している気がします。\n\nHeroku では使用するポート番号を[環境変数 `$PORT`\nから取得します](https://devcenter.heroku.com/articles/dynos#web-dynos)。 \nどうも デフォルトが`5000`のようで、`int(os.environ.get('PORT', '5000'))`\nのようにしてポートを決定するのが定石のようですね。\n\nListen するインターフェースをとりあえず、`0.0.0.0`(全て)にするなら、設定は下記のようになるかと思います。\n\n```\n\n cherrypy.config.update({\n 'server.socket_host': '0.0.0.0',\n 'server.socket_port': int(os.environ.get('PORT', '5000')),\n })\n \n```\n\nまずはサーバの起動を成功させましょう。", "comment_count": 2, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-17T05:50:19.297", "id": "34063", "last_activity_date": "2017-04-17T05:50:19.297", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "3054", "parent_id": "34060", "post_type": "answer", "score": 1 } ]
34060
34063
34063
{ "accepted_answer_id": "34068", "answer_count": 1, "body": "JSでsetTimeoutでのスライドショーの停止、再生がうまくいきません。\n\n<http://codepen.io/anon/pen/RVNgLr>\n\n```\n\n let iterative = () => {\r\n setTimeout(myChange, 5000); // \r\n }\r\n \r\n const pauseBtn = document.getElementById('js-pause-btn');\r\n pauseBtn.addEventListener('click', () => {\r\n clearTimeout(iterative);\r\n });\r\n \r\n const playBtn = document.getElementById('js-play-btn');\r\n playBtn.addEventListener('click', () => {\r\n iterative();\r\n });\n```\n\n```\n\n <div class=\"slideshow-wrap-selectimg--slidegame\">\r\n <div class=\"slideshow-wrap-selectimg--slidegame__slideimg-wrap\">\r\n <img id=\"idshow1-selectimg--slidegame\" class=\"slideshow-wrap__item1-selectimg--slidegame is-fadeout-selectimg--slidegame\" src=\"img/common-img/corpolate-img.jpg\">\r\n <img id=\"idshow2-selectimg--slidegame\" class=\"slideshow-wrap__item2-selectimg--slidegame is-fadein--slidegame\" src=\"img/common-img/corpolate-img.jpg\">\r\n </div>\r\n <div class=\"slideshow-wrap-selectimg--slidegame__selectimg-wrap\">\r\n <ul>\r\n <li id=\"js-selectimg-list1--slidegame\" class=\"slideshow-wrap-selectimg--slidegame__select-list\">\r\n <img class=\"slideshow-wrap-selectimg--slidegame__item1\" src=\"img/common-img/corpolate-img.jpg\" alt=\"\">\r\n </li>\r\n <li id=\"js-selectimg-list2--slidegame\" class=\"slideshow-wrap-selectimg--slidegame__select-list\">\r\n <img class=\"slideshow-wrap-selectimg--slidegame__item2\" src=\"img/common-img/corpolate-img.jpg\" alt=\"\">\r\n </li>\r\n <li id=\"js-selectimg-list3--slidegame\" class=\"slideshow-wrap-selectimg--slidegame__select-list\">\r\n <img class=\"slideshow-wrap-selectimg--slidegame__item3\" src=\"img/common-img/corpolate-img.jpg\" alt=\"\">\r\n </li>\r\n <li>\r\n <!-- href=\"javascript:void(0)\"-リンク先に飛ばないようにする。 -->\r\n <a id=\"js-pause-btn\" class=\"controle-btn-wrap__link p-ripple-effect--most-top\" href=\"javascript:void(0)\"><i class=\"c-controle-btn-wrap__item--slidegame material-icons u-text-shadow-0dot1rem-0dot1rem-0dot1rem-a0dot4\">pause</i></a>\r\n </li>\r\n <li>\r\n <a id=\"js-play-btn\" class=\"controle-btn-wrap__link p-ripple-effect--most-top\" href=\"javascript:void(0)\"><i class=\"c-controle-btn-wrap__item--slidegame material-icons u-text-shadow-0dot1rem-0dot1rem-0dot1rem-a0dot4\">play_arrow</i></a>\r\n </li>\r\n </ul>\r\n </div>\r\n </div>\n```\n\n問題なく動いているので、停止再生の部分以外は間違えがないと思うのですが、 \n停止再生の部分に問題はありますでしょうか? \n抜粋しておきました。\n\n```\n\n let iterative = ()=> {\n setTimeout(myChange , 5000); // \n }\n \n const pauseBtn = document.getElementById('js-pause-btn');\n pauseBtn.addEventListener('click', ()=> {\n clearTimeout(iterative);\n });\n \n const playBtn = document.getElementById('js-play-btn');\n playBtn.addEventListener('click', ()=> {\n iterative();\n });\n \n```", "comment_count": 16, "content_license": "CC BY-SA 4.0", "creation_date": "2017-04-17T06:29:53.707", "favorite_count": 0, "id": "34064", "last_activity_date": "2019-12-13T20:13:02.683", "last_edit_date": "2019-12-13T20:13:02.683", "last_editor_user_id": "32986", "owner_user_id": "20834", "post_type": "question", "score": -1, "tags": [ "javascript" ], "title": "JSでsetTimeoutでのスライドショーの停止、再生がうまくいきません。", "view_count": 634 }
[ { "body": "[setTimeout](https://developer.mozilla.org/ja/docs/Web/API/WindowTimers/setTimeout)の返値が保存されていません。 \nその値をペアとなる[clearTimeout](https://developer.mozilla.org/ja/docs/Web/API/WindowTimers/clearTimeout)に引数として渡す必要があります。\n\n* * *\n\nサンプルコード \n実際の`myChange`の内容(スライドショーを開始する?)などは私にはわからない(スライドショーの停止としてので、clearTimeoutを使うのが適切であるかどうかなどもわからない)ので \nこの実行動作は単なるサンプルとして適当に作ってます。 \n(またsetTimeout,clearTimeoutの代わりにsetInterval,clearIntervalを使用しています。このサンプルのためにきっかけだけでなく連続動作をになうため) \nPLAYボタンを押すとテキストエリアに`*`を追加表示し続けます。 \nPAUSEボタンを押すと停止します。 \nPLAYボタンを押すと再開します。 \n複数回同じボタンが連続して押される場合のために、 \nPLAYボタンを押したらPLAYボタンがDISABLEされて押せなくなるなどの排他処理が必要です。 \n以下の場合はTimeIDが既に設定されているか(nullでないか)どうかで処理を分けています。\n\n```\n\n let myChange = ()=> {\r\n document.getElementById('disp').value += \"*\";\r\n }\r\n \r\n let TimeID = null;\r\n \r\n let iterative = ()=> {\r\n if(TimeID == null)\r\n TimeID = setInterval(myChange , 500); \r\n }\r\n \r\n const pauseBtn = document.getElementById('js-pause-btn');\r\n pauseBtn.addEventListener('click', ()=> {\r\n if(TimeID != null){\r\n clearInterval(TimeID);\r\n TimeID = null;\r\n }\r\n });\r\n \r\n const playBtn = document.getElementById('js-play-btn');\r\n playBtn.addEventListener('click', ()=> {\r\n iterative();\r\n });\n```\n\n```\n\n <textarea cols=\"20\" rows=10\" id=\"disp\"></textarea><br />\r\n <button type=\"button\" id=\"js-play-btn\">PLAY</button>\r\n <button type=\"button\" id=\"js-pause-btn\">PAUSE</button<br />\n```\n\n* * *\n\nsetTimeout, clearTimeoutを使用する例(ボタンを使用不可にする)\n\n```\n\n let myChange = ()=> {\r\n document.getElementById('disp').value += \"*\";\r\n iterative();//これがあるはず。\r\n }\r\n \r\n let TimeID = null;\r\n \r\n let iterative = ()=> {\r\n TimeID = setTimeout(myChange , 500); \r\n }\r\n \r\n const pauseBtn = document.getElementById('js-pause-btn');\r\n pauseBtn.addEventListener('click', ()=> {\r\n clearTimeout(TimeID);\r\n playBtn.disabled = false;\r\n });\r\n \r\n const playBtn = document.getElementById('js-play-btn');\r\n playBtn.addEventListener('click', ()=> {\r\n playBtn.disabled = true;\r\n iterative();\r\n });\n```\n\n```\n\n <textarea cols=\"20\" rows=10\" id=\"disp\"></textarea><br />\r\n <button type=\"button\" id=\"js-play-btn\">PLAY</button>\r\n <button type=\"button\" id=\"js-pause-btn\">PAUSE</button<br />\n```", "comment_count": 6, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-17T08:47:43.360", "id": "34068", "last_activity_date": "2017-04-19T15:10:36.573", "last_edit_date": "2017-04-19T15:10:36.573", "last_editor_user_id": "5044", "owner_user_id": "5044", "parent_id": "34064", "post_type": "answer", "score": 3 } ]
34064
34068
34068
{ "accepted_answer_id": null, "answer_count": 1, "body": "Pythonの初心者で、現在は主に言語について学習中です。\n\nPythonの環境を構築するのに「anaconda4.1.1(Python 3.5.2)」を使用しました。 \nPython3.6が出ているとのことで、この際環境について勉強しようと思っているのですが、理解ができません。\n\nまず、次のように、Python3.6の環境を構築しました。\n\n```\n\n c:\\conda create -n py36 python=3.6 anaconda\n -\n # conda environments:\n #\n py36 C:\\Users\\(uname)\\AppData\\Local\\Continuum\\Anaconda3\\envs\\py36\n root * C:\\Users\\(uname)\\AppData\\Local\\Continuum\\Anaconda3\n \n```\n\n質問です。\n\n1.「activate py36」で、仮想環境を切り替えられるらしいのですが、できません。 \n切り替え方法を教えてください。 \n※メインシェルは「powershell」を使用しています。 \n※シェルをコマンドプロンプトを使用した時には、切り替えられました。\n\n2.コマンドプロンプトで切り替えることができましたが、 \n「(py36)c:>」とプロンプトが変わりました。(py36)が表示されている間は、python3.6の \n仮想環境になることは推測できますが、デフォルトをPython3.6にすることは可能でしょうか? \n例えばrootのバージョンを3.6にアップデートにしてから、 \n3.5.2を新しく構築するものなのでしょうか?\n\n3.仮想環境を切り替えるでネットで調べていたのですが、「virtualenv」というものも \nあるらしいのですが、activeateコマンドとどう違うのでしょうか。", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-17T07:21:32.610", "favorite_count": 0, "id": "34066", "last_activity_date": "2018-05-12T03:56:06.420", "last_edit_date": "2018-03-28T07:51:22.887", "last_editor_user_id": "19110", "owner_user_id": "11148", "post_type": "question", "score": 1, "tags": [ "python", "python3", "anaconda" ], "title": "python仮想環境の切り替え", "view_count": 2055 }
[ { "body": "## 1\\. Powershell で activate する方法\n\nPowershell で Anaconda の仮想環境を切り替えられないのは既知の問題です。[この\nissue](https://github.com/conda/conda/issues/626) に情報が集約されています。\n\n2018年3月現在解決されておらず、以下のワークアラウンドが知られています。\n\n### 方法1\n\n[pscondaenvs](https://anaconda.org/pscondaenvs/pscondaenvs) を使う。\n\n```\n\n conda install -n root -c pscondaenvs pscondaenvs\n \n```\n\n### 方法2\n\nPowershell の中で `cmd` を起動し、`activate` してから Powershell に戻る。\n\n## 2\\. デフォルトの設定を変えるには\n\n> (デフォルトをPython3.6にするには) rootのバージョンを3.6にアップデートにしてから、3.5.2を新しく構築するものなのでしょうか?\n\nはい。仮想環境は一時的な環境変更のために使うものなので、デフォルトを 3.6\nにしたいのであればデフォルトの環境においてアップデートすれば良いです。このときに今のデフォルト環境を失いたくないのであれば、仮想環境をコピーする\n(clone する) ことが[できます](https://conda.io/docs/user-guide/tasks/manage-\nenvironments.html#cloning-an-environment)。\n\nAnaconda の仮想環境についての詳細は、[公式ドキュメント](https://conda.io/docs/user-\nguide/tasks/manage-environments.html)をご参照下さい。\n\n## 3\\. Anaconda の「環境」と virtualenv の違い\n\n大雑把な説明ですが、conda コマンドは virtualenv コマンドと pip コマンドを統合したものです。Anaconda\n公式ドキュメントの[こちら](https://conda.io/docs/commands.html#conda-vs-pip-vs-virtualenv-\ncommands)に比較があるのですが、virtualenv 単体では仮想環境の中でパッケージをインストールすることができません (pip\nを使います)。また、そもそも Anaconda Cloud のパッケージを使うには conda コマンドを使うことになります。\n\nPython の仮想環境ツールは他に pyenv というのもあります。本家 Stack Overflow\nに三者を比較する投稿がいくつかあるので、ご覧ください。\n\n * [What is the difference between pyenv, virtualenv, anaconda?](https://stackoverflow.com/q/38217545/5989200)\n * [Does Conda replace the need for virtualenv?](https://stackoverflow.com/q/34398676/5989200)\n * [What is the relationship between virtualenv and pyenv?](https://stackoverflow.com/q/29950300/5989200)", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2018-03-28T08:25:25.087", "id": "42706", "last_activity_date": "2018-03-28T08:25:25.087", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "19110", "parent_id": "34066", "post_type": "answer", "score": 1 } ]
34066
null
42706
{ "accepted_answer_id": null, "answer_count": 0, "body": "Python-FitbitというFitbit\nAPIをPythonから利用するモジュールを用い、Heroku上のプログラムからOAuth2認証をして、アクセストークン・リフレッシュトークンを取得したい。\n\nPython-Fitbit \n<https://github.com/orcasgit/python-fitbit>\n\n手順はこのサイトを参考にしました。 \n<http://blog.mr-but-dr.xyz/programming/fitbit-python-heartrate-howto/>\n\ndev.fitbit.comでhttp://127.0.0.1:8080をコールバックURLに指定し、ローカルでプログラムを実行すると、ブラウザが開いて認証に成功し、次の処理に進むのですが、<https://appname.herokuapp.com/>\nをコールバックURLに指定し、Heroku上でプログラムを実行すると、認証に失敗?し、次の処理に進みません。\n\n'''gather_keys_oauth2.py'''\n\n```\n\n import cherrypy\n cherrypy.config.update({\n 'server.socket_host': '0.0.0.0',\n 'server.socket_port': int(os.environ.get('PORT', '5000')),\n })\n \n def __init__(self, client_id, client_secret,\n redirect_uri='https://appname.herokuapp.com'):\n \n```\n\napp.py\n\n```\n\n server = gather_keys_oauth2.OAuth2Server(client_id, client_secret)\n server.browser_authorize()\n \n```\n\nコンソールのメッセージ(Heroku上での実行。このメッセージの後、次の処理に移らない)\n\n```\n\n [17/Apr/2017:16:44:13] ENGINE Listening for SIGTERM.\n [17/Apr/2017:16:44:13] ENGINE Listening for SIGHUP.\n [17/Apr/2017:16:44:13] ENGINE Listening for SIGUSR1.\n [17/Apr/2017:16:44:13] ENGINE Bus STARTING\n CherryPy Checker:\n The Application mounted at '' has an empty config.\n \n [17/Apr/2017:16:44:13] ENGINE Started monitor thread '_TimeoutMonitor'.\n [17/Apr/2017:16:44:13] ENGINE Started monitor thread 'Autoreloader'.\n [17/Apr/2017:16:44:13] ENGINE Serving on http://0.0.0.0:28452\n [17/Apr/2017:16:44:13] ENGINE Bus STARTED\n \n```\n\nコンソールのメッセージ(ローカルでの実行。この後、次の処理に進む)\n\n```\n\n [17/Apr/2017:12:18:52] ENGINE Listening for SIGTERM.\n [17/Apr/2017:12:18:52] ENGINE Listening for SIGUSR1.\n [17/Apr/2017:12:18:52] ENGINE Listening for SIGHUP.\n [17/Apr/2017:12:18:52] ENGINE Bus STARTING\n CherryPy Checker:\n The Application mounted at '' has an empty config.\n \n [17/Apr/2017:12:18:52] ENGINE Started monitor thread 'Autoreloader'.\n [17/Apr/2017:12:18:52] ENGINE Started monitor thread '_TimeoutMonitor'.\n [17/Apr/2017:12:18:52] ENGINE Serving on http://127.0.0.1:8080\n [17/Apr/2017:12:18:52] ENGINE Bus STARTED\n 127.0.0.1 - - [17/Apr/2017:12:18:55] \"GET /?code=認証コード HTTP/1.1\" 200 122 \"\" \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_4) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.1 Safari/603.1.30\"\n 127.0.0.1 - - [17/Apr/2017:12:18:55] \"GET /apple-touch-icon-precomposed.png HTTP/1.1\" 404 1385 \"\" \"Safari/12603.1.30.0.34 CFNetwork/811.4.18 Darwin/16.5.0 (x86_64)\"\n 127.0.0.1 - - [17/Apr/2017:12:18:55] \"GET /apple-touch-icon.png HTTP/1.1\" 404 1361 \"\" \"Safari/12603.1.30.0.34 CFNetwork/811.4.18 Darwin/16.5.0 (x86_64)\"\n [17/Apr/2017:12:18:56] ENGINE Bus STOPPING\n [17/Apr/2017:12:19:01] ENGINE HTTP Server cherrypy._cpwsgi_server.CPWSGIServer(('127.0.0.1', 8080)) shut down\n [17/Apr/2017:12:19:01] ENGINE Stopped thread '_TimeoutMonitor'.\n [17/Apr/2017:12:19:01] ENGINE Stopped thread 'Autoreloader'.\n [17/Apr/2017:12:19:01] ENGINE Bus STOPPED\n [17/Apr/2017:12:19:01] ENGINE Bus EXITING\n [17/Apr/2017:12:19:01] ENGINE Bus EXITED\n [17/Apr/2017:12:19:01] ENGINE Waiting for child threads to terminate...\n \n```", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-17T07:53:57.233", "favorite_count": 0, "id": "34067", "last_activity_date": "2017-04-17T07:53:57.233", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "18443", "post_type": "question", "score": 1, "tags": [ "python", "heroku", "oauth" ], "title": "Heroku上のプログラムからのOAuth2認証", "view_count": 205 }
[]
34067
null
null
{ "accepted_answer_id": "34078", "answer_count": 1, "body": "2017-04-17-20:00\n\nstd::cerrについて調べていたところ以下のようなコード \n(<http://en.cppreference.com/w/cpp/io/cerr>) \nに行き当たったのですが、その挙動が理解できずに悩んでいます。\n\nソースコードは以下です。\n\n```\n\n #include <thread>\n #include <iostream>\n #include <chrono>\n void f()\n {\n std::cout << \"Output from thread...\";\n std::this_thread::sleep_for(std::chrono::seconds(2));\n std::cout << \"...thread calls flush()\" << std::endl;\n }\n \n int main()\n {\n std::thread t1(f);\n std::this_thread::sleep_for(std::chrono::seconds(1));\n std::clog << \"This output from main is not tie()'d to cout\\n\";\n std::cerr << \"This output is tie()'d to cout\\n\";\n t1.join();\n return 0;\n }\n \n```\n\nclang version 3.8.0-2ubuntu4\nでコンパイルし、実際に手元の環境(Ubuntu16.04)で動かしてみた所出力は以下のようになりました。\n\n```\n\n This output from main is not tie()'d to cout\n Output from thread...This output is tie()'d to cout\n ...thread calls flush()\n \n```\n\ncerrはバッファリングを行わず、clogはバッファリングを行うとの認識だったのですが、この出力結果を見るに、clogへの出力はバッファリングされず、mainスレッドの待機命令を無視して真っ先に出力されているように見えます。また、その後に関数f()の一行目が実行され、t1スレッドも待機に入り、先に待機がとけたmainスレッドでcerrにバッファリングされていたメッセージが出力されているように見えます。 \n何故このような挙動になり、僕の理解はどのように間違っているのでしょうか。 \nどなたかご存じの方ご教授願います。\n\n21:20 \n質問投稿の後にも試行錯誤しつつ調べていたのですが、一部解決したのでここに報告させていただきます。 \n\"Output from thread...\"よりも\"Thid output\n...\"のほうが早く出力されていたのはf()内一行目ではflushが起きていないためでした。 \nここでバッファに溜まったテキストはcerrの手前で吐き出されていますが、これはcerrが呼び出し直後にまずcout.flushを呼び出すためのようです。以下参考URL \n(<http://en.cppreference.com/w/cpp/io/cerr>)\n\nただバッファリングされるはずのclogがそのまま出力されているのは未だ解決出来ていません。 \n\"\\n\"による行バッファリングの可能性も指摘していただいたのですが、\"\\n\"を取り除いても出力は行われるのでこれが原因でもないようです。\n\n21:43 \nclogですが、試行錯誤の結果、既にcoutにバッファリングされているデータのflushは行わないものの、clog自体のflushはしているということがわかりました。「clogはバッファリングをする」という文言の意味を取り違えていたようです。問題解決に協力してくださったmetropolisさん、ありがとうございました。\n\n21:55 \nclogについてですが、 \ncppreference.com(信用度が足りないらしくリンクが投稿できないので、サイト名だけで失礼します) \nには勝手にflushされない旨が書いてあるのでやはり不可解な挙動のようです。 \n追加で調べて進展したらまた追記します。\n\n04-18-12:45 \n解決しました。詳しくはベストアンサーをご覧ください。Hidekiさんありがとうございました。", "comment_count": 12, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-17T10:41:20.867", "favorite_count": 0, "id": "34071", "last_activity_date": "2017-04-18T03:46:05.227", "last_edit_date": "2017-04-18T03:46:05.227", "last_editor_user_id": "22606", "owner_user_id": "22606", "post_type": "question", "score": 2, "tags": [ "c++", "c++11", "stl" ], "title": "std::cerr,std::clogの違いについて", "view_count": 2014 }
[ { "body": "[isocpp.org](https://isocpp.org/) にある C++仕様のドラフト (n4618) を見てみましたが、std::clog\nについて書かれているのは、27.4.2 Narrow stream object の\n\n> ostream cerr; \n> The object cerr controls output to a stream buffer associated with the\n> object stderr, declared in (27.11.1). \n> After the object cerr is initialized, cerr.flags() & unitbuf is nonzero and\n> cerr.tie() returns &cout. Its state is otherwise the same as required for\n> basic_ios::init (27.5.5.2).\n>\n> ostream clog; \n> The object clog controls output to a stream buffer associated with the\n> object stderr, declared in (27.11.1).\n\nと、27.5.3.1.6 Class ios_base::Init の\n\n> Init(); \n> Effects: Constructs an object of class Init. Constructs and initializes the\n> objects cin, cout, cerr, clog, wcin, wcout, wcerr, and wclog if they have\n> not already been constructed and initialized.\n>\n> ~Init(); \n> Effects: Destroys an object of class Init. If there are no other instances\n> of the class still in existence, calls cout.flush(), cerr.flush(),\n> clog.flush(), wcout.flush(), wcerr.flush(), wclog.flush().\n\nくらいで、他には見つかりませんでした。clog のバッファは、いつ flush されるか、どこにも記述がないので、実装依存と解釈するのが正しいと思います。\n\nつまり\n\n * cerr については、少なくとも出力ごとには必ず flush される。\n * clog については、いつ flush されるか、わからない。出力ごとかもしれないし、あとで、まとめてかもしれない。\n\nです。cppreference.com の記述は、ちょっと紛らわしいと思います。", "comment_count": 2, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-17T18:16:58.787", "id": "34078", "last_activity_date": "2017-04-17T18:16:58.787", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "3605", "parent_id": "34071", "post_type": "answer", "score": 3 } ]
34071
34078
34078
{ "accepted_answer_id": null, "answer_count": 1, "body": "Google カレンダーAPI についての質問です。\n\nGoogle カレンダーAPI をphpで取得し、サービスアカウントを使用して予定を書き込みました。\n\n再度、その同じカレンダーIDのカレンダーを読み込むと、サービスアカウントでphpから書き込んだ予定だけ、読み込むことができません。\n\n原因はなにが考えられますか?\n\nもしくは、サービスアカウントでphpから書き込まれた予定は、phpでは読み込めない仕様なのでしょうか?\n\n設定情報 \n①google-api-php-client-1-master の autoload.php を使っています。 \n②Google カレンダーV3 です。 \n③カレンダーID では共有しているメールアカウント(サービスアカウント)には「予定の変更権限」を与えてあり、カレンダーに書き込みはできます。 \n④オーナーがGoogleカレンダー上で直接書き込んだ予定は、phpで読み込むことができますが、サービスアカウントでphpで書き込んだ予定は読み込むことができません。\n\n要するに、phpで読み込んで、予定をphpで書き込んだ後、リロードしても予定をphpで書き込んだものだけ読み込めないという現象です。\n\nなお、Google カレンダーを開くと、phpから書き込んだ予定は、しっかりと書きこまれています。\n\nただ、予定の作成者は、オーナーのメールアカウントではなく、サービスアカウントのアドレスで作成されています。\n\nどなたかおわかりになる方はいらっしゃいませんでしょうか?\n\n****追記****\n\n```\n\n //read EVENT\n $json_path = '../json/XXXX-123465789.json';\n $json_string = file_get_contents($json_path, true);\n $json = json_decode($json_string, true);\n $private_key = \"-----BEGIN PRIVATE KEY-----\\nMIIEvQIBADAN・・・・・\";\n $client_email = \"[email protected]\";\n $scopes = array(Google_Service_Calendar::CALENDAR);\n $credentials = new Google_Auth_AssertionCredentials(\n $client_email,\n $scopes,\n $private_key\n );\n \n $client = new Google_Client();\n $client->setApplicationName(\"Google Calendar PHP API\");\n $client->setAssertionCredentials($credentials);\n if ($client->getAuth()->isAccessTokenExpired()) {\n $client->getAuth()->refreshTokenWithAssertion();\n }\n $service = new Google_Service_Calendar($client);\n \n \n $read_start = mktime(0, 0, 0, 4, 10, 2017);\n $read_end = mktime(0, 0, 0, 4, 17, 2017);\n \n $calendarId = '[email protected]';\n $optParams = array(\n 'maxResults' => 99,\n 'orderBy' => 'startTime',\n 'singleEvents' => TRUE,\n 'timeMin' => date('c', $read_start),\n 'timeMax' => date('c', $read_end),\n );\n \n $results = $service->events->listEvents($calendarId, $optParams);\n \n //create EVENT\n \n $json_path = './json/xxx-123456789.json';\n $json_string = file_get_contents($json_path, true);\n $json = json_decode($json_string, true);\n \n $calendarId = '[email protected]';\n $private_key = $json['private_key'];\n $client_email = $json['client_email'];\n $scopes = array(Google_Service_Calendar::CALENDAR);\n $credentials = new Google_Auth_AssertionCredentials(\n $client_email,\n $scopes,\n $private_key\n );\n \n $client = new Google_Client();\n $client->setApplicationName(\"Google Calendar\");\n $client->setAssertionCredentials($credentials);\n if ($client->getAuth()->isAccessTokenExpired()) {\n $client->getAuth()->refreshTokenWithAssertion();\n }\n $service = new Google_Service_Calendar($client);\n \n \n $meeting_end_time = _get_sum_time($set_time,$meeting_time);\n $event = new Google_Service_Calendar_Event(array(\n 'summary' => 'created by service account',\n 'start' => array(\n 'dateTime' => '2017-04-04T00:12:00+09:00',\n 'timeZone' => 'Asia/Tokyo',\n ),\n 'end' => array(\n 'dateTime' => '2017-04-04T00:13:00+09:00',\n 'timeZone' => 'Asia/Tokyo',\n ),\n ));\n $event = $service->events->insert($calendarId, $event);\n \n```\n\nよろしくお願いします。", "comment_count": 5, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-17T11:01:04.933", "favorite_count": 0, "id": "34072", "last_activity_date": "2020-06-24T20:44:30.990", "last_edit_date": "2017-04-17T14:40:06.663", "last_editor_user_id": "22603", "owner_user_id": "22603", "post_type": "question", "score": 1, "tags": [ "google-api" ], "title": "Google カレンダーAPI についての質問です。", "view_count": 878 }
[ { "body": "同じ問題にあたりました。繰り返しイベントを通常イベントにばらして取得するパラメータをtrueにしたら取得できるようになりました。", "comment_count": 0, "content_license": "CC BY-SA 4.0", "creation_date": "2020-06-24T20:44:30.990", "id": "67966", "last_activity_date": "2020-06-24T20:44:30.990", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "40810", "parent_id": "34072", "post_type": "answer", "score": 1 } ]
34072
null
67966
{ "accepted_answer_id": "34156", "answer_count": 1, "body": "記事の一覧からいいねをクリックするとこのようなエラーが出てしまいます。 \n[![画像の説明をここに入力](https://i.stack.imgur.com/DSx2S.png)](https://i.stack.imgur.com/DSx2S.png)\n\n@postには記事のIDが入っていてそれを現在のユーザーのfavoritesにしまうと思うのですが@favoritesというインスタンス変数がいまいちわかりません。このbuildを使うと@favoriteの中に現在のユーザーのお気に入りのポストという感じに作られるイメージなのですが合っているでしょうか? \nこのコードで動くはずなのですがrailsを始めたばかりなのでイメージが薄くエラーが取れないです。助けて下さいお願いします。\n\n追記:\n\nroutes.rb\n\n```\n\n Rails.application.routes.draw do\n get 'users/index'\n \n get 'users/show'\n \n devise_for :users\n resources :users, only: [:index, :show] do\n get :favorites, on: :member\n end\n resources :posts do\n resources :favorites, only: [:create, :destroy]\n end\n root 'posts#index'\n # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html\n end\n \n```\n\nfavorite.rb\n\n```\n\n class Favorite < ApplicationRecord\n class Favorite < ActiveRecord::Base\n belongs_to :user\n belongs_to :post\n end\n #追記2:以下のuserとpostのpresenceをコメントアウトしたらうまく動いたのですが\n #userとpostが空でエラーが出ていたみたいなのですが空でいいのでしょうか?\n validates :user, presence: true\n validates :user_id, uniqueness: { scope: :post_id }\n validates :post, presence: true\n end\n \n```\n\npost.rb\n\n```\n\n class Post < ApplicationRecord\n belongs_to :user\n mount_uploader :image, ImageUploader\n acts_as_ordered_taggable_on :interests\n has_many :favorites, dependent: :destroy\n def favorited_by? user\n favorites.where(user_id: user.id).exists?\n end\n end\n \n```\n\nuser.rb\n\n```\n\n class User < ApplicationRecord\n # Include default devise modules. Others available are:\n # :confirmable, :lockable, :timeoutable and :omniauthable\n devise :database_authenticatable, :registerable,\n :recoverable, :rememberable, :trackable, :validatable\n has_many :posts\n has_many :favorites, dependent: :destroy\n end\n \n```\n\nfavorites_controller.rb \n[![画像の説明をここに入力](https://i.stack.imgur.com/A7n7z.png)](https://i.stack.imgur.com/A7n7z.png)\n\n```\n\n class FavoritesController < ApplicationController\n before_action :authenticate_user!\n \n def create\n @post = Post.find(params[:post_id])\n #追記1:以下のpost:とpost_id:に変更したら上の画像の別のエラーが出ました。\n @favorite = current_user.favorites.build(post_id: @post)\n \n if @favorite.save\n redirect_to posts_url, notice: \"お気に入りに登録しました\"\n else\n redirect_to posts_url, alert: \"この投稿はお気に入りに登録できません\"\n end\n end\n \n def destroy\n @favorite = current_user.favorites.find_by!(post_id: params[:post_id])\n @favorite.destroy\n redirect_to posts_url, notice: \"お気に入りを解除しました\"\n end\n \n end\n \n```\n\nfavoriteテーブル\n\n```\n\n class CreateFavorites < ActiveRecord::Migration[5.0]\n def change\n create_table :favorites do |t|\n t.integer :user_id\n t.integer :post_id\n \n t.timestamps\n end\n end\n end\n \n```", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-17T12:13:20.587", "favorite_count": 0, "id": "34075", "last_activity_date": "2017-04-22T05:15:07.907", "last_edit_date": "2017-04-17T19:18:09.557", "last_editor_user_id": "22565", "owner_user_id": "22565", "post_type": "question", "score": 0, "tags": [ "ruby-on-rails", "ruby" ], "title": "railsでいいね機能を付けたのですがうまくいいねが追加されません。", "view_count": 1489 }
[ { "body": "コードからRuby on Rails 5、Deviseを使っていると推定して回答します。 \nこのような前提条件は基本的に明記してください。\n\n* * *\n\n>\n> @postには記事のIDが入っていてそれを現在のユーザーのfavoritesにしまうと思うのですが@favoritesというインスタンス変数がいまいちわかりません。このbuildを使うと@favoriteの中に現在のユーザーのお気に入りのポストという感じに作られるイメージなのですが合っているでしょうか?\n\n`@post`はPostのidではなくPostオブジェクトが入るコードになっています。 \n`@favorite`の理解は概ね合っています。`current_user.favorites.build(..)`は新たにFavoriteオブジェクトを生成したのち、favorite.userにcurrent_userを結びつけます。\n\n* * *\n\nエラーの「unknown attribute: 'post' for\nFavorite.」はFavoriteにpostという属性が見つからないことを示しています。 \nまた、`@favorite.save`で「undefined method `user` for\n#<Favorite:0xa520ecc>」は`user`メソッドがFavoriteオブジェクトに見当たらないことを示しています。 \nこれらは、FavoriteモデルにPostやUserのリレーションが無いということです。 \nそこで最初に疑うべき箇所はFavoriteモデルのコード app/models/favorite.rb です。\n\n```\n\n class Favorite < ApplicationRecord\n class Favorite < ActiveRecord::Base\n belongs_to :user\n belongs_to :post\n end\n #...\n end\n \n```\n\nこれは明らかにおかしいです。\n\n 1. FavoriteモデルにUserとPostのリレーションを含む別のFavoriteモデルが内包してしまっています。通常はこのような構造にはなりません。(内側のモデルクラスは`Favorite::Favorite`になるため別物です)\n 2. `ActiveRecord::Base`はRuby on Rails 4以下で使われていた`ApplicationRecord`相当(正確には継承元)のクラスです。5以上では使わないでください。\n\n以上を踏まえると次のように修正されます。\n\n```\n\n class Favorite < ApplicationRecord\n belongs_to :user\n belongs_to :post\n \n validates :user, presence: true\n validates :user_id, uniqueness: { scope: :post_id }\n validates :post, presence: true\n end\n \n```", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-20T07:02:12.603", "id": "34156", "last_activity_date": "2017-04-22T05:15:07.907", "last_edit_date": "2017-04-22T05:15:07.907", "last_editor_user_id": "19925", "owner_user_id": "19925", "parent_id": "34075", "post_type": "answer", "score": 2 } ]
34075
34156
34156
{ "accepted_answer_id": "34105", "answer_count": 3, "body": "```\n\n $(document).on('click', function() {\n $('body').append('<div class=\"t\"></div>');\n });\n // あとから文字列をセットしたい\n $('.t').html('set');\n \n```\n\nこのままだとsetというテキストはセットされません。どうすれば、あとから文字列をセットすることができるでしょうか?", "comment_count": 2, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-17T14:18:08.063", "favorite_count": 0, "id": "34077", "last_activity_date": "2017-08-30T13:13:12.350", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "19687", "post_type": "question", "score": 0, "tags": [ "javascript", "jquery" ], "title": "jQueryでクリックして追加された要素にテキストをセットしたい", "view_count": 486 }
[ { "body": "```\n\n <script>\n $(document).ready(function(){\n $('.t').append('<p class=\"p\"></p>');\n $('.p').text('set');\n });\n </script>\n \n <body>\n <div class='t'></div>\n </body>\n \n```\n\npタグにtextを付けるのはどうでしょうか。", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-18T01:18:14.583", "id": "34083", "last_activity_date": "2017-04-18T04:14:16.720", "last_edit_date": "2017-04-18T04:14:16.720", "last_editor_user_id": null, "owner_user_id": "22611", "parent_id": "34077", "post_type": "answer", "score": 0 }, { "body": "> どうすれば、あとから文字列をセットすることができるでしょうか?\n\n「後でイベントハンドラ関数の処理を追加したい」の意でしょうか。\n\n```\n\n function handleClick (event) {\r\n var div = $('<div class=\"t\"></div>');\r\n $('body').append(div);\r\n \r\n var endfn = event.data.endfn;\r\n \r\n if (typeof endfn === 'function') {\r\n event.data.div = div;\r\n endfn(event);\r\n }\r\n }\r\n \r\n var data = {};\r\n $(document).on('click', data, handleClick);\r\n \r\n // 後で click ハンドラ関数の処理を追加する\r\n data.endfn = function (event) {\r\n event.data.div.text('set');\r\n };\n```\n\n```\n\n <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"></script>\n```", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-18T12:31:42.340", "id": "34102", "last_activity_date": "2017-04-18T12:31:42.340", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "20262", "parent_id": "34077", "post_type": "answer", "score": 0 }, { "body": "```\n\n $(document).on('click', function() {\n $('body').append('<div class=\"t\">set</div>');\n });\n \n```", "comment_count": 0, "content_license": "CC BY-SA 3.0", "creation_date": "2017-04-18T18:10:08.233", "id": "34105", "last_activity_date": "2017-04-18T18:10:08.233", "last_edit_date": null, "last_editor_user_id": null, "owner_user_id": "2685", "parent_id": "34077", "post_type": "answer", "score": 0 } ]
34077
34105
34083