id
stringlengths
32
32
text
stringlengths
0
895k
name
stringlengths
0
33k
domain
stringlengths
5
44
bucket
stringclasses
19 values
answers
list
d01a921f7a9fbe2a47bdc17df3358794
###  前提・実現したいこと tweepyツイートの検索キーワードでフォローをしたい ###  発生している問題・エラーメッセージ ``` Traceback (most recent call last): raise TweepError(error_msg, resp, api_code=api_error_code) tweepy.error.TweepError: [{'code': 108, 'message': 'Cannot find specified user.'}] ``` ###  該当のソースコード ``` import tweepy import traceback CONSUMER_KEY = 'XXXXXXXXXXXXX' CONSUMER_SECRET = 'XXXXXXXXXXXXXXXXX' ACCESS_TOKEN = 'XXXXXXXXXXXXXXXX' ACCESS_SECRET = 'XXXXXXXXXXXXXXXXX' auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) auth.set_access_token(ACCESS_TOKEN, ACCESS_SECRET) api = tweepy.API(auth) q = "検索文字" count = 10 search_results = api.search(q=q, count=count) for result in search_results: username = result.user._json['screen\_name'] user_id = result.id print(user_id) user = result.user.name print(user) tweet = result.text print(tweet) time = result.created_at print(time) try: api.create_friendship(user_id) print("をFollowしました") except : traceback.print_exc() ``` ###  補足情報(FW/ツールのバージョンなど) Python 3.6.4 tweepy 3.6.0
tweepyでツイート検索キーワードでフォローしたいがエラーで出る =================================
teratail.com
2020.05
[ { "text": "resultの中身を見るとわかると思いますが \n\n`user_id = result.id`ここで代入しているidってtweetのidですよね? \n\n質問者さんが想定されているuser\\_idではないと思います。 \n\n期待している入力が入ってこないので下記エラーが出ているのだと思われます。 \n\n\n\n```\n# エラーは入力で受け取ったユーザIDは見つからなかったということですよね\nTraceback (most recent call last):\n raise TweepError(error_msg, resp, api_code=api_error_code)\ntweepy.error.TweepError: [{'code': 108, 'message': 'Cannot find specified user.'}]\n```\n\n[tweepy doc - api reference](http://docs.tweepy.org/en/v3.5.0/api.html) \n\n", "name": "", "is_accepted": true } ]
0ff1eafd3055b2f48bd7335d98c9c353
こんにちは。  Windows10でアプリケーションを開発しています。  Visual Studio 2015 Communityを使っています。  ### 前提・実現したいこと C#からChatWorkのTaskに登録をしたいです。 ### 試したこと roomを指定して、 var requestUrl = string.Format("https://api.chatwork.com/v1/rooms/{0}/messages", roomId); でチャットに発言できました。 そこで、messageに期限とchatworkidを加えて、 requestUrl = string.Format("https://api.chatwork.com/v1/rooms/{0}/tasks", roomId); として試しました。 chatworkidは http://help.chatwork.com/hc/ja/articles/203354420-%E3%83%81%E3%83%A3%E3%83%83%E3%83%88%E3%83%AF%E3%83%BC%E3%82%AFID%E3%82%92%E8%A8%AD%E5%AE%9A-%E5%A4%89%E6%9B%B4-%E3%81%99%E3%82%8B で取得しました。 ### 発生している問題・エラーメッセージ 400エラーというerrorで投稿できません。 ### 該当のソースコード ``` public void send2Chatwork(string message) { message = "テスト" + "& limit = 1474627240 & to\_ids = cancat,"; // 各種設定値 const string apiKey = "apikey"; // グループチャットを指定 const string roomId = "roomID"; //文字コードを指定する var encode = Encoding.GetEncoding("UTF-8"); // パラメタのエンコード・構築 var postData = "body=" + Uri.EscapeDataString(message); var postDataBytes = System.Text.Encoding.ASCII.GetBytes(postData); // WebRequest作成 var requestUrl = string.Format("https://api.chatwork.com/v1/rooms/{0}/messages", roomId); requestUrl = string.Format("https://api.chatwork.com/v1/rooms/{0}/tasks", roomId); var request = WebRequest.Create(requestUrl); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; // POSTデータ長を指定 request.ContentLength = postDataBytes.Length; request.Headers.Add(string.Format("X-ChatWorkToken: {0}", apiKey)); // データをPOST送信するためのStreamを取得 var requestStream = request.GetRequestStream(); // 送信するデータを書き込む requestStream.Write(postDataBytes, 0, postDataBytes.Length); requestStream.Close(); // サーバーからの応答を受信する try { var response = request.GetResponse(); // 応答データを受信するためのStreamを取得 var responseStream = response.GetResponseStream(); // 受信して表示 var streamReader = new StreamReader(responseStream, encode); // 結果受信 var responseMessage = streamReader.ReadToEnd(); streamReader.Close(); MessageBox.Show(responseMessage); } catch (WebException webexception) { string error = webexception.Response.ToString(); } catch (Exception exception) { string error = exception.Message; } } ``` ### 補足情報(言語/FW/ツール等のバージョンなど) Microsoft Visual Studio Community 2015  Version 14.0.25424.00 Update 3  Microsoft .NET Framework  Version 4.6.01038  インストールしているバージョン:Community  Visual C# 2015   00322-20000-00000-AA575  Microsoft Visual C# 2015  です。  よろしくお願いします。
C#でChatWorkのtaskに登録したいです ========================
teratail.com
2020.45
[ { "text": "\n```\nvar postDataBytes = System.Text.Encoding.ASCII.GetBytes(postData);\n```\n\n \n\nここをUTF8にしてみてはどうでしょうか?当方、UTF8で送信しています。 \n\n\n\n```\nvar postDataBytes = Encoding.GetEncoding(\"utf-8\").GetBytes(postData);\n```\n", "name": "", "is_accepted": true }, { "text": "\n```\nmessage = \"テスト\" + \"& limit = 1474627240 & to\\_ids = cancat,\";\n```\n\n \n\n上記の「to\\_ids 」の値ですが、ChatworkIDではなくWEB画面のTOを押したときに表示されるIDです。 \n\n\n\n```\n[To:XXXXXX] 〇〇 〇〇さん\n```\n\n \n\n上記の「XXXXXX」です。 \n\n", "name": "", "is_accepted": false } ]
7458c7a8b3fc98c514b4c766c033c04c
Apacheから移行してきたばかりで、openldapとmod\_auto\_ldapに基づいた認証をすべてNginxに移動したいのですが可能でしょうか?
NginxはLDAP認証の対応について ===================
teratail.com
2021.10
[ { "text": "NginxではLDAPは使えません。\n \nサードパーティのスクリプトを付けたxsendfileを使ってLDAP認証を処理する必要があります。\n \n", "name": "", "is_accepted": true } ]
929b86a9dd66ef3896449b718f82aa24
初めまして、gasで今日の日付、1ヶ月後の日付を2020/7/05 という形で取得したいと考えております。(時間は00:00:00) なので ``` function doPost(e) { //1ヶ月後の日付を取得 var now =new Date(); var nextMonth =now.setMonth(now.getMonth() + 1); console.log(nextMonth); //年月日を代入 var today = new Date(); var todayDate = Utilities.formatDate(today, "Asia/Tokyo", "yyyy/mm/dd"); console.info(todayDate); ``` と記述しました。以前はこれでうまくいっていたはずなのですが別の場所を触ってもう一度テストしたらなぜかうまく行かなくなりました。 nextMonthの値は1596609818288のような数字の羅列 todayDateの値は2020/43/05のように年と日付だけ合っている状態です また、 nowの値はなぜかWed Aug 05 2020 15:25:46 GMT+0900 (日本標準時) todayの値はSun Jul 05 2020 15:25:46 GMT+0900 (日本標準時) でしたなぜでしょうか? 変
gasで日付を取得するとおかしな日付になる =====================
teratail.com
2020.40
[ { "text": "`now`に`setMonth`すると、`now`の月の値が更新されます。このときの返り値(ミリ秒単位の数値)は、今回は必要ないので捨てます。更新された`now`を文字列形式にして表示するには`Utilities.formatDate`を使います。 \n\n\n月の指定は「MM」なので、それも修正します。 \n\n\n\n```\nfunction doPost(e) {\n //1ヶ月後の日付を取得\n var now = new Date();\n now.setMonth(now.getMonth() + 1);\n console.log(\"nextMonth: \" + Utilities.formatDate(now, \"Asia/Tokyo\", \"yyyy/MM/dd\"));\n //年月日を代入\n var today = new Date();\n var todayDate = Utilities.formatDate(today, \"Asia/Tokyo\", \"yyyy/MM/dd\");\n console.log(\"todayDate: \" + todayDate); \n}\n```\n", "name": "", "is_accepted": true } ]
b86d032ac7915039e075d17713cdc887
### 前提・実現したいこと 以下のjsonをローカルストレージに登録し、別コンポーネントで読み込んだ時に以下のようなエラーが発生します。 改善点がわかる方がいましたらコメントお願いします。 ``` //Jsonの中身 {Time: new Date()} ``` ### 発生している問題・エラーメッセージ ``` Uncaught TypeError: Cannot read property 'getFullYear' of undefined ``` ``` Uncaught TypeError: Date.parse(...).getFullYear is not a function ``` ### 該当のソースコード objにはローカルストレージの値を取得できていることは確認済です。 ``` {Date.parse(obj['Time']).getFullYear() + "年"} ```
[React]ローカルストレージのDateを読み込むとエラー ==============================
teratail.com
2020.34
[ { "text": "\n```\n//Jsonの中身\n{Time: new Date()}\n```\n\nJSONへ`Date`は格納できません。**文字列**になっています。\n\n", "name": "", "is_accepted": true } ]
12f9bf00ff1d588feeeb867fa0301c13
###  経緯・やりたい事 * gulpでjsファイルの`console.log(***)`を削除したく、`gulp-strip-debug`を使うことにした。 * しかし、実行すると`console.log(***)`が`void 0`に置き換わっている。 * 単純に`console.log(***)`を削除するにはどうしたらよいか。 ###  コード ``` var gulp = require('gulp'); var webserver = require('gulp-webserver'); var plumber = require('gulp-plumber'); var stripDebug = require('gulp-strip-debug'); var jshint = require('gulp-jshint'); var paths = { dist: './dist', src: './src' }; ~中略~ gulp.task('js', function() { gulp.src(paths.src + '/js/*.js') .pipe(plumber()) .pipe(jshint('.jshintrc')) .pipe(jshint.reporter('jshint-stylish')) .pipe(jshint.reporter('fail')) .pipe(stripDebug()) .pipe(gulp.dest(paths.dist + '/js')); }); ~後略~ ``` 以上になります。 よろしくお願い致します。 --- ###  追記 * `gulp-strip-debug`後に、`gulp-uglify`でjsをuglifyすると、`void 0`部分は削除される様子。
jsファイルのcosoleをgulp-strip-debugで削除しようとすると、void 0に置き換わる。 ======================================================
teratail.com
2021.25
[ { "text": "https://github.com/sindresorhus/gulp-strip-debug/issues/2\n\n\n以前は`console`を削除していたが、`void 0`へ置き換えをしたのこと。また、\n\n\n\n> \n> Uglify is able to remove it since knows about all edge cases and how to handle them.\n> \n> \n> \n\n\nとのこと。 \n\ngulp-uglifyで削除確認済。\n\n\n\n\n---\n\n\n本件、解決済とさせて頂きます。\n\n", "name": "", "is_accepted": true } ]
e3273ca37acef55124488c185eb013de
Go言語でコマンドを実行できるプログラムを作りたいと思っています。 どんなコードを書けばできますでしょうか? どなたかサンプルコードあれば教えていただけますか? 宜しくお願いします。
Go コマンドを実行してくれるプログラムを作りたい =========================
teratail.com
2021.10
[ { "text": "例えばlsコマンドを実行するプログラムだと次のようになります。\n \n\n \n\n```\npackage main\n\nimport {\n    “log”\n    “os/exec”\n}\nfunc main() {\n    out, error := exec.Command(“ls”).Output()\n    \n    if error != nil {\n        log.Printf(“エラー : %s”, error)\n        return\n    }\n    log.Print(“%s”, out)\n}\n```\nこのような感じです。 \n", "name": "", "is_accepted": true } ]
f70de009385473b7feedd6239b065212
お世話になります。 CentOS-apacne製のオリジンサーバーを作成しました。 便宜上、このサーバーのURLは下記の通りとさせて頂きます。 http://test.nic.jp:8888/top/css/top.css ポート番号8888は、サーバー側で80にポートフォワードしています。 このサーバーにブラウザでアクセスするとタイムアウトエラーとなります。 アクセスログへの出力もありません。 しかし、APサーバーにログインしたコンソールから、curlコマンドでアクセスすると 参照先のファイルの内容が表示され、アクセスログにも出力されます。 curlで得た、HTTPレスポンスヘッダの情報は下記の通りです。 ``` # curl -vI http://test.nic.jp:8888/top/css/top.css * About to connect() to test.nic.jp port 8888 (#0) * Trying xxx.xxx.xx.xxx... connected * Connected to test.nic.jp (xxx.xxx.xx.xxx) port 8888 (#0) > HEAD /top/css/top.css HTTP/1.1 > User-Agent: curl/7.19.7 (x86\_64-redhat-linux-gnu) libcurl/7.19.7 NSS/3.19.1 Basic ECC zlib/1.2.3 libidn/1.18 libssh2/1.4.2 > Host: test.nic.jp:8888 > Accept: */* > < HTTP/1.1 200 OK HTTP/1.1 200 OK < Date: Tue, 07 May 2019 02:18:41 GMT Date: Tue, 07 May 2019 02:18:41 GMT < Server: Apache Server: Apache < Last-Modified: Tue, 19 Feb 2019 01:56:29 GMT Last-Modified: Tue, 19 Feb 2019 01:56:29 GMT < ETag: "xxxx-xxxxxxxxxxxxx" ETag: "xxxx-xxxxxxxxxxxxx" < Accept-Ranges: bytes Accept-Ranges: bytes < Content-Length: 4454 Content-Length: 4454 < Cache-Control: public,max-age=600 Cache-Control: public,max-age=600 < Connection: close Connection: close < Content-Type: text/css Content-Type: text/css < * Closing connection #0 ``` アクセスログへの出力内容は下記の通りです。 ``` 99.9.9.99 - - [07/May/2019:11:18:41 +0900] "HEAD /top/css/top.css HTTP/1.1" 200 - "-" "curl/7.19.7 (x86\_64-redhat-linux-gnu) libcurl/7.19.7 NSS/3.19.1 Basic ECC zlib/1.2.3 libidn/1.18 libssh2/1.4.2" test.nic.jp:8888 80 970 ``` .htaccessによるUser-Agentでの接続制御は行っておりません。 curlからとブラウザからのアクセス方法の違いにより、ポートフォワードやルート等に違いがあるのかや 問題に対し、何かお気づきの点がございましたら、ご教示頂けないでしょうか。
ブラウザからオリジンサーバーのファイルにアクセスできない ============================
teratail.com
2020.29
[ { "text": "確認が済みました。 \n\n\n原因は、社内LANから外に出る際、port番号でフィルタリングされていたからでした。 \n\n\nですので \n\n社内LAN内にある、私の業務用端末のブラウザからオリジンサーバーにアクセスした際はエラーとなり \n\nVPN内ですが、社内LAN外にあるAPサーバーからcurlでオリジンサーバーにアクセスした際は成功していた。 \n\nということです。 \n\n\n早速社内LANに、port番号8888を許可するようにしたら、無事に \n\n私の業務用端末のブラウザからオリジンサーバーへのアクセスに成功しました。 \n\n\n皆様には、様々な視点でご検討頂き本当にありがとうございました。 \n\n感謝の気持ちを良い評価にて表したいと思います。 \n\nありがとうございました。 \n\n", "name": "", "is_accepted": true } ]
10f17ccc94ed3aa3ac7d1a2bc3972703
FirebaseのFireStoreを利用してデータの保存を行おうとしても上手くいきません。原因がさっぱり分からないまま3日が経過したため、引き続き原因を調査中ですが、こちらでも質問させていただきます。何卒よろしくお願い申し上げます。 Xcode(最新) iOS13.2 言語Swift ``` # Uncomment the next line to define a global platform for your project platform :ios, '13.2' target 'アルキロク開発' do # Comment the next line if you're not using Swift and don't want to use dynamic frameworks use_frameworks! # Pods for アルキロク開発 # add the Firebase pod for Google Analytics pod 'Firebase/Analytics' # add pods for any other desired Firebase products # https://firebase.google.com/docs/ios/setup#available-pods pod 'Firebase/Core' pod 'Firebase/Analytics' pod 'Firebase/Auth' pod 'Firebase/Firestore' target 'アルキロク開発Tests' do inherit! :search\_paths # Pods for testing end target 'アルキロク開発UITests' do inherit! :search\_paths # Pods for testing end end ``` ``` import UIKit import Firebase import FirebaseAuth class RankingViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() var defaultStore : Firestore! defaultStore = Firestore.firestore() defaultStore.collection("Tea").document("Darjeeling").setData([ "ProducingArea": "India", "TeaLeaf": "OP" ]) { err in if let err = err { print("Error writing document: \(err)") } else { print("Document successfully written!") } } } ``` ``` service cloud.firestore { match /databases/{database}/documents { match /{document=**} { allow read, write; } } } ``` **エラー発生条件** FireStoreにデータを送る段階で発生(おそらく) **エラーの内容** Thread 7: EXC\_BREAKPOINT (code=1, subcode=0x1ac8127ec)[![Error画面](https://teratail-v2.storage.googleapis.com/uploads/contributed_images/ebee70c9382abbdb16ec908e7fd1a49d.png)](https://teratail-v2.storage.googleapis.com/uploads/contributed_images/ebee70c9382abbdb16ec908e7fd1a49d.png)
FirebaseのFireStoreについて(Swift) =============================
teratail.com
2021.39
[ { "text": "[ここ](https://github.com/firebase/firebase-ios-sdk/issues/3283)はご覧になりましたか?\n\n", "name": "", "is_accepted": true } ]
a53b654db39f61c968be1cffa766472d
### 前提・実現したいこと MacOSでの画像認識等を行うための環境設定を行う上で、 deelにおける、 エラーを無くしたいです。 ### 発生している問題・エラーメッセージ エラーメッセージ ``` File "tiny.py", line 7, in <module> CNN = Alexnet() NameError: name 'Alexnet' is not defined 追記・・ File "tiny.py", line 4, in <module> from deel.network import * File "/Users/deel/deel/network/\_\_init\_\_.py", line 337, in <module> from deel.network.alexnet import AlexNet File "/Users/deel/deel/network/alexnet.py", line 93 return y.data.shape ^ 追記2 ./getPretrainedModels.sh: line 1: wget: command not found ./getPretrainedModels.sh: line 2: wget: command not found ./getPretrainedModels.sh: line 3: wget: command not found ./getPretrainedModels.sh: line 4: wget: command not found ./getPretrainedModels.sh: line 5: wget: command not found ./getPretrainedModels.sh: line 6: wget: command not found tar: Error opening archive: Failed to open 'googlenet\_places205.tar.gz' mv: rename googlenet_places205/googlelet_places205_train_iter_2400000.caffemodel to ./googlelet_places205_train_iter_2400000.caffemodel: No such file or directory mv: rename googlenet_places205/categoryIndex_places205.csv to ./categoryIndex_places205.csv: No such file or directory### 該当のソースコード ``` python ソースコード ``` 訂正後です。 from deel import * from deel.network import * from deel.commands import * deel = Deel() CNN = AlexNet() CNN.Input("deel.png") CNN.classify() ShowLabels() ### 試したこと chainerのダウングレードを行い、その他にも多くのサイトを調べましたが、Macでの説明はなく、初心者のせいでもあるのだと思いますが、いくら試しても上手くいかないです。 ### 補足情報(FW/ツールのバージョンなど) 清水亮さんの初めてのディープラーニングプログラミングを参考にして作業を進めています。 Macに沿った説明をして頂けたら嬉しいです。
どうしてもエラーが出てしまう。 ===============
teratail.com
2020.45
[ { "text": "githubのソースを見た感じだと`Alexnet()`ではなく`AlexNet()`ではないでしょうか。nが小文字か大文字かの違いです。\n\n", "name": "", "is_accepted": true }, { "text": "\n> \n> ソースコードで書かれていることは全て書籍のものを写したものなのですが、importが足りていないということはあるのでしょうか。 \n> \n> \n> \n\n\n書籍と同じに入力して動作するとは限りません。なぜなら本には誤記などがつきものだからですし、執筆当時とは環境やライブラリなどが更新されてしまっていることもあるからです。 \n\n例えば、「初めてのディープラーニングプログラミング」には正誤表がありますね。作者は神ではありません。人間なのです。間違うこともありえます。 \n\nhttp://gihyo.jp/book/2017/978-4-7741-8534-7/support#supportApology\n\n", "name": "", "is_accepted": false }, { "text": "正直エラーの解決方法はわかりませんでした。すみません。 \n\nですが、質問にあるソースコードをエラーを起こさず実行することができたのでその手順を示したいと思います。 \n\nまず、githubからdeelをクローンしてきます。そして`deel/msic`に移動し、`getPretrainedModels.sh`を実行します。 \n\n\n\n```\nhttps://github.com/uei/deel.git\ncd deel/msic\n./getPretrainedModels.sh\n```\n\n \n\n一つ前の階層に戻り、質問にあるプログラムをファイルに保存します(ここではファイル名をtest.pyとします)。 \n\n\n\n```\ncd ../\n```\n\n \n\n以下を保存 \n\n\n\n```\nfrom deel import *\nfrom deel.network import *\nfrom deel.commands import *\n\ndeel = Deel()\n\nCNN = AlexNet()\n\nCNN.Input(\"deel.png\")\nCNN.classify()\nShowLabels()\n```\n\n \n\nそして`test.py`を実行します。 \n\n\n\n```\npython test.py\n```\n\n \n\nおそらくこれで実行できるのではないかと思います。\n\n", "name": "", "is_accepted": false } ]
be40df48db64ad56764f398333b4d025
下記のサイトを参考に、 ボタンのアニメーションをつけましたが、 右の背景でつけた、矢印画像が、ホバー時に上手く、表示されません。 aタグの中にspanタグをつけ。それに矢印画像を付けるとホバーすると表示されるようになるのですが、 spanタグの場合、ホバーできる領域が狭いのが問題となります。 アニメーションを入れた状態で、矢印画像もホバー時にも表示させたいです。 https://www.nxworld.net/tips/10-css-hover-fill-animation.html ``` <p><a class="button" href="#"><span>Button</span></a></p> ``` ``` .button::before { position: absolute; top: 0; right: 0; bottom: 0; left: 0; z-index: -1; content: ''; background: #fff; transform-origin: right top; transform: scale(0, 1); transition: transform .3s; } .button:hover::before { transform-origin: left top; transform: scale(1, 1); } .button { position: relative; display: inline-block; border: 1px solid #000; padding: 15px 60px 15px 30px; background: #000; background-position-x: right; background-position: 90% 50%; color: #fff; } .button:hover { color: #082242; } .button span{ background: url(../img/btn_icon.png) right no-repeat #082242; } .button span:hover { z-index: 5; color: #000; background: url(../img/02.png) right no-repeat;padding: 0 10px 0 20px; } ```
ボタンのアニメーションをつけるとホバー時に背景画像が表示されない ================================
teratail.com
2021.25
[ { "text": "こういうことでしょうか。 \n\n\n\n```\n/*\n.button span:hover\n ↓ */\n.button:hover span\n```\n", "name": "", "is_accepted": true } ]
a46b45d12eba99910b9748cb7780208c
### 前提・実現したいこと redux-toolkitを利用してstate管理を実装しています。 以下のようにactionの引数を複数にしても受け取れると思うのですが、うまくいきません。 何が原因なのでしょうか。 ご教授お願いします。 参考 <https://redux-toolkit.js.org/usage/usage-guide> ### 発生している問題・エラーメッセージ ``` {type: "members/setHoge", payload: 1}payload: 1type: "members/setHoge"\_\_proto\_\_: Object members.js:55 undefined members.js:56 undefined members.js:57 undefined ``` ### 該当のソースコード ``` dispatch(setHoge(1, 2, 3)); ``` ``` setHoge: (state, action) => { const { a, b, c } = action.payload; console.log(action); //action.payload=1 console.log(a); //undefined console.log(b); //undefined console.log(c); //undefined }, ```
[Redux]actionの引数を複数にできない ========================
teratail.com
2020.40
[ { "text": "\n> \n> 以下のようにactionの引数を複数にしても受け取れると思うのですが \n> \n> \n> \n\n\n受け取れません。複数のプロパティを設定した**オブジェクト**を受け渡しする必要があります。\n\n", "name": "", "is_accepted": true } ]
29fb8d8e997e4c7bdcdbb20af40312b0
今ユーザーが撮った写真を以下のコードでRealmに保存しているのですが、このような形でRealmのデータベースに直接画像を保存するのは果たして正しい方法なのでしょうか?Realmから画像を読み込む際に処理が重くなっているようなので気になりました。他に方法があるとすれば教えていただけると幸いです。検索ワードなどでも良いので教えてください。 ``` class Image: Object { @objc dynamic var imageData:Data? } class ViewController:UIViewController{ /*色々略*/ //撮った写真をここにキープします @IBOutlet var imageView: UIImageView! //保存した後にrealmから呼び出してこっちに表示する(今回はこうしているが本来は別viewのtableViewCellの中のimageViewに返す予定) var copyImageView:UIImageView? //realmに写真をData型で保存する関数 func rgstImage() { let realm = try! Realm() do{ try realm.write { let image = Image() //PNGで保存するとたまに落ちたのでJPEGで保存。これもimageのdataが重いせいな気がしている image.imageData = UIImageJPEGRepresentation(imageView.image!, 1) realm.add(image) } }catch let error{ print(error) } } //realmから写真を呼び戻す関数。tableviewcellのなかのimageに代入するときに使うと重さを感じる。 func roadImage() { let realm = try! Realm() let images = realm.objects(Image.self) let copyImageView.image = UIImage(data: images[0].imageData!) } ```
IPhoneアプリでの画像保存について ===================
teratail.com
2020.34
[ { "text": "使一つの方法として、画像自体はローカルのドキュメントに保存しておき、データベースにはファイル名やパスを保存するという方法があります。 \n\n\n「swift 画像 保存」などと検索するといろんな情報が出てくると思います。\n\n", "name": "", "is_accepted": true } ]
e185df2679cb29510f1178df3fb24422
###  前提・実現したいこと Ruby初心者です。 出力結果を計算して、それをさらに出力したいのですが、上手くいきません。 => 886524 886065 883193 880943 882866 880516 878316 882034 882149 882945 884501 883813 882995 881790 881405 を合計して、平均を算出したいです。 よろしくお願いします。 ###  発生している問題・エラーメッセージ ``` undefined method `sum' for 886524:Fixnum (NoMethodError) ``` ###  該当のソースコード ``` get_candle.each do |data| tp = (data[2]+data[3]+data[4])/3 p tp.sum end #上記の出力結果は p tp とした場合です。 ``` ###  試したこと 色々弄ったのですが、上手くいきません。 ###  補足情報(FW/ツールのバージョンなど)
Ruby で出力結果を合計したい ================
teratail.com
2020.34
[ { "text": "やりたいとかいてあることと、コードの差があり、本当にやりたいことが不明確ですが、 \n\nこんなことでしょうか? \n\n\n\n```\nget_candle = [\n 1, 2, 3, 4, 5,\n 6, 7, 8, 9, 10\n]\n\nget_candle.each_cons(3) do |data|\n puts \"#{data} の平均: #{data.sum / 3}\"\nend\n```\n\n \n\n実行結果 \n\n\n\n```\n[katoy@katoy-MacBook-Pro zzz3]$ ruby ss.rb\n[1, 2, 3] の平均: 2\n[2, 3, 4] の平均: 3\n[3, 4, 5] の平均: 4\n[4, 5, 6] の平均: 5\n[5, 6, 7] の平均: 6\n[6, 7, 8] の平均: 7\n[7, 8, 9] の平均: 8\n[8, 9, 10] の平均: 9\n```\n\n追記: \n\n\n\n> \n> 1、それぞれの配列の2,3,4の平均を算出 \n> \n> 2、その値を合計(上の例だと、8つあるので8つを合計) \n> \n> 3、その値を8で除し、平均を算出 \n> \n> \n> \n\n\nをしたいとのことなので、次のようにしてみました。 \n\n\n\n```\nget_candle = [\n [0, 1, 2, 3, 4, 5, 6],\n [0, 1, 12, 3, 4, 5, 6],\n [0, 1, 22, 3, 4, 5, 6],\n [0, 1, 32, 3, 4, 5, 6],\n [0, 1, 42, 3, 4, 5, 6],\n [0, 1, 52, 3, 4, 5, 6],\n [0, 1, 62, 3, 4, 5, 6],\n [0, 1, 72, 3, 4, 5, 6]\n]\n\naverages = get_candle.map{|data| (data[2] + data[3] + data[4]) / 3}\np averages\np averages.sum / get_candle.size\n```\n\n実行例: \n\n\n\n```\n$ ruby ss.rb\n[3, 6, 9, 13, 16, 19, 23, 26]\n14\n```\n", "name": "", "is_accepted": true } ]
99239bd3b43a6d464e4f98faf775087f
WP\_Queryで取得したクエリを配列に入れてjsonでjsに持って行きたいのですがループの中で呼んだ$postがnullになります。 ``` $slug = $_POST['slug'];   $cat = get_category_by_slug($slug);   $id = $cat->term_id;   $args = array(     'include' => $id   );   $results = array();   $args = array(     'post_type' => "post",     'cat' => $id,     'posts_per_page' => 8,     'order' => 'desc',     'orderby ' => 'modified',   );   $blog_posts = new WP_Query($args);   $count = 0;   while ( $blog_posts->have_posts()) : $blog_posts->the_post();   $hoge = $post->post_content;   $results[$count]["title"] = $post->post_title;   $count++;   endwhile;   wp_reset_postdata();   header('Content-Type: application/json; charset=utf-8');   echo json_encode($results);   die();      ``` 上記がコードになります。 何卒よろしくお願いします。
WP\_Queryで取得したクエリを配列に入れてjsonでjavascriptに渡す ==========================================
teratail.com
2021.17
[ { "text": "自己解決しました。\n \n$postを使わず\n \n\n```\n$results[$count][\"title\"] = $blog_posts->post->post_title;\n```\nで対応しました。\n \n\n \nもし$postが使えなかった理由がわかる方いればご教授していただければ幸いです。\n \n \n", "name": "", "is_accepted": true }, { "text": "ここにあるコードの中では、$postに何かを代入しているコードは見当りませんが?\n \n私の見落しでしょうか... \n", "name": "", "is_accepted": false } ]
5ba6a96ac7901ff043d943a7cbb77485
フロントエンドにロードバランサーを設置して、2系でTomcatを運用しているので、セッションを共有するためDBに保持しようと考えているのですが、大丈夫なのでしょうか。 リアルタイムでの同期はできず、ディレイが発生してしまったりしないでしょうか。
Tomcatのセッションの永続化の方法 ===================
teratail.com
2020.16
[ { "text": "フロントエンドからTomcatへの振り分けは、単純なラウンドロビンでしょうか。\n \n\n \nDBにセッション情報を永続化する機構をTomcatは持っているため、共有は可能ですが、おっしゃるとおりディレイは発生します。\n \n\n \nですので単純なラウンドロビンだとセッションの整合性を保てないです。\n \nスティッキーセッション+ラウンドロビンならば目的を達成できるのではと思います。 \n", "name": "", "is_accepted": true } ]
bca0e05a384004bff411d552544538d3
Advanced Custom Fieldsを使わずに、function.phpのみで、カスタムフィールドの出し分けをしたいです。 例えば、下記のカスタムフィールドを、カテゴリー「book」が選択されている場合のみに表示させるにはどのようにすれば良いでしょうか? ``` // 固定カスタムフィールドボックス function add\_book\_fields() { //add\_meta\_box(表示される入力ボックスのHTMLのID, ラベル, 表示する内容を作成する関数名, 投稿タイプ, 表示方法) //第4引数のpostをpageに変更すれば固定ページにオリジナルカスタムフィールドが表示されます(custom\_post\_typeのslugを指定することも可能)。 //第5引数はnormalの他にsideとadvancedがあります。 add_meta_box( 'book\_setting', '本の情報', 'insert\_book\_fields', 'post', 'normal'); } add_action('admin\_menu', 'add\_book\_fields'); // カスタムフィールドの入力エリア function insert\_book\_fields() { global $post; var_dump(get_the_category()); //下記に管理画面に表示される入力エリアを作ります。「get\_post\_meta()」は現在入力されている値を表示するための記述です。 echo '題名: <input type="text" name="book\_name" value="'.get_post_meta($post->ID, 'book\_name', true).'" size="50" /><br>'; echo '作者: <input type="text" name="book\_author" value="'.get_post_meta($post->ID, 'book\_author', true).'" size="50" /><br>'; echo '価格: <input type="text" name="book\_price" value="'.get_post_meta($post->ID, 'book\_price', true).'" size="50" /> <br>'; if( get_post_meta($post->ID,'book\_label',true) == "is-on" ) { $book_label_check = "checked"; }//チェックされていたらチェックボックスの$book\_label\_checkの場所にcheckedを挿入 echo 'ベストセラーラベル: <input type="checkbox" name="book\_label" value="is-on" '.$book_label_check.' ><br>'; } // カスタムフィールドの値を保存 function save\_book\_fields( $post\_id ) { if(!empty($_POST['book\_name'])){ //題名が入力されている場合 update_post_meta($post_id, 'book\_name', $_POST['book\_name'] ); //値を保存 }else{ //題名未入力の場合 delete_post_meta($post_id, 'book\_name'); //値を削除 } if(!empty($_POST['book\_author'])){ update_post_meta($post_id, 'book\_author', $_POST['book\_author'] ); }else{ delete_post_meta($post_id, 'book\_author'); } if(!empty($_POST['book\_price'])){ update_post_meta($post_id, 'book\_price', $_POST['book\_price'] ); }else{ delete_post_meta($post_id, 'book\_price'); } if(!empty($_POST['book\_label'])){ update_post_meta($post_id, 'book\_label', $_POST['book\_label'] ); }else{ delete_post_meta($post_id, 'book\_label'); } } add_action('save\_post', 'save\_book\_fields'); ```
【wordpress】記事投稿画面でカテゴリーごとにカスタムフィールドを切り替える。 ==========================================
teratail.com
2020.10
[ { "text": "\n> \n> カテゴリー「book」が選択されている場合のみに表示させるには \n> \n> \n> \n\n\nJavaScriptでカテゴリの選択状態を判別して、カスタムフィールドをCSSで表示/非表示するようにすれば出来ます。\n\n", "name": "", "is_accepted": true } ]
80fedb260f9aaa3b30fce2eb9fed73e0
HTTPメソッドのGETとPOSTなのですが、どういう風に 使い分ければいいのでしょうか? どなたか教えていただけないでしょうか?
PHP初心者です。GETとPOSTの使いわけがわかりません。 ==============================
teratail.com
2020.50
[ { "text": "**POST**:ログイン時のユーザID、パスワードなど**他の人に見せたくない情報を扱う**時\n \n    送信したデータで**データベース情報を変更(追加、更新、削除)する**処理があるとき  \n \n**GET** :**他人に見られても、変更されても、問題ない**情報を扱う時(検索時のキーワードとか)\n \n\n \nわたしは、こんなかんじで使い分けてます。\n \nデータの変更が伴う処理をやっているところは、ブックマークされると困るので → POST\n \nページ数とか、検索時のキーワードなどそれほど重要ではないもの → GET\n \n \n", "name": "", "is_accepted": true }, { "text": "**データの取得が目的ならば、GETを使い、**\n \n**データを送信して何か情報を変更させることが目的ならば、POST**\n \nというように使い分ければいいかと思います。\n \n\n \nはじめのうちは、どちらのHTTPメソッドを使えばよいかわからないかと\n \n思いますが、上記に書いたことで使い分けをすればよいと思います。 \n", "name": "", "is_accepted": false } ]
2099e63e214c2378b20644603a872495
上記のようにしたい 入力.htmlでチェック入れ送信→保存.phpでcsvに保存 ### 発生している問題 ``` チェックボックスの入力を保存できない ``` ### 該当のソースコード ``` <html> <head> <title>入力</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> </head> <body> <form method="post" action="hozon.php"> ラジオ1 <input type="radio" name="radio1" value="1">1 <input type="radio" name="radio1" value="2">2 <br>ラジオ2 <input type="radio" name="radio2" value="3">3 <input type="radio" name="radio2" value="4">4 <br>チェック <input type="checkbox" name="check[]" value="5">5 <input type="checkbox" name="check[]" value="6">6 <br><input type="button" onclick="submit();" value="送信"> </form> </body> </html> ``` ``` <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ja"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>保存</title> </head> <body> 保存しました <button type="button" onclick="history.back()">戻る</button> <?php $fp = fopen("sample.csv", "a"); $text_name = $_POST['radio1']; fwrite($fp,"$text\_name,"); $text_name = $_POST['radio2']; fwrite($fp,"$text\_name,"); $text_name = $_POST['check']; fwrite($fp,"$text\_name,\n"); fclose($fp); ?> </body> </html> ```
チェックボックスの状態をcsvに保存したい =====================
teratail.com
2020.45
[ { "text": "checkboxはPHPで受け取ると配列になっているのでは? \n\n\n\n```\nfwrite($fp,\"$text\\_name[0],\\n\");\nfwrite($fp,\"$text\\_name[1],\\n\");\n```\n", "name": "", "is_accepted": true }, { "text": "`var_dump($_POST['check']);`で出力してみると分かりますが、 \n\n入力コントロールのnameを[]で送信した場合は配列として送信されるので、文字列に直したければ[implode()](https://www.php.net/manual/ja/function.implode.php)などで結合してください。\n\n", "name": "", "is_accepted": false }, { "text": "値が送られてこない(null)のときにどうしたいかによります \n\n\n\n```\n<?PHP\n$r1=filter_input(INPUT_POST,'radio1');\n$r2=filter_input(INPUT_POST,'radio2');\n$c=filter_input(INPUT_POST,'check',FILTER_DEFAULT,FILTER_REQUIRE_ARRAY);\nif(is_null($c)) $c=[];\n$res=array_merge([$r1,$r2],$c);\nprint_r($res);\n?>\n<form method=\"post\">\nラジオ1\n<input type=\"radio\" name=\"radio1\" value=\"1\">1\n<input type=\"radio\" name=\"radio1\" value=\"2\">2\n<br>ラジオ2\n<input type=\"radio\" name=\"radio2\" value=\"3\">3\n<input type=\"radio\" name=\"radio2\" value=\"4\">4\n<br>チェック\n<input type=\"checkbox\" name=\"check[]\" value=\"5\">5\n<input type=\"checkbox\" name=\"check[]\" value=\"6\">6\n<br><input type=\"button\" onclick=\"submit();\" value=\"送信\">\n</form>\n```\n\n上記のようなデータのとりかたでよいならあとは$resを[fputcsv](https://www.php.net/manual/ja/function.fputcsv.php)すればよいでしょう \n\n", "name": "", "is_accepted": false } ]
735d8c3499614086eb512dcc693cd00c
### 前提・実現したいこと スライドショーの次のページを表示させる矢印を付けたい ### 発生している問題・エラーメッセージ 2,3ページ目の矢印はクリックできるが、1ページ目がクリックできない ### ``` <!--- start image slider---> <div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel" data-interval="7000"> <ol class="carousel-indicators"> <li data-target="#carouselExampleIndicators" data-slide-to="0" class="active"></li> <li data-target="#carouselExampleIndicators" data-slide-to="1"></li> <li data-target="#carouselExampleIndicators" data-slide-to="2"></li> </ol> <div class="carousel-inner" role="listbox"> <!--- slide1---> <div class="carousel-item active" style="background-image:url(img/slide0.jpg);"> <div class="carousel-caption text-center"> <h1>Welcome To NUno</h1> <h3>Animated Bootstrap Theme</h3> <a class="btn btn-outline-light btn-lg" href="#course">Get Started</a> </div> </div> <!---slider2---> <div class="carousel-item" style="background-image:url(img/slide1.jpg);"></div> <!---slider3---> <div class="carousel-item" style="background-image:url(img/slide2.jpg);"></div> </div><!--- end carousel---> <!---prev next button--> <a class="carousel-control-prev" href="#carouselExampleIndicators" role="button" data-slide="prev"> <span class="carousel-control-prev-icon" aeia-hidden="true"></span> </a> <a class="carousel-control-next" href="#carouselExampleIndicators" role="button" data-slide="next"> <span class="carousel-control-next-icon" aeia-hidden="true"></span> </a> </div> <!--- end image slider---> ``` ``` /*---slider---*/ .carousel-item { height: 100vh; } .carousel-caption { position: absolute; top: 38%; text-transform: uppercase; width: 100%; right: 0; left: 0; } .carousel-caption h1 { font-size: 3.8rem; font-weight: 700; letter-spacing: .3rem; text-shadow: .1rem .1rem .8rem black; padding-bottom: 1rem; } .carousel-caption h3 { font-size: 2rem; text-shadow: .1rem .1rem .5rem black; padding-bottom: 1.1rem; } .btn-lg { border-width: medium; border-radius: 0; font-size: 1.1rem; } ``` ### 試したこと 原因は、文字がかぶってることにあると考えているのですが、対処法がわかりません。
Bootstrapでスライドショーを作りたい ======================
teratail.com
2020.40
[ { "text": "こんばんは。 \n\n\n>対処法がわかりません。 \n\n\n3つ挙げます。 \n\n\n\n\n---\n\n\n前景をクリックできなくする方法。 \n\n\n\n```\n.carousel-caption {\n pointer-events: none;\n}\n```\n\n\n\n---\n\n\n前面に出してしまう方法。 \n\n\n\n```\n.carousel-control-next, .carousel-control-prev {\n z-index: 99;\n}\n```\n\n\n\n---\n\n\n前景を小さくしてしまう方法。 \n\n\n\n```\n.carousel-caption {\n width: max-content;\n margin: 0 auto;\n}\n```\n", "name": "", "is_accepted": true } ]
8c50f693409728d47069f8410f161931
[参考内容](https://codepen.io/aq_yoshida/pen/gKedxY)をもとに ドットで表示した位置が画像で表示されるものになっています 2枚の画像を用意し画像を重ねた時 違った位置にドットがある場合に重なっていない部分のドットを点滅するようにすることを目指しています 自身でやると画像そのものを点滅することしかできません. 解決方法お分かりの方いましたらよろしくお願いいたします. 下記の一部分のコードは2つ画像選択できるのですが,1つのみ移動させて重ねるものになっています.画像は透過したもので下の部分が見える形になっています. アドバイスいただけましたらよろしくお願いいたします. ``` .drag-and-drop { cursor: move; position: absolute; z-index: 1000; } .drag { z-index: 1001; } ``` ``` (function(){ //要素の取得 var elements = document.getElementsByClassName("drag-and-drop"); //要素内のクリックされた位置を取得するグローバル(のような)変数 var x; var y; //マウスが要素内で押されたとき、又はタッチされたとき発火 for(var i = 0; i < elements.length; i++) { elements[i].addEventListener("mousedown", mdown, false); elements[i].addEventListener("touchstart", mdown, false); } //マウスが押された際の関数 function mdown(e) { //クラス名に .drag を追加 this.classList.add("drag"); //タッチデイベントとマウスのイベントの差異を吸収 if(e.type === "mousedown") { var event = e; } else { var event = e.changedTouches[0]; } //要素内の相対座標を取得 x = event.pageX - this.offsetLeft; y = event.pageY - this.offsetTop; //ムーブイベントにコールバック document.body.addEventListener("mousemove", mmove, false); document.body.addEventListener("touchmove", mmove, false); } //マウスカーソルが動いたときに発火 function mmove(e) { //ドラッグしている要素を取得 var drag = document.getElementsByClassName("drag")[0]; //同様にマウスとタッチの差異を吸収 if(e.type === "mousemove") { var event = e; } else { var event = e.changedTouches[0]; } //フリックしたときに画面を動かさないようにデフォルト動作を抑制 e.preventDefault(); //マウスが動いた場所に要素を動かす drag.style.top = event.pageY - y + "px"; drag.style.left = event.pageX - x + "px"; //マウスボタンが離されたとき、またはカーソルが外れたとき発火 drag.addEventListener("mouseup", mup, false); document.body.addEventListener("mouseleave", mup, false); drag.addEventListener("touchend", mup, false); document.body.addEventListener("touchleave", mup, false); } //マウスボタンが上がったら発火 function mup(e) { var drag = document.getElementsByClassName("drag")[0]; //ムーブベントハンドラの消去 document.body.removeEventListener("mousemove", mmove, false); drag.removeEventListener("mouseup", mup, false); document.body.removeEventListener("touchmove", mmove, false); drag.removeEventListener("touchend", mup, false); //クラス名 .drag も消す drag.classList.remove("drag"); } })() ``` ``` <div class="drag-and-drop1" id="input\_img"> </div> ``` 現状 [作成](https://codepen.io/yudance/pen/jONoqYj)
画像が重なったらある部分を点滅 ===============
teratail.com
2020.05
[ { "text": "canvasを使うと実現できそうです。 \n\n[canvas:画像の合成方法色々](http://webos-goodies.jp/archives/51054671.html) \n\n\nリンク先にサンプルがあるので、 distination-over/distination-in を時間単位で切り替えるようなイメージになるでしょうか。\n\n", "name": "", "is_accepted": true } ]
c90c351c7ff5980f3db42ae77a3a7b31
Ruby初心者です。 現在、インスタグラムのようなサービスの作成を行っております。 gemのdeviseをインストールしたのですが、ユーザ情報の編集と削除が出来ません。(エラーにもならない) 何らかの理由で、updateアクションが機能していないのでは?と考え、 registration\_controller.rbを作成し、以下のようにオーバーロードしてみました。 ``` def update @resource = Resource.find(parmas[:id]) if @user.update_attributes(user_params) redirect_to @user else render 'edit' end end ``` しかし、同様にユーザ情報の編集をすることが出来ません。 どのように行えば、updateすることが出来るでしょうか? ご教授して頂けると幸いです。 よろしくお願いいたします。 【追記】 機能しないviewはdeviseのregistration/edit.html.erbになります。 以下に載せます。 **rails routes** ``` new_user_session GET /users/sign_in(.:format) devise/sessions#new user_session POST /users/sign_in(.:format) devise/sessions#create destroy_user_session DELETE /users/sign_out(.:format) devise/sessions#destroy new_user_password GET /users/password/new(.:format) devise/passwords#new edit_user_password GET /users/password/edit(.:format) devise/passwords#edit user_password PATCH /users/password(.:format) devise/passwords#update PUT /users/password(.:format) devise/passwords#update POST /users/password(.:format) devise/passwords#create cancel_user_registration GET /users/cancel(.:format) devise/registrations#cancel new_user_registration GET /users/sign_up(.:format) devise/registrations#new edit_user_registration GET /users/edit(.:format) devise/registrations#edit user_registration PATCH /users(.:format) devise/registrations#update PUT /users(.:format) devise/registrations#update DELETE /users(.:format) devise/registrations#destroy POST /users(.:format) devise/registrations#create ```    **registration/edit,html.erb**   ``` <h1>プロフィールの編集</h1> <%= form\_for(resource, as: resource\_name, url: registration\_path(resource\_name), html: { method: :put }) do |f| %> <div class="form-group"> <%= f.label :name, "名前" %> <%= f.text\_field :name, autofocus: true, class: "form-control" %> </div> <div class="form-group"> <%= f.label :website, "ウェブサイト" %> <%= f.text\_field :website, autofocus: true, class: "form-control" %> </div> <div class="form-group"> <%= f.label :bio, "自己紹介" %> <%= f.text\_field :bio, autofocus: true, class: "form-control" %> </div> <div class="form-group"> <%= f.label :email, "メールアドレス" %> <%= f.email\_field :email, autofocus: true, class: "form-control" %> </div> <div class="form-group"> <%= f.label :password, "パスワード" %> <%= f.password\_field :password, autofocus: "off", class: "form-control" %> </div> <div class="form-group"> <%= f.label :password\_confirmation, "パスワードの確認" %> <%= f.password\_field :password\_confirmation, autofocus: "off", class: "form-control" %> </div> <%= f.submit "変更する", class: "btn btn-primary" %> <% end %> <br> <div class="form-group"> <%= button\_to "アカウントを削除する", registration\_path(resource\_name), data: { confirm: "Are you sure?" }, method: :delete %> </div> <ul> <li><%= link\_to "パスワードの変更",edit\_user\_password\_path(@resource)%></li> <li><%= link\_to "Back", :back %></li> </ul> ```       **routes.rb**   ``` Rails.application.routes.draw do devise_for :users root to: 'pages#home' resources :users, only: %i(show index) resources :posts, only: %i(index new create show) do resources :photos, only: %i(create) end resources :posts do resources :likes, only: %i(create destroy) end resources :users do member do get :following, :followers end end resources :relationships, only: %i(create destroy) end ```
devise updateアクションとdestroyアクションが機能しない =====================================
teratail.com
2021.31
[ { "text": "controllerを作っただけでは、足りず \n\nroutes.rbに記述が必要です。 \n\n\n\n```\n devise_for :users, :controllers => {\n :registrations => 'users/registrations'\n }\n```\n\n参考 \n\nhttp://madogiwa0124.hatenablog.com/entry/2017/11/26/221657\n\n", "name": "", "is_accepted": true } ]
c170b6e4ce062471fb2f1ebe17eb9d6f
``` using System; using System.Threading.Tasks; using System.Runtime.InteropServices.WindowsRuntime; using Windows.Devices.Enumeration; using Windows.Devices.Bluetooth.GenericAttributeProfile; namespace TestGATT { static class Program { static void Main(string[] args) { communicate().Wait(); } static void callback(GattCharacteristic sender, GattValueChangedEventArgs eventArgs) { Console.Write(System.Text.Encoding.ASCII.GetString(eventArgs.CharacteristicValue.ToArray())); } static async Task communicate() { var selector = GattDeviceService.GetDeviceSelectorFromUuid(ToolboxIdentifications.GattServiceUuids.Nordic_UART); var collection = await DeviceInformation.FindAllAsync(selector); foreach (DeviceInformation info in collection) { Console.WriteLine(string.Format("Name={0} IsEnabled={1}", info.Name, info.IsEnabled)); var service = await GattDeviceService.FromIdAsync(info.Id); var tx_characteristics = service.GetCharacteristics(ToolboxIdentifications.GattCharacteristicsUuid.TX)[0]; var rx_characteristics = service.GetCharacteristics(ToolboxIdentifications.GattCharacteristicsUuid.RX)[0]; rx_characteristics.ValueChanged += callback; await rx_characteristics.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify); while (true) { var input = Console.ReadLine(); var result = await tx_characteristics.WriteValueAsync(System.Text.Encoding.ASCII.GetBytes(input + "\n").AsBuffer(), GattWriteOption.WriteWithoutResponse); } } } } } ``` 上記のようなサンプルコードをフォームアプリに書き写したのですが、 「型'IBuffer'は、参照されていないアセンブリに定義されています。」、 「型'IAsyncAction'は、参照されていないアセンブリに定義されています。」 などのエラーの対処方法が分からず、苦慮しています。 参照設定に問題があるのでしょうか。 初歩的で申し訳ございませんが、ご教示いただけませんでしょうか。 よろしくお願いいたします。 [![イメージ説明](https://teratail.storage.googleapis.com/uploads/contributed_images/aff1d7fb712fe9fb39b2ffb884f8a8b3.png)](https://teratail.storage.googleapis.com/uploads/contributed_images/aff1d7fb712fe9fb39b2ffb884f8a8b3.png) [![![イメージ説明](https://teratail.storage.googleapis.com/uploads/contributed_images/1471d4bb7e5ddcd2761ef2e506b33079.png)](https://teratail.storage.googleapis.com/uploads/contributed_images/1471d4bb7e5ddcd2761ef2e506b33079.png)説明](52a240a6634c62a04d065ad2c0a03c5d.png)](85743b47349e5f0830cb190126f28575.png)
C#フォームアプリでBluetoothのGATT通信を行う方法 ===============================
teratail.com
2021.04
[ { "text": "こんにちは。 \n\n\nWindowsRuntimeのAPIを.NETから利用する場合は参照追加などが必要ですが、 \n\nそれは既にお済でしょうか。 \n\n以下などを参考に設定してみてください。 \n\n\nhttps://blogs.msdn.microsoft.com/lucian/2015/10/23/how-to-call-uwp-apis-from-a-desktop-vbc-app/\n\n", "name": "", "is_accepted": true }, { "text": "参照が不足しているようです。 \n\n下記サイトを参考に、参照設定を追加してみてください。 \n\n自分もこれで解決しました。 \n\n\nhttps://stackoverflow.com/questions/49071899/uwp-brokered-windows-runtime-component-build-error\n\n", "name": "", "is_accepted": false } ]
7dee3fb770d31a2f1c614bd754f3564d
swift初心者です。 下記のようなコードを書いていたらエラーになりました。 nill合体演算子"??"を使って、取得できた値(Int?型)をStringに変換してtextに表示したいです。 ``` class TestClass:XMLMappable{ var comment: String? var ava_mon: Int?  (略) } class ResultViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, XMLParserDelegate { @IBOutlet weak var comment: UITextField! @IBOutlet weak var ava_mon: UITextField! override func viewDidLoad() { super.viewDidLoad() request() } func request() { if let url = URL(string: "https:xxxxxxx") { let request = URLRequest(url: url) let task: URLSessionTask = URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in do { let xmlDictionary = try XMLSerialization.xmlObject(with: data) as? [String: Any] let xmlResponse = XMLMapper<TestClass>().map(XMLObject: xmlDictionary) self.comment.text = xmlResponse?.comment ?? "" self.ava_mon.text = String(xmlResponse?.ava_mon) ?? ""// ここでエラー } catch { print("Serialization error occurred: \(error.localizedDescription)") } }) // 通信開始 task.resume() } } ``` エラーは次のとおりです。 ``` Type of expression is ambiguous without more context ``` 回避するために一旦別の変数に入れてnilチェックをしようかと思ったのですが、一行でやる方法はないのかと思い質問させていただきました。 この辺のサイトを参考にしています。 https://fukatsu.tech/optional-swift 必要と思われるコードを載せました。XMLでレスポンスが帰ってくるWebAPIを呼び出して表示する処理です。 XMLMapperというライブラリを利用しています。 https://github.com/gcharita/XMLMapper XMLをオブジェクトにマップしてくれるライブラリです。 xmlResponseは取得できていて、一行上のcommentは正常に表示されます。
nil合体演算子"??"でnilじゃない場合の値を変換するには ===============================
teratail.com
2020.45
[ { "text": "`Optional<Wrapped>` の `map<U>(_ transform: (Wrapped) -> U)` を使うといいのではないでしょうか? \n\n\n`map` は, 値が `nil` でないときだけ, `transform` を実行します. \n\n`transform` の実行の際は `nil` でないのが確定しているので, 引数が `nil` にならない型の値として渡されてきます. \n\nそして `transform` の完了後, `transform` の戻り値を再度 `nil` になりうる値として返します. \n\nこの際 `transform` 内で型を変換することもできます. \n\n\n\n```\n// TestClass ではなく TestClass? のメソッドを使うため,\n// xmlResponse?.ava\\_mon 【?.】 map ではなく, xmlResponse?.ava\\_mon 【.】 map であることに注意.\nself.ava_mon.text = xmlResponse?.ava_mon.map({ (n: Int) -> String in\n return String(n)\n}) ?? \"\"\n```\n\n…で, これだとちょっと長いので, 省略記法を駆使するとここまで縮められます. \n\n\n\n```\nself.ava_mon.text = xmlResponse?.ava_mon.map { String($0) } ?? \"\"\n```\n", "name": "", "is_accepted": true }, { "text": "\n```\nself.ava_mon.text = String(xmlResponse?.ava_mon) ?? \"\"\n```\n\nnilになるのは`String(xmlResponse?.ava_mon)`じゃなくて`xmlResponse?.ava_mon`じゃないですかね。\n\n", "name": "", "is_accepted": false } ]
27fbb97362e5b4182abcdd7a3287f3b7
### 前提・実現したいこと デプロイしたrailsアプリをunicornを使用し、CentOSから表示したいです。 ### 発生している問題・エラーメッセージ cloud9でcap staging deployを実行しました。 そこからteratermでdeployされたディレクトリを開こうとするといくらでも開けアプリにたどり着きません。。。 【/home/deploy/】 ``` [deploy@tk2-241-30026 deploy]$ ls deploy staging ``` ↑cd deployコマンド何度でも実行できてしまいます。 一体私のアプリはどこに行ってしまったのでしょう… 【releaseディレクトリは空のようです。】 ``` [deploy@tk2-241-30026 deploy]$ cd staging [deploy@tk2-241-30026 staging]$ ls releases shared [deploy@tk2-241-30026 staging]$ cd releases [deploy@tk2-241-30026 releases]$ ls ←releaesの中身は空です。 ``` 【sharedにはいくつかデプロイされています】 ``` [deploy@tk2-241-30026 ~]$ cd /home/deploy/staging [deploy@tk2-241-30026 staging]$ ls releases shared [deploy@tk2-241-30026 staging]$ cd shared [deploy@tk2-241-30026 shared]$ ls bin config log public tmp vendor [deploy@tk2-241-30026 shared]$ ``` ### 該当のソースコード ``` lock '3.7.1' set :application, 'third\_app' set :repo\_url, 'ssh://[email protected]/ユーザー名/アプリ名.git' set :git\_https\_username, 'ユーザー名' set :deploy\_to, '/home/deploy/staging' set :pty, true set :rbenv\_ruby, '2.3.1' set :rbenv\_type, :system set :ssh\_options, :port => "ポート番号" set forward\_agent: true after 'deploy:publishing', 'deploy:restart' namespace :deploy do desc 'Restart application' task :restart do invoke 'unicorn:restart' end end ``` デプロイ時に表示された内容です。 ``` $ cap staging deploy 00:00 git:wrapper 01 mkdir -p /tmp 01 bash: warning: setlocale: LC\_ALL: cannot change locale (C.UTF-8) ✔ 01 [email protected] 0.599s Uploading /tmp/git-ssh-third_app-staging-ubuntu.sh 100.0% 02 chmod 700 /tmp/git-ssh-third_app-staging-ubuntu.sh 02 bash: warning: setlocale: LC\_ALL: cannot change locale (C.UTF-8) ✔ 02 [email protected] 0.149s 00:01 git:check 01 git ls-remote --heads ssh://[email protected]/sagaekeiga/third\_app.git 01 bash: warning: setlocale: LC\_ALL: cannot change locale (C.UTF-8) 01 /bin/sh: warning: setlocale: LC\_ALL: cannot change locale (C.UTF-8) 01 f1fa9b57dc8683e2efce7c8eb03d224bebdb9a8f refs/heads/IndividualEvaluation 01 bf3331afd60eed3c38ce042857632d9684cf8d47 refs/heads/SocialProfile 01 13df3fec6c5fb2f69d0f2dc5f43bb0ceb5932e88 refs/heads/UI-1 01 91678db69f43a1fd0693c3015e98e0fd5e4ca31f refs/heads/call 01 a68f87b354fdf69404b73a9edac6928580e193dc refs/heads/cap 01 e150cd8b4dd9bb4eb9d503eb191f9ed2f3e8c0b9 refs/heads/clip 01 d398612c204ab6bec2b1844ee5a91c1fe3992519 refs/heads/comment 01 ed11b1f282d81e03466edddc6c151e0c41db6001 refs/heads/demand 01 46d626e46a3159de1b417d6e4b63e142eb424579 refs/heads/devise-strongparameters 01 81947c39e6e62732f89966e500465e15cd92ea74 refs/heads/follow-shops-to-users 01 f2cb5821c2dc96501b1739fa4dea2270ec39cdab refs/heads/follow-users-to-shop 01 3e545daec4224b4441b6b76b6cabbb24112a000f refs/heads/following-shops 01 d6a1dd6636b30c2007110386c18121e4000b80e6 refs/heads/following-shops-new 01 7faf81d6534152ef505b66fe8329c53b2e2d73c0 refs/heads/following-users 01 f311041927a9250f57828c054a29dbb87c3b68ea refs/heads/following-users-to-shop 01 3ec55025f675fddfdb1443507b39acfb8ed56835 refs/heads/insist_shop-to-micropost.user 01 5f0b0784e0d0e1baf038786fe2a8be94089715b4 refs/heads/like-shop 01 7d3d18c80f9913a9e081fe61d791fbe8eb040f4f refs/heads/like-users-to-shop 01 14b36068c5139fe0520b88ee7e56492a56ea20e2 refs/heads/liking-shops 01 4bfb35a5a6192a2dca96695c72411ff735a4f39e refs/heads/liking-users 01 be74a9312638eb02f935a11f297ab81a339b9486 refs/heads/mailer 01 e04a5a001d123fbe48ac6034219ca6e291ff43d4 refs/heads/master 01 de8224260bfc71f585b1f47ed8a8bb0a00809f84 refs/heads/messagebox 01 338ea850c89dd09dbd9516fe47d36b41dc03cf72 refs/heads/micropost-partial 01 93ab80c6a4ceb93033fc12ba58bc371cef4af316 refs/heads/micropost_partial_fusion 01 962aced04ebf61068f8a3be4e42023bd2f4d7929 refs/heads/microposts-partial 01 eaab87dc15b5586baf08ac38233a359f00c3d483 refs/heads/movie 01 63da3a3c5f809ccdb53b52fc873d6b488285c489 refs/heads/my-new-feature 01 eaab87dc15b5586baf08ac38233a359f00c3d483 refs/heads/rank 01 983dc6e3373cfb755c852eb8f8662c13177e4d37 refs/heads/recruit 01 4e5f7da406ca722aabe45a026853fdafb0b3fe1b refs/heads/request 01 cecdfb261ea13a888a254692b2d2b605530447a2 refs/heads/say_shop-to-micropost.shop 01 5f3fad920c15d9c45ee9eef673dd53475c18dfb9 refs/heads/search 01 72c54307c0b3971c9984a1d15f47986bdfb5d959 refs/heads/shop-favorites-micropost 01 3708d79eebf2bda7ec901e82c94847fe07a094c8 refs/heads/shop_controller 01 6512361d20b307f0fab6b778ac97c2171da46979 refs/heads/shops-update-delete 01 e23ca6174a237e88bbc3cfdb086930732ddd92a0 refs/heads/sign_up-login 01 8a9cf90684498c85f098dcf50b0410a7cadf4b01 refs/heads/signup-login 01 eaab87dc15b5586baf08ac38233a359f00c3d483 refs/heads/tag 01 f755dcb002868f110eaa43a8d2c36bada93b00f2 refs/heads/test 01 3e545daec4224b4441b6b76b6cabbb24112a000f refs/heads/testfile 01 46cafea290ba59c58bf905b84967ab64fa7db853 refs/heads/updating-users 01 0a76cc4a3900747a3422b96c1ed9d082a77fd0ad refs/heads/user-favorites-ajax 01 72c54307c0b3971c9984a1d15f47986bdfb5d959 refs/heads/user-favorites-page 01 338ea850c89dd09dbd9516fe47d36b41dc03cf72 refs/heads/user-shop-microposts 01 b5c0f8d4c6610636243a5043432110867eb309b4 refs/heads/users-update-delete 01 11db5c51f344d556a23119e309d617d0475b5de1 refs/heads/websocket ✔ 01 [email protected] 3.504s 00:05 deploy:check:directories 01 mkdir -p /home/deploy/staging/shared /home/deploy/staging/releases 01 bash: warning: setlocale: LC\_ALL: cannot change locale (C.UTF-8) ✔ 01 [email protected] 0.090s 00:05 deploy:check:linked_dirs 01 mkdir -p /home/deploy/staging/shared/bin /home/deploy/staging/shared/log /home/deploy/staging/shared/tmp/backup /home/deploy/… 01 bash: warning: setlocale: LC\_ALL: cannot change locale (C.UTF-8) ✔ 01 [email protected] 0.090s 00:05 deploy:check:make_linked_dirs 01 mkdir -p /home/deploy/staging/shared/config 01 bash: warning: setlocale: LC\_ALL: cannot change locale (C.UTF-8) ✔ 01 [email protected] 0.087s 00:05 deploy:check:linked_files linked file /home/deploy/staging/shared/config/secrets.yml does not exist on xxx.xx.xxx.xx ``` 無限ではないんですがこんなにあります… ``` [deploy@tk2-241-30026 deploy]$ cd deploy [deploy@tk2-241-30026 deploy]$ cd deploy [deploy@tk2-241-30026 deploy]$ cd deploy [deploy@tk2-241-30026 deploy]$ cd deploy [deploy@tk2-241-30026 deploy]$ cd deploy [deploy@tk2-241-30026 deploy]$ cd deploy [deploy@tk2-241-30026 deploy]$ cd deploy [deploy@tk2-241-30026 deploy]$ cd deploy [deploy@tk2-241-30026 deploy]$ cd deploy [deploy@tk2-241-30026 deploy]$ cd deploy [deploy@tk2-241-30026 deploy]$ cd deploy [deploy@tk2-241-30026 deploy]$ cd deploy [deploy@tk2-241-30026 deploy]$ cd deploy [deploy@tk2-241-30026 deploy]$ cd deploy [deploy@tk2-241-30026 deploy]$ cd deploy [deploy@tk2-241-30026 deploy]$ cd deploy [deploy@tk2-241-30026 deploy]$ cd deploy [deploy@tk2-241-30026 deploy]$ cd deploy [deploy@tk2-241-30026 deploy]$ cd deploy [deploy@tk2-241-30026 deploy]$ cd deploy [deploy@tk2-241-30026 deploy]$ cd deploy [deploy@tk2-241-30026 deploy]$ cd deploy [deploy@tk2-241-30026 deploy]$ cd deploy [deploy@tk2-241-30026 deploy]$ cd deploy [deploy@tk2-241-30026 deploy]$ cd deploy ``` ### 補足情報(言語/FW/ツール等のバージョンなど) Rails5.0.0 CentOS6.8 Ubuntu Teraterm ### 追加 staging.rbが二つありました。何か関係ありそうですね… 【deploy/staging.rb】 ``` set :pty, true server 'xxx.xx.xxx.xx', user: 'deploy', roles: %w{app db web} set :linked\_dirs, %w{bin log tmp/backup tmp/pids tmp/sockets vendor/bundle} shared\_path = "/home/deploy/staging/shared" set :unicorn\_pid, "#{shared\_path}/tmp/pids/unicorn.pid" set :unicorn\_options, -> { "--path /staging" } set :unicorn\_exec, -> { "unicorn\_rails" } ``` 【unicorn/staging.rb】 ``` base = "/home/deploy/staging" current_path = "#{base}/current" shared_path = "#{base}/shared" worker_processes 2 preload_app true timeout 30 stderr_path "#{current\_path}/log/unicorn.stderr.log" stdout_path "#{current\_path}/log/unicorn.stdout.log" listen "/tmp/unicorn.staging.sock" pid "#{shared\_path}/tmp/pids/unicorn.pid" #ダウンタイム無し preload_app true before_fork do |server, worker| ENV['BUNDLE\_GEMFILE'] = File.expand_path('Gemfile', current_path) old_pid = "#{server.config[:pid]}.oldbin" if File.exists?(old_pid) && server.pid != old_pid begin sig = (worker.nr + 1) >= server.worker_processes ? :QUIT : :TTOU Process.kill(sig, File.read(old_pid).to_i) rescue Errno::ENOENT, Errno::ESRCH # someone else did our job for us end end end after_fork do |server, worker| defined?(ActiveRecord::Base) and ActiveRecord::Base.establish_connection end ```
デプロイ先のディレクトリが無限に存在します =====================
teratail.com
2021.17
[ { "text": "おそらくハードリンクが張られて無限ループになっているかと思います \n\n\n`ln ./hoge ./hoge/deploy` \n\n\nのような。。。 \n\nlinked\\_dirs など、指定している個所を調べてみてはどうでしょう\n\n", "name": "", "is_accepted": false } ]
acc14f3cd46f31f881ac1fc1e38543d6
質問のタイトル通りなのですが平面を移動するのと同じ移動速度で坂道を上るようにプログラムを作成したいです、またジャンプや落下をすることができるようにしたいのですが下記コードのmove.yをどうしたらいいのでしょうか? また。同じ速度ではありませんが上ってキーを離すと上にずっとの上って行ってしまうのですがこれはどう解決すればいいんでしょうか? はやり移動はAddForceを使うべきだと思うのですが... ``` using System.Collections; using System.Collections.Generic; using UnityEngine; public class Player : MonoBehaviour { private float input_h; private float input_v; private Vector3 move; private Rigidbody rb; private Animator ani; public ParticleSystem ps; private float walk_speed;//移動速度 private float run_speed;//移動速度 private const float gravity_force = -50.0f; private const float jump_force = 100.0f; private float gravity;//ジャンプの上下数値管理 private bool isJump; private bool isGround; // Use this for initialization void Start () { walk_speed = 100.0f; isGround = false; rb = GetComponent<Rigidbody>(); ani = GetComponent<Animator>(); Physics.gravity = new Vector3(0, gravity_force, 0); } void animation\_mng() { /*アニメーション*/ float speed = Mathf.Sqrt((move.x * move.x) + (move.z * move.z)); //Debug.Log(speed); ani.SetFloat("Walk\_Speed", speed); } // Update is called once per frame void Update () { input_h = Input.GetAxis("Horizontal"); input_v = Input.GetAxis("Vertical"); Vector3 move_x = new Vector3(); Vector3 move_y = new Vector3(); move_y = Vector3.Scale(Camera.main.transform.forward, new Vector3(1, 0, 1)).normalized * input_v * walk_speed; move_x = Camera.main.transform.right * input_h * walk_speed; move = move_x + move_y; if (move != Vector3.zero) { transform.rotation = Quaternion.LookRotation(move.normalized); } animation_mng(); if (isGround == false) { } else { } if (isGround == true) { rb.velocity = new Vector3(rb.velocity.x, 0, rb.velocity.z); } } void FixedUpdate() { rb.AddForce(move); Debug.Log(rb.velocity); // Debug.Log(move); } private void OnCollisionEnter(Collision c) { isGround = true; move.y = 0; rb.velocity = new Vector3(0, 0, 0); Physics.gravity = new Vector3(0, 0, 0); } void Hit() { } } ```
坂道を上るときも平面を歩くときも同じ速度で移動したい、またジャンプと落下重力可能 ========================================
teratail.com
2020.34
[ { "text": "AddForceを使うということは、それに力を加え続けるということです。 \n\n(多分中学校3年でもやったと思いますが)物体を同じ力で押していたら、一定の速度ではなく、だんだん加速をしていく等加速度運動をします。 \n\nなのでAddFoeceを移動に使うことは個人的にはお勧めしません。 \n\n\nどうしても使いたいようならこちらのサイトを参考にしてみてはいかがでしょうか? \n\n\nUnityでRigidBodyのAddForce()に速度制限をつけてすーっと動かしてすーっと止める \n\nhttp://nnana-gamedev.hatenablog.com/entry/2017/09/07/012721 \n\n\nそれと、落下のほうですが、 \n\n\n\n```\n private void OnCollisionEnter(Collision c)\n {\n isGround = true;\n move.y = 0;\n rb.velocity = new Vector3(0, 0, 0);\n Physics.gravity = new Vector3(0, 0, 0);\n }\n```\n\n \n\nの \n\n\n\n```\nPhysics.gravity = new Vector3(0, 0, 0);\n```\n\n \n\nが邪魔していました。 \n\nこの一文を削除してみてください。\n\n", "name": "", "is_accepted": true } ]
cedc7824d1477785009ddf4417182d46
### 前提・実現したいこと PythonでMySQLのDBに作成したテーブルの中の行数を扱いたいです。 mysql> でいじっている時に `SELECT COUNT~~` で行数が取得できていたのでこれを実行してみたのですが何も返ってきませんでした。 テーブルの行数を知りったい場合どのような処理で取得すればいいのでしょうか? ### 発生している問題・エラーメッセージ ``` [root@1692edfad74 chaapp]# python /test.py SELECT COUNT = None count = None ``` ### 該当のソースコード ``` import mysql.connector import sys def connectDBServer(\_user, \_pw, \_host, \_db): return mysql.connector.connect( user=_user, password=_pw, host=_host, database=_db, buffered=True, charset='utf8') connector = connectDBServer('USER', 'PW', 'ホスト', 'DB名') cursor = connector.cursor() count = cursor.execute("SELECT COUNT(*) FROM tablename;") print("SELECT COUNT = ", cursor.execute("SELECT COUNT(*) FROM tablename;")) print("count = ", count) ```
Python MySQL テーブルの行数を取得したい ==========================
teratail.com
2020.34
[ { "text": "cursor.fetchall()[0][0] \n\n\nで取得できました。綺麗な形ではないですが取得したいものは取れたので解決にしまします。\n\n", "name": "", "is_accepted": true } ]
d4a4166386f7563d7d3d8183ff720895
まずは、表示をどのようにしたいかお見せ致します。 [![![イメージ説明](https://teratail-v2.storage.googleapis.com/uploads/contributed_images/db01f1949bf06379831c448f5c8a5169.png)](https://teratail-v2.storage.googleapis.com/uploads/contributed_images/db01f1949bf06379831c448f5c8a5169.png)最初の状態で、テキストに文字を入力して送信のボタンを押すと2段目のように、 ひとつのブロックに入力した文字が書かれてしまいます。 そうではなく、一番下のように 入力したら、別のブロックを生成して、更に時間も表示したいと考えております。 現状のコードを下記に記載致しますので、 ご教授お願い致します。 ``` <script type="text/javascript">     var webSocket;     window.onload = function() {         var forRtoA = document.createElement('a');         forRtoA.href = "loadMessage";         webSocket = new WebSocket(forRtoA.href.replace("http://", "ws://").replace("https://", "wss://"));         var messageArea = document.getElementById("messageArea");                  var appendMessage = function(value, color) {             var messageElement = document.createElement("div");             messageElement.style.color = color;             messageElement.innerText = value;             messageArea.insertBefore(messageElement, messageArea.firstChild);         }         webSocket.onmessage = function(message) {             var data = JSON.parse(message.data);             if ("message" == data.command) {                 appendMessage(data.text, "black");             } else if ("error" == data.command) {                 appendMessage(data.text, "red");             }         }         webSocket.onerror = function(message) {             appendMessage(message, "red");         }         var messageInput = document.getElementById("messageInput");         messageInput.onkeypress = function(e) {             if (13 == e.keyCode) {                 var message = messageInput.value;                 if (webSocket && "" != message) {                     webSocket.send(message);                     messageInput.value = "";                 }             }         }     }          function disp(){         var date = new Date();         var month = date.getMonth() + 1;         var day = date.getDate();         var hours = date.Hours();         var minutes = date.getMinutes();         var time = month + "/" + day + " " + hours + ":" + minutes;         document.getElementsByClassName("time_send").value= time;     } </script> ``` ``` <c:forEach var="messagelist" items="${ requestScope.messageList }">             <ul class="message-list">             <c:if test="${ messagelist.userid == myuserid }" var="myuser"/>             <c:if test="${ !myuser }">                 <li class="msg_recieve">                     <a href="" target="_blank">                     <img src="<c:out value='${ UserProfile.photo }'/>" alt="メッセージ相手写真" class="c-message_photo img-circle c-photo_mini">                     </a>                     <div class="inner-box">                     <p class="balloon_left"><c:out value="${ messagelist.message }"/></p>                     <p class="time_recieve"><time datetime="2015-07-11T11:11">                         <fmt:formatDate value="${ messagelist.comment_time }" pattern="MM/dd"/>                         <fmt:formatDate value="${ messagelist.comment_time }" type="TIME" timeStyle="SHORT"/>                         </time></p>                     </div>                 </li>              </c:if>              <c:if test="${ myuser }">                 <li class="msg_send ">                     <div class="inner-box">                          <p class="balloon_right" id="messageArea"><c:out value="${ messagelist.message }"/></p>                         <p class="time_send"><time datetime="2015-07-11T11:11">                         <fmt:formatDate value="${ messagelist.comment_time }" pattern="MM/dd"/>                         <fmt:formatDate value="${ messagelist.comment_time }" type="TIME" timeStyle="SHORT"/>                         </time></p>                     </div>                 </li>              </c:if>             </ul>         </c:forEach> ``` また、相手が入力した文字も即座に表示できるようにしたいです。 よろしくお願い致します。
WebSocketでチャットをおこないたいが、表示のさせ方がおかしいです ====================================
teratail.com
2021.25
[ { "text": "appendMessageでテキストをp要素に追加するのではなく、ul要素のliを追加するようにすれば、テキスト入力でブロックが追加できます。その時に現在時刻を取得するか、テキスト入力のタイミングで現在時刻も一緒にサーバーに送信、クライアントで受信すれば時刻も表示可能です。\n \n<http://akioblog.com/2013/03/10/868/>\n \n\n \nテキストだけでなく、時刻もサーバーに送受信するのはjson形式などで工夫してやってみてください。\n \n<http://hakuhin.jp/js/json.html>\n \n\n \n\n> また、相手が入力した文字も即座に表示できるようにしたいです。\n\nサーバーサイドのWebsocket処理でブロードキャスト送信するか、ルーム毎の管理などをしたい場合は、対象ルームの全ユーザーに送信するような処理が必要になります。\n \n\n \nサーバーサイドの実装がどうなっているか?Webscoketの通信の仕組みやDOM操作などおそらく不明確な部分が結構あるのではないでしょうか?部分的に不明な部分を都度実装するのではなく、仕組みを把握されてから実装した方がいいと思います。 \n", "name": "", "is_accepted": false } ]
c21207493850677f89a787d7454198fa
先日も同じ質問出してますが、結構問題の説明が足りなかった気がしまして、今日改めて質問させていただきます。 コードを貼る前に、DBの情報をご覧ください。 ID  入力値 詳細 ---------- 1    xxx        詳細        2    xxx        詳細       3    xxx        詳細       4    xxx        詳細 今index.phpにはブラウザ上でこのように表示しています。  そしてこの詳細にはリンクが入ってます。   ``` <html> <head> <title>DB</title> <link rel="stylesheet" type="text/css" href="css.css"> </head> <body> <form method="post" name="form" action="info.php"> <input type="text" name="name"></input> <input type="submit"></button> </form> <table border="2" cellspacing="10" width="200px"> <tr> <th scope="col">ID</th> <th scope="col">入力値</th> <th scope="col">詳細</th> </tr> <?php $link = mysql_connect('localhost', 'root', ''); if (!$link) { die('接続失敗です。'.mysql_error()); } $db\_selected = mysql_select_db('kadai', $link); if (!$db\_selected){ die('データベース選択失敗です。'.mysql_error()); } mysql_set_charset('utf8'); $result = mysql_query('SELECT id,name FROM user'); if (!$result) { die('クエリーが失敗しました。'.mysql_error()); } while ($row = mysql_fetch_assoc($result)) { ?> <tr> <td><?php print(htmlspecialchars($row['id']));?></td> <td><?php print(htmlspecialchars($row['name']));?></td> <td id="ss"><a href="info.php">詳細</a></td> </tr> <?php } $close\_flag = mysql_close($link); ?> </body> </html> ```      info.php -------- 日付  xxxx        ID     5        入力値    xxxxx       日付  xxxx        ID     7        入力値    xxxxx       日付  xxxx        ID     8        入力値    xxxxx       日付  xxxx        ID     9        入力値    xxxxx           --------ー |トップページへ| --------- これがinfo.phpのブラウザで表示している状態です。 やりたいことは、index.phpページの詳細をクリックしたら、info.phpに飛んでそれぞれの詳細が表示されるように、今はDBにはいってるデータ全部表示していますが、何番目の詳細をクリックすると何番目の詳細が出るようにしたいです。 回答よろしくお願いいたします。
DBから取得したデータをそれぞれの詳細が見れるようにしたいです。 ================================
teratail.com
2020.29
[ { "text": "クエリストリングにIDを含めinfo.phpで受け取ったidの検索結果のものを表示すればいいのではなくてですか? \n\n※追記・修正依頼にある通り情報がないのでidがユニークである前提ですが。 \n\n\n\n```\nループ開始\n ・・・・\n <a href=\"/info.php?id=<?php $row['id']; ?>\">\n ・・・・\nループ終了\n```\n\nこちらは何をするためのものでしょう \n\n\n\n```\n<form method=\"post\" name=\"form\" action=\"info.php\">\n<input type=\"text\" name=\"name\"></input>\n<input type=\"submit\"></button>\n</form>\n```\n", "name": "", "is_accepted": true } ]
52c1e194375b6c8063735945db00b741
新しいクラスファイルを追加したら、tomcatが起動できないです。 http://stackoverflow.com/questions/1392383/server-tomcat-v6-0-server-at-localhost-failed-to-startのサイトにしたがって、Open Launch configurationも設定しましたが、結果はおなじでした。 下記コンソールの失敗した際のログの一部です。 Caused by: org.apache.catalina.LifecycleException: A child container failed during start     at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1131)     at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:800)     at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)     ... 6 more 10 20, 2015 4:32:27 午前 org.apache.catalina.startup.Catalina start 重大: The required Server component failed to start so Tomcat is unable to start. org.apache.catalina.LifecycleException: Failed to start component [StandardServer[8005]]     at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)     at org.apache.catalina.startup.Catalina.start(Catalina.java:691)     at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)     at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)     at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)     at java.lang.reflect.Method.invoke(Method.java:606)     at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:322)     at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:456) Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardService[Catalina]]     at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)     at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:732)     at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)     ... 7 more Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina]]     at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)     at org.apache.catalina.core.StandardService.startInternal(StandardService.java:443)     at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)     ... 9 more Caused by: org.apache.catalina.LifecycleException: A child container failed during start     at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1131)     at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:302)     at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)     ... 11 more 10 20, 2015 4:32:27 午前 org.apache.coyote.AbstractProtocol pause 情報: Pausing ProtocolHandler ["http-bio-8080"] 10 20, 2015 4:32:27 午前 org.apache.coyote.AbstractProtocol pause 情報: Pausing ProtocolHandler ["ajp-bio-8009"] 10 20, 2015 4:32:27 午前 org.apache.catalina.core.StandardService stopInternal 情報: サービス Catalina を停止します 10 20, 2015 4:32:27 午前 org.apache.coyote.AbstractProtocol destroy 情報: Destroying ProtocolHandler ["http-bio-8080"] 10 20, 2015 4:32:27 午前 org.apache.coyote.AbstractProtocol destroy 情報: Destroying ProtocolHandler ["ajp-bio-8009"] 解決方法を教えていただけないでしょうか。
新しいクラスファイルを追加したら、tomcatが起動できない ==============================
teratail.com
2021.31
[ { "text": "プロジェクトの削除等を行っていませんか?\n \nその場合「server.xml」に不要なプロジェクト情報が残っている可能性があります。このファイルを削除することで動くかもしれません。 \n", "name": "", "is_accepted": false } ]
a673c81ff2122336493e19b1f9c1e47a
以下のサイトを参考にしましたが,自分の場合は問題があるパッケージがlinux-baseというもので サイトの手順では該当するパッケージをremoveしていましたが,linux-baseはやばい感じしかしないのでどうすればいいかわかりません 解決策をご享受していただけると助かります https://www.ostechnix.com/fix-sub-process-usr-bin-dpkg-returned-an-error-code-1-in-ubuntu/ sudo apt updateを行う ``` riku@riku-HP-ENVY-x360-Convertible-13-ag0xxx:~$ sudo apt update [sudo] password for riku: Get:1 https://repo.steampowered.com/steam stable InRelease [2,852 B] Get:2 https://repo.steampowered.com/steam stable/steam Sources [565 B] , , , Building dependency tree Reading state information... Done 5 packages can be upgraded. Run 'apt list --upgradable' to see them. W: Target Packages (contrib/binary-amd64/Packages) is configured multiple times in /etc/apt/sources.list:58 and /etc/apt/sources.list:59 W: Target Packages (contrib/binary-all/Packages) is configured multiple times in /etc/apt/sources.list:58 and /etc/apt/sources.list:59 W: Target Translations (contrib/i18n/Translation-en_US) is configured multiple times in /etc/apt/sources.list:58 and /etc/apt/sources.list:59 W: Target Translations (contrib/i18n/Translation-en) is configured multiple times in /etc/apt/sources.list:58 and /etc/apt/sources.list:59 W: Target Translations (contrib/i18n/Translation-ja) is configured multiple times in /etc/apt/sources.list:58 and /etc/apt/sources.list:59 W: Target DEP-11 (contrib/dep11/Components-amd64.yml) is configured multiple times in /etc/apt/sources.list:58 and /etc/apt/sources.list:59 W: Target DEP-11 (contrib/dep11/Components-all.yml) is configured multiple times in /etc/apt/sources.list:58 and /etc/apt/sources.list:59 W: Target DEP-11-icons-small (contrib/dep11/icons-48x48.tar) is configured multiple times in /etc/apt/sources.list:58 and /etc/apt/sources.list:59 W: Target DEP-11-icons (contrib/dep11/icons-64x64.tar) is configured multiple times in /etc/apt/sources.list:58 and /etc/apt/sources.list:59 W: Target DEP-11-icons-hidpi (contrib/dep11/[email protected]) is configured multiple times in /etc/apt/sources.list:58 and /etc/apt/sources.list:59 W: Target CNF (contrib/cnf/Commands-amd64) is configured multiple times in /etc/apt/sources.list:58 and /etc/apt/sources.list:59 W: Target CNF (contrib/cnf/Commands-all) is configured multiple times in /etc/apt/sources.list:58 and /etc/apt/sources.list:59 N: Skipping acquire of configured file 'contrib/binary-i386/Packages' as repository 'http://download.virtualbox.org/virtualbox/debian focal InRelease' doesn't support architecture 'i386' W: Target Packages (contrib/binary-amd64/Packages) is configured multiple times in /etc/apt/sources.list:58 and /etc/apt/sources.list:59 W: Target Packages (contrib/binary-all/Packages) is configured multiple times in /etc/apt/sources.list:58 and /etc/apt/sources.list:59 W: Target Translations (contrib/i18n/Translation-en_US) is configured multiple times in /etc/apt/sources.list:58 and /etc/apt/sources.list:59 W: Target Translations (contrib/i18n/Translation-en) is configured multiple times in /etc/apt/sources.list:58 and /etc/apt/sources.list:59 W: Target Translations (contrib/i18n/Translation-ja) is configured multiple times in /etc/apt/sources.list:58 and /etc/apt/sources.list:59 W: Target DEP-11 (contrib/dep11/Components-amd64.yml) is configured multiple times in /etc/apt/sources.list:58 and /etc/apt/sources.list:59 W: Target DEP-11 (contrib/dep11/Components-all.yml) is configured multiple times in /etc/apt/sources.list:58 and /etc/apt/sources.list:59 W: Target DEP-11-icons-small (contrib/dep11/icons-48x48.tar) is configured multiple times in /etc/apt/sources.list:58 and /etc/apt/sources.list:59 W: Target DEP-11-icons (contrib/dep11/icons-64x64.tar) is configured multiple times in /etc/apt/sources.list:58 and /etc/apt/sources.list:59 W: Target DEP-11-icons-hidpi (contrib/dep11/[email protected]) is configured multiple times in /etc/apt/sources.list:58 and /etc/apt/sources.list:59 W: Target CNF (contrib/cnf/Commands-amd64) is configured multiple times in /etc/apt/sources.list:58 and /etc/apt/sources.list:59 W: Target CNF (contrib/cnf/Commands-all) is configured multiple times in /etc/apt/sources.list:58 and /etc/apt/sources.list:59 ``` sudo apt upgradeを行う ``` riku@riku-HP-ENVY-x360-Convertible-13-ag0xxx:~$ sudo apt upgrade Reading package lists... Done Building dependency tree Reading state information... Done , , , Setting up linux-base (4.5ubuntu3.1) ... debconf: DbDriver "config": /var/cache/debconf/config.dat is locked by another p rocess: Resource temporarily unavailable dpkg: error processing package linux-base (--configure): installed linux-base package post-installation script subprocess returned error exit status 1 Setting up thunderbird (1:68.10.0+build1-0ubuntu0.20.04.1) ... Setting up thunderbird-locale-en (1:68.10.0+build1-0ubuntu0.20.04.1) ... Setting up thunderbird-locale-en-us (1:68.10.0+build1-0ubuntu0.20.04.1) ... Setting up thunderbird-locale-ja (1:68.10.0+build1-0ubuntu0.20.04.1) ... Setting up thunderbird-gnome-support (1:68.10.0+build1-0ubuntu0.20.04.1) ... Processing triggers for mime-support (3.64ubuntu1) ... Processing triggers for hicolor-icon-theme (0.17-2) ... Processing triggers for gnome-menus (3.36.0-1ubuntu1) ... Processing triggers for man-db (2.9.1-1) ... Processing triggers for desktop-file-utils (0.24-1ubuntu3) ... Errors were encountered while processing: linux-base E: Sub-process /usr/bin/dpkg returned an error code (1) ``` dpkgの依存関係を確認してみる ``` sudo dpkg --configure -a [sudo] password for riku: Setting up linux-base (4.5ubuntu3.1) ... debconf: DbDriver "config": /var/cache/debconf/config.dat is locked by another process: Resource temporarily unavailable dpkg: error processing package linux-base (--configure): installed linux-base package post-installation script subprocess returned error exit status 1 Errors were encountered while processing: linux-base ``` ``` sudo apt-get install -f Reading package lists... Done Building dependency tree Reading state information... Done The following packages were automatically installed and are no longer required: dkms libgsoap-2.8.91 libllvm9 libvncserver1 virtualbox-dkms Use 'sudo apt autoremove' to remove them. 0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded. 1 not fully installed or removed. After this operation, 0 B of additional disk space will be used. debconf: DbDriver "config": /var/cache/debconf/config.dat is locked by another process: Resource temporarily unavailable Setting up linux-base (4.5ubuntu3.1) ... debconf: DbDriver "config": /var/cache/debconf/config.dat is locked by another process: Resource temporarily unavailable dpkg: error processing package linux-base (--configure): installed linux-base package post-installation script subprocess returned error exit status 1 Errors were encountered while processing: linux-base E: Sub-process /usr/bin/dpkg returned an error code (1) ``` **grep '^[^#]' /etc/apt/sources.list** ``` riku@riku-HP-ENVY-x360-Convertible-13-ag0xxx:~$ grep '^[^#]' /etc/apt/sources.list deb http://jp.archive.ubuntu.com/ubuntu/ focal main restricted deb http://jp.archive.ubuntu.com/ubuntu/ focal-updates main restricted deb http://jp.archive.ubuntu.com/ubuntu/ focal universe deb http://jp.archive.ubuntu.com/ubuntu/ focal-updates universe deb http://jp.archive.ubuntu.com/ubuntu/ focal multiverse deb http://jp.archive.ubuntu.com/ubuntu/ focal-updates multiverse deb http://jp.archive.ubuntu.com/ubuntu/ focal-backports main restricted universe multiverse deb http://security.ubuntu.com/ubuntu focal-security main restricted deb http://security.ubuntu.com/ubuntu focal-security universe deb http://security.ubuntu.com/ubuntu focal-security multiverse deb http://download.virtualbox.org/virtualbox/debian focal contrib deb [arch=amd64] http://download.virtualbox.org/virtualbox/debian focal contrib ```
Ubuntu18.04で apt upgradeを行った際に生じる Errors were encountered while processing: の解決方法 =================================================================================
teratail.com
2021.25
[ { "text": "/etc/apt/sources.list の以下のエントリーをコメントにしてください。 \n\n\n\n```\n# deb http://download.virtualbox.org/virtualbox/debian focal contrib\n```\n\nsudoして好きなエディターで編集するか、GUIなら「ソフトウェアとアップデート」の「他のソフトウェア」に項目があるはずです(チェックを外す)。\n\n", "name": "", "is_accepted": true }, { "text": "「apt upgrade できない」でぐぐるといろいろ記事が引っかかります \n\n参考にならないでしょうか\n\n", "name": "", "is_accepted": false } ]
5bb835663b9eb5fd7d5daaa387f533d8
CSSでボタンを作成しました。 訪問済みのリンクの色を変更したいと思い、a:visitedをCSSに追加記述しましたが正しく表示されません。 [![イメージ説明](https://teratail.storage.googleapis.com/uploads/contributed_images/51cd0f59356320fc9b38a3cb7b6d85b7.jpeg)](https://teratail.storage.googleapis.com/uploads/contributed_images/51cd0f59356320fc9b38a3cb7b6d85b7.jpeg) 下記ボタンのコードで「こうなってしまった」の表示になりました。 記述や順序におかしな点がありましたらご指摘いただき「こうなってほしい」の表示にしたいです。 どうぞ宜しくお願い致します。 ``` .BUTTON\_1 { background: #F9CFD3; background-image: -webkit-linear-gradient(top, #F9CFD3, #F9A9AE); background-image: linear-gradient(to bottom, #F9CFD3, #F9A9AE); border-radius: 20px; color: #FFFFFF; font-family: '游ゴシック', 'Yu Gothic', sans-serif !important; font-size: 40px; width: 98%; font-weight: 100; padding: 47px 40px 40px 40px; text-shadow: 1px 1px 20px #FFFFFF; text-decoration: none; display: inline-block; cursor: pointer; } .BUTTON\_1:hover { color: #FFFFFF; background: #F9A9AE; background-image: -webkit-linear-gradient(top, #F9A9AE, #F9CFD3); background-image: linear-gradient(to bottom, #F9A9AE, #F9CFD3); } .BUTTON\_1:visited { color: #EC779F } ```
訪問済みリンクのデザイン変更(a:visited)がうまく反映されない ===================================
teratail.com
2020.05
[ { "text": "すでにそのリンクをクリックしたからではないでしょうか? \n\nキャッシュの削除orスーパーリロードでどうでしょう? \n\n\n* [ChromeとFirefoxで確実にキャッシュクリアする方法(スーパーリロード、ハードキャッシュクリア)](https://web-generalist.com/super-reload/)\n* [Chromeのキャッシュを「完全に」削除する方法、まとめ。](http://www-creators.com/archives/504)\n\n\n※擬似クラスの記述順は:link→:visited→:hover→:activeです \n\n\n* [:link、:visited、:hover、:active の記述順序とその覚え方](https://jmblog.jp/posts/2007-09-25/link-visited-hover-active/)\n", "name": "", "is_accepted": true } ]
1a61db1e1ad1c1e1e33169fa96ff278a
こんにちは。 cakephp3でshellの実行をしたいと考えております。 ProcsShellを作り、モデルのUsersを呼び出そうとしております。 プログラムは下記のとおりです。 src/shell/ProcShell.php ``` use App\config\app; class ProcsShell extends Shell { public function main() { parent::initialize(); $this->loadModel('Users'); } } ``` こちらを実行させると下記のようなエラーメッセージが出ます。 config/app.phpが走っておらず、defaultクラスがないと怒られているようです。 ``` Datasource class default could not be found. in [/home/ubuntu/workspace/xxxxx/vendor/cakephp/cakephp/src/Datasource/ConnectionRegistry.php, line 57] ``` config/app.php ``` 'Datasources' => [ 'default' => [ 'className' => 'Cake\Database\Connection', 'driver' => 'Cake\Database\Driver\Mysql', 'persistent' => false, 'host' => "xxxxx", 'username' => "xxx", 'password' => "xxxxx", 'database' => "xxxxxxx", 'encoding' => 'utf8', 'timezone' => 'Asia/Tokyo', 'cacheMetadata' => true, 'quoteIdentifiers' => false, ], ``` config/app.phpが実行されていないようなのですが useの使い方が間違っているのでしょうか? よろしくお願い致します。
cakephp3のshellでデータベースへの接続について =============================
teratail.com
2019.43
[ { "text": "同じコードを自分の環境で実行しても、同じようなエラーにならないですね \n\nちなみに、**use App\\config\\app;**という宣言はいらないです。内部で勝手に実行してくれています。 \n\nまたparent::initialize();の処理もinitializeをオーバライドしていないなら、明示的に実行する必要はありません。コードは上記ですべてでしょうか。処理が他にあるのでしょうか。 \n\n\nもっともシンプルなシェルを書いてみたので実行してみてもらえますか \n\n\n\n```\n<?php\nnamespace App\\Shell;\n\nuse Cake\\Console\\Shell;\n\nclass ProcsShell extends Shell\n{\n public function main()\n {\n $this->loadModel('Users');\n debug($this->Users->find()->limit(5));\n }\n}\n```\n\n\n\n---\n\n\n**(追記) 10/5 6:36** \n\n\n同じエラーを再現させることができました。 \n\n※app.phpのDatasources.default.classNameの設定を削除すると発生しますね \n\n\n\n```\n'Datasources' => [\n 'default' => [\n //'className' => 'Cake\\Database\\Connection', // これがないとおきる\n 'driver' => 'Cake\\Database\\Driver\\Mysql',\n```\n", "name": "", "is_accepted": true } ]
9049fbf11f845f324a025344d6969332
### 前提・実現したいこと ``` HTMLのフォームから「式」を取得し、四則演算記号を判別して演算の順番通りに計算をこなしていくということを実現したいです。 仕組みとしては、四則演算子を一つずつ潰していく感じになります。今対応させるのは自然数のみです。 最終的に結果が全て計算されたものになるようなプログラムを目指しています。 ``` ### 発生している問題・エラーメッセージ ``` 乗除計算では値が不自然なものに、和と差の計算では結果に"NaN"が含まれかつ式も右にそのまま出てきます。 三項以上の掛け算でNaNが出現します。 ``` ### 該当のソースコード ``` function keisan() { //a /*try{*/ var chk1 = 0 var str = document.siki.mainsiki.value; var strlong = str.length; for (var cnt = 0; cnt < 10; cnt++) { //b if (str.indexOf(cnt, 0) != 0) { //c chk1++ } //c } //b if (chk1 > 9) { //d alert("最初の文字は数字にしてください"); return; } //d var siki = str; var sikilong = siki.length; var sisoku = new Array(); sisoku[0] = '+'; sisoku[1] = '-'; sisoku[2] = '*'; sisoku[3] = '/'; var sisokunum = 0; for (var cntstrnum = 0; cntstrnum < sikilong; cntstrnum++) { //e var chk = siki.charAt(cntstrnum); for (var cnta = 0; cnta < 4; cnta++) { //f if (chk == sisoku[cnta]) { //g sisokunum = sisokunum + 1; } //g } //f } //e if (sisokunum == 0) { //h alert("答え:" + siki); return; } //h //×÷の計算 var nisokukw = 0; for (var cntnuma = 0; cntnuma < sikilong; cntnuma++) { //1 var chk = siki.charAt(cntnuma); for (var cntb = 2; cntb < 4; cntb++) { //2 if (chk == sisoku[cntb]) { //3 nisokukw = nisokukw + 1; } //3 } //2 } //1 var kakerupo = -1; var warupo = -1; for (var cntmaina = 0; cntmaina <= nisokukw; cntmaina++) { //4 for (var cntc = 2; cntc < 4; cntc++) { //5 if (siki.indexOf(sisoku[cntc]) != -1) { //6 if (cntc == 2) { //7 kakerupo = siki.indexOf(sisoku[cntc]); } else if (cntc == 3) { //7 warupo = siki.indexOf(sisoku[cntc]); } //7 } //6 } //5 if (kakerupo == -1 && warupo == -1) { break; } if (kakerupo != -1 && warupo != -1) { //8 if (kakerupo > warupo) { //9 var levelrl = kakerupo; } else { //9 var levelrl = warupo; } //9 } else if (kakerupo != -1) { //8 var levelrl = kakerupo; } else if (warupo != -1) { //8 var levelrl = warupo; } //8 var levelll = -1; for (var cntd = levelrl - 1; cntd >= 0; cntd--) { //i if (levelll != -1) { //j break; } //j for (var cntnumb = 0; cntnumb < 4; cntnumb++) { //k if (siki.charAt(cntd) == sisoku[cntnumb]) { //l var levelll = cntd; break; } //l if (levelll != -1) { //m break; } //m } //k } //i if (levelll == -1) { //n levelll = 0; } //n a = siki.substring(levelll, levelrl - 1); sikipa = siki.substring(0, levelll); var levellr = levelrl; var levelrr = -1; for (var cnte = levellr + 1; cnte < sikilong; cnte++) { //o for (var cntnumc = 0; cntnumc < 4; cntnumc++) { //p if (siki.charAt(cnte) == sisoku[cntnumc]) { //q levelrr = siki.charAt(cnte); break; } //q if (levelrr != -1) { //r break; } //r } //p if (levelrr != -1) { ///u break; } ///u } //o if (levelrr == -1) { //s levelrr = sikilong; } //s b = siki.substring(levellr + 1, levelrr); sikipb = siki.substring(levelrr, sikilong - 1); if (levelrr == sikilong - 1){ sikipb = ""; } if (siki.charAt(levelrl) == sisoku[2]) { //t en = a * b; } else if (siki.charAt(levelrl) == sisoku[3]) { //t en = a / b; } //t if (levelll == 0){ sikipa = ""; } siki = sikipa + en + sikipb; sikilong = siki.length; } //4 //+-の計算 var nisokuth = 0; for (var cntf = 0; cntf <= sikilong; cntf++) { for (var cntnumd = 0; cntnumd < 4; cntnumd++) { if (sisoku[cntnumd] == siki.charAt(cntf)) { nisokuth++; } } } for (var cntmainb = 0; cntmainb <= nisokuth; cntmainb++) { //1 var middle = -1; for (var cntg = 0; cntg < sikilong; cntg++) { //2 for (var cntnume = 0; cntnume < 2; cntnume++) { //3 if (sisoku[cntnume] == siki.charAt(cntg)) { //4 var middle = cntg; break; } //4 if (middle != -1) { //5 break; } //5 } //3 if (middle == -1) { break; } var lrright = -1; var llleft = 0; var llright = middle - 1; var lrleft = middle + 1; for (var cntaa = lrleft; cntaa < sikilong - lrleft + 1; cntaa++) { for (var cntnumaa = 0; cntnumaa < 2; cntnumaa++) { if (sisoku[cntnumaa] == siki.charAt(cntaa)) { lrright = cntaa - 1; break; } } if (lrright == -1) { lrlight = sikilong; } } var a = siki.substring(llleft, llright); var b = siki.substring(lrleft, lrright); if (siki.charAt(middle) == sisoku[0]) { en = a + b; } else if (siki.charAt(middle) == sisoku[1]) { en = a - b; } var sikipb = substring(lrright, sikilong); siki = en + sikipb; } //2 if (middle == -1) { alert("答え:" + siki); return; } } //1 /*}catch(e){ alert("式が不適合もしくはエラーです。"); return; } finally{ return; }*/ } //a ``` ### 試したこと コードを見たらわかるかと思いますが、括弧がちゃんと対応しているか英数字をふって確かめたりしました。 デバッグも粗方行いました。 ### 補足情報(言語/FW/ツール等のバージョンなど) 特になし
JavaScriptで取得した式を計算したい(四則演算のみ) ==============================
teratail.com
2021.17
[ { "text": "乱暴ですが要件を満たすだけならeval関数で計算できるんじゃないでしょうか。 \n\n\n\n```\nfunction keisan(){\n var ans = eval(\"10*10*30\");\n alert(ans);\n}\n```\n\n \n\nevalを使うくらいならthink49さんが製作した関数を使うほうがよさそうですが。 \n\nコード自体はsubstringの文字の切り出し位置がずれて計算が正しく行えていないように感じましたが、このレベルのバグになると作った本人がデバッグで地道に修正していくのが一番早いじゃないでしょうか。 \n\nどうしてもこの方式を大きく変えたくないというのであれば、think49さんのおっしゃるとおり一旦和算/減算/積算/除算それぞれの計算を行う関数に分割してデバッグしたほうがいいような気がします。 \n\n問題点が分かってからくっつけてもいいわけですし。 \n\n4つの計算関数を作ったうえで、文字列式の書式チェックを行って必要な関数を呼び出す四則演算関数を別に作るとかもありかもしれません。\n\n", "name": "", "is_accepted": true }, { "text": "参考までに、似た要件のコードを書いたことがあります。 \n\n\n* [eval-calculation.js - JSFiddle](https://jsfiddle.net/3k2yabck/2/)\n* [eval-calculation.js: 計算式の文字列を評価する - GitHub Gist](https://gist.github.com/think49/54b074cab2145efddb48765652c74710)\n\n\n質問文に書かれたコードは全体的に見通しが悪いので、和算/減算/積算/除算をそれぞれ関数化してコードを分けて切り分けすると問題点がはっきりして良いと思います。 \n\n細かな最適化は後でも出来ます。 \n\n\nRe: ko20vonobird さん\n\n", "name": "", "is_accepted": false }, { "text": "全体をスクロールする程度に読みましたが、頭に入ってきにくいというのが感想です。 \n\n相当な熟練者でもない限り、このコードを一読して指摘・修正するのは難しいのではないでしょうか。 \n\n質問者の方は初心者ということですが、そのレベルと逸脱した \n\n上級者にしかわからないコード(上級者向けのコードとは違います)を書いているということになります。 \n\n誰でも(数か月後の自分も)読めるコードを書くのが、プログラミングには必要です。 \n\n\n具体的には \n\n●変数の説明をコメントに記述する(説明がいらないような命名が理想です) \n\n例)nisokukw・・・*と/の数 \n\n●行う処理の説明をコメントしておく(これも説明がいらないようなfunction名などで処理を分けるのが理想です) \n\n\nさて、具体的なコードは書きませんが、私なら以下のフローで書くと思います。()は使わないという前提です。 \n\n\n1 フォームの文字列を加算、減算で分解 \n\n\"5-4/6-8+9/7*2+5-7*8\" \n\nを \n\n[ [\"+\" , \"5\" ] , [\"-\" , \"4/6\"] , [\"-\" , \"8\"] , [\"+\" , \"9/7*2\"] , [\"+\" , \"5\"] , [\"-\" , \"7*8\"] ] \n\nとする。 \n\n2 各配列の第二要素をそれぞれ計算。 \n\n3 各配列の第一要素にのっとって、第二要素を集計 \n\n\nご参考になれば、幸甚です。\n\n", "name": "", "is_accepted": false }, { "text": "\"javascript expression eval\" で google 検索すると 数式の評価を javascript で行うことに関する情報をえられます。 \n\n\nたとえば \n\n\n* JavaScript Expression Evaluator <https://silentmatt.com/javascript-expression-evaluator/> \n\nソースコードは <https://github.com/silentmatt/expr-eval/blob/master/parser.js>\n\n\n数式の評価の実装は、コンパイラ、インタープリターをつくる際も入門的な知識が必要です。 \n\n\n他にもこんなページがみつかります。 \n\n\n* 文字列の計算式の計算結果を取得する <http://dobon.net/vb/dotnet/programing/eval.html>\n* 計算式の文字列を評価する <https://gist.github.com/think49/54b074cab2145efddb48765652c74710>\n\n\nこれらのコードを研究してみてから、質問文のコードをみなおすとよいと思います。\n\n", "name": "", "is_accepted": false } ]
b06e88cd346c379471874dbfecf85e91
windows10上のanacondaでpythonを使って、perlのプログラムの呼び出しをしようとしているのですがエラーがでます ``` tokenizer_cmd = ['./tokenizer.perl', '-l', 'en', '-q', '-'] Traceback (most recent call last): File "imdb\_preprocess.py", line 134, in <module> main() File "imdb\_preprocess.py", line 112, in main dictionary = build_dict(os.path.join(path, 'train')) File "imdb\_preprocess.py", line 64, in build_dict sentences = tokenize(sentences) File "imdb\_preprocess.py", line 43, in tokenize tokenizer = Popen(tokenizer_cmd, stdin=PIPE, stdout=PIPE) File "C:\Users\ユーザ名\Anaconda3\envs\py3.5\lib\subprocess.py", line 676, in __init__ restore_signals, start_new_session) File "C:\Users\ユーザ名\Anaconda3\envs\py3.5\lib\subprocess.py", line 957, in _execute_child startupinfo) OSError: [WinError 193] %1 は有効な Win32 アプリケーションではありません。 ``` いろいろと調べた結果、パスに空白がはいっているとこのエラーが出るという情報を得ましたが ユーザ名に空白をいれてしまっているので、その関係なのかなと思ったりしているのですが 関係ありますか? もし関係あるとして、レジストリの変更をしないといけないようなのですが 自分のユーザ名が原因になっているときの、サービス名がわからなかったので 足踏みしています
OSError: [WinError 193] %1 は有効な Win32 アプリケーションではありません。 ======================================================
teratail.com
2019.43
[ { "text": "キーワード引数shellにTrueを渡したら解消するかもしれません。 \n\n\n\n```\ntokenizer = Popen(tokenizer_cmd, stdin=PIPE, stdout=PIPE, shell=True)\n```\n", "name": "", "is_accepted": true } ]
a4bc49bd66aeaaff90df77fd95fd6e64
JAVA初心者です! あるサンプルプログラムをGitHubよりダウンロードして eclipseでインポートして、変更無しで実行したところ index.jspより指定しているJSpの画面が表示されず 「HTTPステータス404」が発生してしまいます。 色々試してみましたがお手上げ状態です。 サンプルプログラムを記載しますので おかしい箇所の指摘をお願い出来ないでしょうか!! 以上、宜しくお願いします。 *********************************** index.jsp <html> <body> <div id="header"> <a href="loginpage">Login</a> </div> <div> <h2>Hello World!</h2> <a href="addnewemployee">Add New Employee</a><br /> <a href="displayemployees">Employee List</a> </div> <div> <a href="hello.jsp">Hello Page</a> </div> </body> </html> ************************************ LoginController.java package com.babu.learning.spring.controllers; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import com.babu.learning.spring.dao.EmployeeDAOImpl; @Controller public class LoginController { @RequestMapping("/loginpage") public ModelAndView loginPage(HttpServletRequest request, HttpServletResponse response) { request.getSession().setAttribute("redirectURL", request.getRequestURL()); return new ModelAndView("loginpage","something",null); } @RequestMapping("/loginaction") public ModelAndView loginAction(HttpServletRequest request, HttpServletResponse response) { String redirectPage = "loginHome"; if(!request.getAttribute("password").equals(new EmployeeDAOImpl().getPassword((String)request.getAttribute("userName")))) { redirectPage = "Error"; } return new ModelAndView(redirectPage, "message", null); } } ********************************** EmployeeController.java package com.babu.learning.spring.controllers; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import com.babu.learning.spring.manager.EmployeeManager; import com.babu.learning.spring.models.Employee; @Controller public class EmployeeController { @Autowired private EmployeeManager employeeManager; @RequestMapping(value = "/hello", method = RequestMethod.GET) value = "/hello", method = RequestMethod.GET public ModelAndView helloHandler() { return new ModelAndView("hello", "message", "Hello"); } @RequestMapping("/addnewemployee") public ModelAndView addNewEmployee() { return new ModelAndView("addnewemployee"); } @RequestMapping("/addEmployee") public ModelAndView addEmployee(HttpServletRequest request, HttpServletResponse response) { Employee newEmployee = new Employee(); newEmployee.setBaseLocaiton((String)request.getParameter("baseLocation")); newEmployee.setDesignation((String)request.getParameter("designation")); newEmployee.setFirstName((String)request.getParameter("firstName")); newEmployee.setLastName((String)request.getParameter("lastName")); newEmployee.setUserName((String)request.getParameter("userName")); newEmployee.setPassword((String)request.getParameter("password")); newEmployee.setSalary(Integer.parseInt((String)request.getParameter("salary"))); if(employeeManager.addNewEmployee(newEmployee)){ return new ModelAndView("employeeslist", "message", newEmployee.getFirstName()+" "+newEmployee.getLastName() +" Employee added successfully"); } return new ModelAndView("employeeslist", "message", newEmployee.getFirstName()+" "+newEmployee.getLastName()+" cannot be added. Try again later."); } } ************************************ web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app\_2\_5.xsd"> <servlet> <servlet-name>spring</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextClss</param-name> <param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value> </init-param> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring-servlet.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>spring</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app> *********************************** spring-servlet.xml <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/aop  http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"> <context:component-scan base-package="com.babu.learning.spring.controllers, com.babu.learning.spring.dao, com.babu.learning.spring.models"/> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/"/> <property name="suffix" value=".jsp"/> </bean> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" scope="prototype"> <property name="url" value="jdbc:derby://localhost:1527/sample;create=true"/> <property value="org.apache.derby.jdbc.ClientDriver" name="driverClassName"/> </bean> <bean id="jdbcTemplate" class = "org.springframework.jdbc.core.JdbcTemplate" scope="prototype"> <property name="dataSource" ref="dataSource"/> </bean> </beans>
springMVCで「HTTPステータス404」 ========================
teratail.com
2021.21
[ { "text": "<https://github.com/babureddyh> のだとは思いますが \n\n\nどうみても作りかけ放置で動かなくてあきらめた系だと思いますよ\n\n", "name": "", "is_accepted": true }, { "text": "404は指定したファイルが存在しない場合に発生するHTTPステータスコードです。 \n\n私の場合は、ファイルの場所の指定を間違えてたまにだします。 \n\n`<a href=\"hello.jsp\">Hello Page</a>`で指定している`hello.jsp`のパスの指定を間違っていませんか? \n\n", "name": "", "is_accepted": false } ]
0185187e5ace33b107edc878ac45edf3
プログラミングc++言語での質問です。 類似度計算のプログラムなのですが、教えていただける方、よろしくお願いします。実装するのはsimilarity.cppの中の「記述」と書いてある部分です。 <内容> similarity.cpp のmk\_tfidf\_list関数は、引数として指定した記事IDに含まれる名詞のTF・IDF値をリストにして返す関数です。→ 「TF・IDF計算」の課題(*)のプログラムを改良し、計算結果をリストにして返すようにして下さい。 単語ベクトルの生成で、記事に出現していない単語は0として生成となっていますが、実際の類似度計算においては、内積(分子)もノルム(分母)の計算においても「0」を考慮する必要はありません。 similarity.cpp include <iostream> ================== include <fstream> ================= include <stdlib.h> ================== include <string.h> ================== include <math.h> ================ define N 227 ============ using namespace std; struct cell { string key; int value;  double tfidf;  struct cell *next; }; using namespace std; // 機能:引数として指定した記事IDに含まれる名詞のTF・IDF値をリストにして返す // 備考:TF・IDF計算プログラムを関数にしたもの struct cell *mk\_tfidf\_list(string input\_id) {  // TF・IDF計算プログラムを記述 return NULL; } int main(int argc, char *argv[]) { string id1 = argv[1]; string id2 = argv[2]; // 指定した記事ID1のTF・IDFリスト struct cell *tf\_idf1; tf\_idf1 = mk\_tfidf\_list(id1); // 指定した記事ID1のTF・IDFリスト struct cell *tf\_idf2; tf\_idf2 = mk\_tfidf\_list(id2); double sim = 0; // 類似度計算のコードを記述 cout << id1 << " - " << id2 << " : " << sim << endl; } (*)参考にするTF・IDF計算のプログラム include <iostream> ================== include <fstream> ================= include <stdlib.h> ================== include <string.h> ================== include <math.h> ================ include <fstream> ================= define N 227 ============ using namespace std; struct cell{ //tf int num; string data; cell *next; }; struct cell *make\_cell(int num, string data){ struct cell *mk\_cell; mk\_cell = new struct cell; mk\_cell->data = data; mk\_cell->num = num; mk\_cell->next = NULL; return mk\_cell; } struct cell *search\_cell(string data,cell *head){ struct cell *buf; buf= head; while(buf != NULL){ if(buf->data == data){ return buf; }  buf = buf->next; } return NULL; } void print\_cell(cell *head){ cell *buf; buf = head; while(buf != NULL){ cout << buf->data << ":" << buf->num << endl; buf = buf->next; } } int main(int argc, char *argv[]){  int size = 0; string input\_id1 = argv[1]; // 指定したファイルIDを取得 ifstream f\_data("posdata.txt"); // posdata.txt ファイルオープン string line; cell *head; head = NULL; // postdata.txtから1行ずつ読み込み while(f\_data >> line){ // 記事IDと名詞例(noun1, noun2,...)のデータに分割 int index = line.find(",");  string f\_id = line.substr(0,index);  string w\_str = line.substr(index+1);  if(f\_id == input\_id1){ // split 名詞列のデータから名詞を1つずつ取り出し int n; for(int i=0; i <= w\_str.length(); i=n+1 ){ n = w\_str.find\_first\_of(",", i); if( n == string::npos ) { n = w\_str.length(); } string word = w\_str.substr(i, n-i ); //単語 if(search\_cell(word,head) == NULL){ //単語がなかった場合 struct cell *tmp; tmp = make\_cell(1,word); tmp->next = head; head = tmp; size++; }else if (search\_cell(word,head) != NULL){ cell *tmp2; tmp2 = search\_cell(word,head); tmp2->num++; } } } } ifstream fin("df.txt"); string line2; cell *head2; head2 = NULL; while(fin >> line2){ int index = line2.find(",");  string f\_id2 = line2.substr(0,index);  string w\_str2 = line2.substr(index+1); int num2 = atoi(w\_str2.data()); cell *tmp2 = make\_cell(num2,f\_id2); tmp2->next = head2; head2 = tmp2; } cell *buf = head; while(buf!=NULL){ double tfidf = 0; double df = 0; cell *buf2 = head2; cell *tmp = search\_cell(buf->data,head2); if(tmp != NULL){ tfidf = buf->num * log2(N*1.0/tmp->num); cout << input\_id1 << "->" << buf->data << ":" << tfidf << endl; } buf = buf->next; } f\_data.close(); return 0; }
c++での類似度計算について ==============
teratail.com
2021.25
[ { "text": "それだけ材料があって、なにがわからんのですか?\n\n", "name": "", "is_accepted": false } ]
3b39fdff67d8576cf477622e8e56d07f
### 前提・実現したいこと Object[]型への変換エラーについてです。 List<T>型のコレクションをforeachで1行づつ取り出して、Excelに出力しようと思っています。 EPPlus.dllというライブラリを利用して出力する既存クラスがあるため、 そのクラスの型が、Object[]型になっています。 集めたデータは、List<T>型なので、Object[]型と一致しないためエラーが発生しています。 このデータをExcelに出力しようと考えていますが、Object[]型へのキャスト? あるいは代入の仕方を教えていただければと思います。 実際には簡単な方法があるのかもしれませんが、残念ながら思いつきませんでした。 ### 発生している問題・エラーメッセージ 以下は、機能を縮小させて発生したエラーメッセージです。 ``` エラー 2 引数 1: 'MEMBER' から 'System.Collections.Generic.List<MEMBER>' に変換できません エラー 1 'AAA.PrintData(System.Collections.Generic.List<MEMBER>)' に最も適しているオーバーロード メソッドには無効な引数がいくつか含まれています。 ``` ### 該当のソースコード 機能を縮小させたソースコードです ``` using System; using System.Collections.Generic; using System.Linq; public partial class MEMBER { public string no { get; set; } public string id { get; set; } public string name_1st { get; set; } public string name_2nd { get; set; } public string tel_no { get; set; } } public class Key { public Key(string id) { this.target = id; } public string target {get; set; } } class AAA { public List<Key> key_id = new List<Key>(); private static List<MEMBER> mlist(Key key_id) { List<MEMBER> Member = new List<MEMBER> { new MEMBER { no = "0001", id = "1" ,name_1st = "あいう", name_2nd = "えお", tel_no = "0123450000"}, new MEMBER { no = "0002", id = "1" ,name_1st = "かきく", name_2nd = "けこ", tel_no = "0123451111"}, new MEMBER { no = "0003", id = "1" ,name_1st = "たちつ", name_2nd = "てと", tel_no = "0123452222"}, new MEMBER { no = "0001", id = "2" ,name_1st = "あいう", name_2nd = "えお", tel_no = "09012340000"}, new MEMBER { no = "0002", id = "2" ,name_1st = "かきく", name_2nd = "けこ", tel_no = "09012341111"}, new MEMBER { no = "0003", id = "2" ,name_1st = "たちつ", name_2nd = "てと", tel_no = "09012342222"}, }; return Member; } public void PrintOut() { int row = 0; int column = 0; foreach (var key in key_id) { foreach (var Collection in mlist(key)) { OutPut(PrintData(Collection)); row++; } } } private Object[] OutPut(Object[] print) { List<Object> result = new List<object>(); result.Add(print[0]); int j = 10; for (int i = 1; i <= j; i++) { result.Add(print[i]); } return result.ToArray(); } private Object[] PrintData(List<MEMBER> member) { List<Object> result = new List<object>(); foreach (var opdata in member) { result.Add(opdata.no); result.Add(opdata.no); result.Add(opdata.name_1st); result.Add(opdata.name_2nd); result.Add(opdata.tel_no); } return result.ToArray(); } } ``` ### 試したこと foreachや型変換にこだわりはなく、List<MEMBER>のようなデータを1行ずつ取り出し、出力する方法を探しています。 ### 補足情報(言語/FW/ツール等のバージョンなど) C# MVC .NET Framework EPPlus 必要な情報が足りないようでしたら教えてください。
コレクションとforeachについて ==================
teratail.com
2021.04
[ { "text": "こんにちは. \n\n\nObject型配列を生成し,そこにMEMBERリストから取り出した要素を追加して,Object型配列を満たす事は出来ています. \n\nエラー原因はPrintDataの引数の型が一致していない事です. \n\nCollectionを渡していますが,Collectionはforeachで取り出された要素型なので,MEMBER型になっています. \n\nつまり分かりやすく書くと, \n\nforeach (MEMBER Collection in mlist(key)) \n\nです. \n\n※ varは便利ですがコードを読みにくくしてしまうことがあるので,そんな時は型を明示的に書く方が有効です. \n\n\nしたがって, \n\n\nOutPut(PrintData(mlist(key))); \n\n\nとすればエラーは解消できると思います. \n\nこの場合,foreach (var Collection in mlist(key)) のループは不要です. \n\n", "name": "", "is_accepted": true }, { "text": "\n```\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.IO;\n\npublic partial class MEMBER\n{\n public string no { get; set; }\n public string id { get; set; }\n public string name_1st { get; set; }\n public string name_2nd { get; set; }\n public string tel_no { get; set; }\n}\n\npublic class Key\n{\n public Key(string id)\n {\n this.target = id;\n }\n\n public string target {get; set; }\n}\n\nclass AAA\n{\n public List<Key> key_id = new List<Key>();\n\n private static List<MEMBER> mlist(Key key_id)\n {\n List<MEMBER> Member = new List<MEMBER> {\n new MEMBER { no = \"0001\", id = \"1\" ,name_1st = \"あいう\", name_2nd = \"えお\", tel_no = \"0123450000\"},\n new MEMBER { no = \"0002\", id = \"1\" ,name_1st = \"かきく\", name_2nd = \"けこ\", tel_no = \"0123451111\"},\n new MEMBER { no = \"0003\", id = \"1\" ,name_1st = \"たちつ\", name_2nd = \"てと\", tel_no = \"0123452222\"},\n new MEMBER { no = \"0001\", id = \"2\" ,name_1st = \"あいう\", name_2nd = \"えお\", tel_no = \"09012340000\"},\n new MEMBER { no = \"0002\", id = \"2\" ,name_1st = \"かきく\", name_2nd = \"けこ\", tel_no = \"09012341111\"},\n new MEMBER { no = \"0003\", id = \"2\" ,name_1st = \"たちつ\", name_2nd = \"てと\", tel_no = \"09012342222\"},\n };\n return Member;\n }\n\n public static void Main()\n {\n PrintOut();\n }\n\n public static void PrintOut()\n {\n List<Key> key_id = new List<Key>();\n //Print();\n }\n\n public void Print()\n {\n int row = 0;\n foreach (Key key in key_id)\n {\n\n foreach (MEMBER Collection in mlist(key))\n {\n OutPut(PrintData(Collection)); \n //NewCell();\n row++;\n }\n }\n }\n\n private Object[] OutPut(Object[] print)\n {\n List<Object> result = new List<object>();\n result.Add(print[0]);\n int j = 10;\n\n for (int i = 1; i <= j; i++)\n {\n result.Add(print[i]);\n }\n return result.ToArray();\n }\n\n private Object[] PrintData(MEMBER member)\n {\n List<Object> result = new List<object>();\n\n\n result.Add(member.no);\n result.Add(member.no);\n result.Add(member.name_1st);\n result.Add(member.name_2nd);\n result.Add(member.tel_no);\n\n return result.ToArray();\n\n }\n}\n```\n", "name": "", "is_accepted": false } ]
51dbfb447018ad114fc47db08ae4742e
### 前提・実現したいこと [![イメージ説明](https://teratail.storage.googleapis.com/uploads/contributed_images/ec4228a4deb367a5e7aa1922adbfb715.png)](https://teratail.storage.googleapis.com/uploads/contributed_images/ec4228a4deb367a5e7aa1922adbfb715.png) 単価入力、数量を選択すると金額、合計金額が表示されるプログラムを書きたいのですが 金額が反映されません。 どうかご教授のほどよろしくお願いします。 ### 発生している問題・エラーメッセージ ``` 単価、数量を入力しても金額が反映されない ``` ### 該当のソースコード ``` <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <title>Register</title> <script type="text/javascript"> function keisan(){ // 設定開始 var tax = 8; // 消費税率 // 商品1 var price1 = document.form1.goods1.selectedIndex * money1; // 単価を設定 document.form1.field1.value = price1; // 小計を表示 // 商品2 var price2 = document.form1.goods2.selectedIndex * money2; // 単価を設定 document.form1.field2.value = price2; // 小計を表示 // 商品3 var price3 = document.form1.goods3.selectedIndex * money3; // 単価を設定 document.form1.field3.value = price3; // 小計を表示 // 合計を計算 var total1 = price1 + price2 + price3; // 設定終了 document.form1.field\_total1.value = total1; // 合計を表示 var tax2 = Math.round((total1 * tax) / 100); document.form1.field\_tax.value = tax2; // 消費税を表示 document.form1.field\_total2.value = total1 + tax2; // 税込合計を表示 } // --> </script> </head> <body> <form action="#" name="form1"> <table border="1" style="background-color: #ffffff;"> <tr> <th>商品名</th> <th>単価</th> <th>数量</th> <th>金額</th> </tr> <tr> <td><input type="text"></td> <td align="right"><input type="text" class="money1">円</td> <td><select name="goods1" onChange="keisan()"> <option>0</option> <option>1</option> <option>2</option> <option>3</option> <option>4</option> <option>5</option> </select></td> <td><input type="text" name="field1" size="8" value="0"> 円</td> </tr> <tr> <td><input type="text"></td> <td align="right"><input type="text" class="money1">円</td> <td><select name="goods2" onChange="keisan()"> <option>0</option> <option>1</option> <option>2</option> <option>3</option> <option>4</option> <option>5</option> </select></td> <td><input type="text" name="field2" size="8" value="0"> 円</td> </tr> <tr> <td><input type="text"></td> <td align="right"><input type="text" class="money1">円</td> <td><select name="goods3" onChange="keisan()"> <option>0</option> <option>1</option> <option>2</option> <option>3</option> <option>4</option> <option>5</option> </select></td> <td><input type="text" name="field3" size="8" value="0"> 円</td> </tr> <tr> <td align="right" colspan="3">合計</td> <td><input type="text" name="field\_total1" size="8" value="0"> 円</td> </tr> <tr> <td align="right" colspan="3">消費税</td> <td><input type="text" name="field\_tax" size="8" value="0"> 円</td> </tr> <tr> <td align="right" colspan="3"><strong>税込合計</strong></td> <td><input type="text" name="field\_total2" size="8" value="0"> 円</td> </tr> </table> </form> </body> </html> ```
単価、個数を入力すると自動で合計金額を表示させたい =========================
teratail.com
2020.40
[ { "text": "ざっと見ただけですが、定義されていない値をかけようとしているので失敗するのでは。 \n\n\n\n```\ndocument.form1.goods1.selectedIndex * money1 // 「money1」が定義されずに使われている\n```\n", "name": "", "is_accepted": true } ]
66a87ea1b578d68244e3a1205b2c4739
テキスト入力欄にフォーカスしたとき、隣にパネルを表示し、パネル内のボタンをクリックするか、パネルの外をクリックしたときパネルを閉じるような処理を作ろうと思っています。 基本的な開閉はうまく行ったのですがパネルの枠外をクリックしたときの処理を付け加えると一瞬表示されてすぐに閉じてしまいます。 正しく開閉させるにはどのようにすればいいのでしょうか? 以下はサンプルです。今のところ jQuery を使う予定はありません。よろしくお願いいたします。 ``` <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> .panel { display: none; border: 1px solid #000; padding: 15px; width: 320px; } .panel.active { display: block; } </style> </head> <body> <input id="example"> <div id="panel" class="panel"> <p>選択してください</p> <button data-text="foo">foo</button> <button data-text="bar">bar</button> </div> <script> var input = document.getElementById('example'); var panel = document.getElementById('panel'); input.addEventListener('focus', function(){ panel.classList.add('active'); }); var buttons = panel.querySelectorAll('button'); for(var i = 0; i < buttons.length; i++){ buttons[i].addEventListener('click', function(){ input.value = this.getAttribute('data-text'); panel.classList.remove('active'); }); } // パネルの外をクリックしたら閉じる document.addEventListener("click", function(evt) { var targetElement = evt.target; do { if (targetElement == panel) { return; } targetElement = targetElement.parentNode; } while (targetElement); panel.classList.remove('active'); }); </script> </body> </html> ``` --- ###  追記 パネル内に <p> 要素を追加
要素の外側をクリックしたときに要素を非表示にしたい =========================
teratail.com
2020.16
[ { "text": "\n```\n<style>\n.panel {\nborder: 1px solid #000;\npadding: 15px;\nwidth: 320px;\n}\n.panel:not(.active) {\ndisplay:none;\n}\n</style>\n<script>\nwindow.addEventListener('DOMContentLoaded', function(e){\n var input = document.querySelector('#example');\n var panel = document.querySelector('#panel');\n input.addEventListener('focus', function(){\n panel.classList.add('active');\n });\n document.addEventListener('click', function(e){\n var t=e.target;\n if(t.id!==\"example\" && t.id!==\"panel\"){\n console.log(t.id);\n panel.classList.remove('active');\n }\n });\n});\n</script>\n<input id=\"example\">\n<div id=\"panel\" class=\"panel\" style=\"\">\n<button data-text=\"foo\">foo</button>\n<button data-text=\"bar\">bar</button>\n</div>\n```\n\n パネル内の要素をクリックしても閉じない\n====================\n\n\nIE対応版 \n\n\n\n```\n<style>\n.panel {\nborder: 1px solid #000;\npadding: 15px;\nwidth: 320px;\n}\n.panel:not(.active) {\ndisplay:none;\n}\n</style>\n<script>\nif(!HTMLElement.prototype.closest){\n HTMLElement.prototype.closest=function(selector){\n var self=this;\n while(p=self.parentNode){\n if([].map.call(p.querySelectorAll(selector),function(x){\n return x;\n }).filter(function(x){\n return x===self;\n }).length>=1) return self;\n self=p;\n }\n return null;\n }\n}\nwindow.addEventListener('DOMContentLoaded', function(e){\n var input = document.querySelector('#example');\n var panel = document.querySelector('#panel');\n input.addEventListener('focus', function(){\n panel.classList.add('active');\n });\n document.addEventListener('click', function(e){\n var t=e.target;\n if(t.id!==\"example\" && !t.closest(\"#panel\")){\n console.log(t.id);\n panel.classList.remove('active');\n }\n });\n});\n</script>\n<input id=\"example\">\n<div id=\"panel\" class=\"panel\" style=\"\">\n<button data-text=\"foo\">foo</button>\n<button data-text=\"bar\">bar</button>\n<input type=\"text\">\n</div>\n```\n", "name": "", "is_accepted": true } ]
541ecd0a4dd52a0e565fba3fd0f42631
### 前提・実現したいこと https://www.tensorflow.org/versions/r0.8/get\_started/os\_setup.html ここの順番通りにインストールとしたところ、tensorFlowのインストールでエラーが発生しました。この不具合を解消するやり方をどなたかご教示願います。 実行したコマンド sudo pip install --upgrade https://storage.googleapis.com/tensorflow/mac/tensorflow-0.8.0-py2-none-any.whl ### 発生している問題・エラーメッセージ ``` The directory '/Users/takeshi/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. The directory '/Users/takeshi/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. Collecting tensorflow==0.8.0 from https://storage.googleapis.com/tensorflow/mac/tensorflow-0.8.0-py2-none-any.whl Downloading https://storage.googleapis.com/tensorflow/mac/tensorflow-0.8.0-py2-none-any.whl (19.3MB) 100% |████████████████████████████████| 19.3MB 46kB/s Requirement already up-to-date: six>=1.10.0 in /Library/Python/2.7/site-packages/six-1.10.0-py2.7.egg (from tensorflow==0.8.0) Collecting protobuf==3.0.0b2 (from tensorflow==0.8.0) Downloading protobuf-3.0.0b2-py2.py3-none-any.whl (326kB) 100% |████████████████████████████████| 327kB 2.0MB/s Collecting wheel (from tensorflow==0.8.0) Downloading wheel-0.29.0-py2.py3-none-any.whl (66kB) 100% |████████████████████████████████| 71kB 4.7MB/s Collecting numpy>=1.10.1 (from tensorflow==0.8.0) Downloading numpy-1.11.0-cp27-cp27m-macosx\_10\_6\_intel.macosx\_10\_9\_intel.macosx\_10\_9\_x86\_64.macosx\_10\_10\_intel.macosx\_10\_10\_x86\_64.whl (3.9MB) 100% |████████████████████████████████| 3.9MB 218kB/s Collecting setuptools (from protobuf==3.0.0b2->tensorflow==0.8.0) Downloading setuptools-22.0.5-py2.py3-none-any.whl (510kB) 100% |████████████████████████████████| 512kB 1.5MB/s Installing collected packages: setuptools, protobuf, wheel, numpy, tensorflow Found existing installation: setuptools 1.1.6 Uninstalling setuptools-1.1.6: Exception: Traceback (most recent call last): File "/Library/Python/2.7/site-packages/pip-8.1.2-py2.7.egg/pip/basecommand.py", line 215, in main status = self.run(options, args) File "/Library/Python/2.7/site-packages/pip-8.1.2-py2.7.egg/pip/commands/install.py", line 317, in run prefix=options.prefix\_path, File "/Library/Python/2.7/site-packages/pip-8.1.2-py2.7.egg/pip/req/req\_set.py", line 736, in install requirement.uninstall(auto\_confirm=True) File "/Library/Python/2.7/site-packages/pip-8.1.2-py2.7.egg/pip/req/req\_install.py", line 742, in uninstall paths\_to\_remove.remove(auto\_confirm) File "/Library/Python/2.7/site-packages/pip-8.1.2-py2.7.egg/pip/req/req\_uninstall.py", line 115, in remove renames(path, new\_path) File "/Library/Python/2.7/site-packages/pip-8.1.2-py2.7.egg/pip/utils/\_\_init\_\_.py", line 267, in renames shutil.move(old, new) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 299, in move copytree(src, real\_dst, symlinks=True) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 208, in copytree raise Error, errors Error: [('/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/\_markerlib/\_\_init\_\_.py', '/tmp/pip-VERMRv-uninstall/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/\_markerlib/\_\_init\_\_.py', "[Errno 1] Operation not permitted: '/tmp/pip-VERMRv-uninstall/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/\_markerlib/\_\_init\_\_.py'"), ('/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/\_markerlib/\_\_init\_\_.pyc', '/tmp/pip-VERMRv-uninstall/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/\_markerlib/\_\_init\_\_.pyc', "[Errno 1] Operation not permitted: '/tmp/pip-VERMRv-uninstall/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/\_markerlib/\_\_init\_\_.pyc'"), ('/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/\_markerlib/markers.py', '/tmp/pip-VERMRv-uninstall/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/\_markerlib/markers.py', "[Errno 1] Operation not permitted: '/tmp/pip-VERMRv-uninstall/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/\_markerlib/markers.py'"), ('/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/\_markerlib/markers.pyc', '/tmp/pip-VERMRv-uninstall/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/\_markerlib/markers.pyc', "[Errno 1] Operation not permitted: '/tmp/pip-VERMRv-uninstall/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/\_markerlib/markers.pyc'"), ('/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/\_markerlib', '/tmp/pip-VERMRv-uninstall/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/\_markerlib', "[Errno 1] Operation not permitted: '/tmp/pip-VERMRv-uninstall/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/\_markerlib'")] ``` ### 試したこと エラーの指示通りに sudo -H pip install --upgrade https://storage.googleapis.com/tensorflow/mac/tensorflow-0.8.0-py2-none-any.whl と、-Hをつけても、Exceptionのエラーは解消されませんでした。 ### 補足情報(言語/FW/ツール等のバージョンなど) OS X El Capitan 10.11.5
tensorFlowがインストールできない =====================
teratail.com
2019.51
[ { "text": "OS Xに始めからインストールされているPythonを使うと、この問題が発生するみたいですね。 \n\n\nTensorFlowのインストール時に一部のライブラリーをアップデートするため \n\n古いものをアンインストールしようとするのですが、 \n\nプリインストールのPythonでは、`sudo`でもそれができないようです。 \n\n(El Capitanのセキュリティー強化の影響のようです。) \n\n\n`--ignore-installed`を付けてアンインストールを抑止するか、 \n\nvirtualenvなどを使ってインストール済みでないPythonを用意して、 \n\nそこにTensorFlowを入れるようにしてみてください。 \n\n\n今後の他の問題が発生したときのためにも、virtualenvの導入をお勧めします。 \n\n\n... \n\n\n参考にならないかも知れませんが、リンクをはっておきます。 \n\n\nsixのOSError:でtensorFlowがインストールできんがな - カネモウケプログラミング   \n\n<http://pikurusux.hatenablog.com/entry/2015/11/12/004217> \n\n", "name": "", "is_accepted": true } ]
2f18f24615848f44986fac0cd555336b
Railsでshowアクションを呼び出した際に、意図した画面に遷移はするものの表示されるURLが以下のようになります。 http://localhost:3000/mypage.6 「/mypage.6」→「/mypage/6」と表示するのが正しいと思いますが、何が間違っているのかわかりません。 こちらはRailsでDeviseのログイン後にmypages#showを呼び出しています。 ご教授お願いいたします。 ⬛︎route.db ``` Rails.application.routes.draw do root to:'tops#index' devise_for :users resource:mypage # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html end ``` ⬛︎ApplicationController ``` class ApplicationController < ActionController::Base protect_from_forgery with: :exception before_action :configure\_permitted\_parameters, if: :devise\_controller? protected def configure\_permitted\_parameters added_attrs = [:username, :email, :password, :password\_confirmation, :remember\_me] devise_parameter_sanitizer.permit :sign\_up, keys: added_attrs devise_parameter_sanitizer.permit(:account\_update, keys: [:username]) end def after\_sign\_in\_path\_for(resource) mypage_path(resource.id) end def after\_sign\_out\_path\_for(resource) root_path end private def store\_current\_location store_location_for(:user, request.url) end end ``` ⬛︎MypagesController ``` class MypagesController < ApplicationController before_action :authenticate\_user! def show @user = User.find_by(id: params[:id]) end end ```
Railsのshowアクションでidを指定した際にうまくURLが表示されません。 ========================================
teratail.com
2020.40
[ { "text": "\n```\nresource :mypage\n```\n\n \n\nが原因かと思います。 \n\nこのルーティングでは、/mypage/:id で呼び出すことはできないです。 \n\nやりたいことが実現できるのは、下記のいずれかではないでしょうか。 \n\n\n方法1 \n\nroutes.rb  resources :mypages \n\nurl  /mypages/:id \n\n\n方法2 \n\nroutes.rb  resource :mypage \n\nurl  /mypage/ \n\n\n方法3 \n\nget 'mypage/:id', to: 'mypages#show' \n\nurl /mypage/:id \n\n\nrails routes でヘルパーメソッドとurlとコントローラーを確認しながらやるといいと思います。 \n\n", "name": "", "is_accepted": true } ]
d2fe0c4fb28d5d1e9346b7a258a4f3b7
### 前提・実現したいこと 自分で定義した型(Matrix)の配列をA,Bと二つ生成したい ### 発生している問題・エラーメッセージ 下記のread関数のreturn部分で「double[][]からMatrix型には変換できません」と表示され,同じくread関数のthis.m[row][col] = {{2,3},{2,2}}; 部分で「構文エラーです」と表示される.  ### 該当のソースコード ``` import java.io.BufferedReader; import java.io.FileReader; public class Matrix { private int row; /* 行列の列 */ private int col; /* 行列の行 */ private double[][] m = new double[row][col]; /* 使用する行列 */ public Matrix(){ /* コンストラクタ */ this.m = new double[row][col]; } public Matrix read(String file) { /* ファイルから読み込んで行列を生成する */ try { BufferedReader br = new BufferedReader(new FileReader(file)); String line; this.row=2; /* 適当に代入 */ this.col=2; /* 適当に代入 */ while ((line = br.readLine()) != null){/* 行単位で処理 */ /* 処理は省略 */ } this.m[row][col] = {{2,3},{2,2}}; /* 試しに適当に代入(この部分でエラーが出る) */ return m; /* この部分でエラーが出る */ } catch(Exception e){ e.printStackTrace();/* エラー処理 :トレース*/ return m; } } public static void main(String[] args) { String file1; String file2; file1=args[0]; file2=args[1]; Matrix instance = new Matrix(); Matrix A = instance.read(file1); Matrix B = instance.read(file2); } } ``` ### 試したこと 本来であればファイルからスペースで区切られた行列の値を読み込んで生成したいのですが,ひとまずその処理は省略して適当にrow,col,m[][]に代入しています. //追記 コンストラクタでのthis.m = new double[row][col];のrow,colには0が入っているから改めてmを初期化する必要がある…というところまで分かったのですが,read(String)の返り値としてMatrix型の変数は何を指定してやればよいのかわかりません.mはdouble型であってMatrix型でないならば何を返せばよいのでしょうか? ### 補足情報(FW/ツールのバージョンなど) eclipse 2019のjava10を使用しています
自分で定義した型(Matrix)の配列をA,Bと二つ生成したい ===============================
teratail.com
2020.40
[ { "text": "ファイルの先頭に row と col の値があるものとします。 \n\nfile1.txt \n\n\n\n```\n2 2\n1 7\n5 3\n```\n\n \n\nfile2.txt \n\n\n\n```\n3 5\n1.1 2.2 3.3 4.4 5.5\n6.6 7.7 8.8 9.9 10\n11 12 13 14 15\n```\n\n\n```\nimport java.util.Scanner;\nimport java.io.*;\n\nclass Matrix {\n\n private int row; // 行列の行\n private int col; // 行列の列\n private double[][] m; // 使用する行列\n\n public Matrix(int row, int col) {\n this.row = row; this.col = col; m = new double[row][col];\n }\n public int getRow() { return row; }\n public int getCol() { return col; }\n public double get(int i, int j) { return m[i][j]; }\n public void set(int i, int j, double d) { m[i][j] = d; }\n\n public static Matrix read(String file) {\n try {\n Scanner sc = new Scanner(new File(file));\n int row = sc.nextInt(), col = sc.nextInt();\n Matrix mat = new Matrix(row, col);\n for (int i = 0; i < row; i++)\n for (int j = 0; j < col; j++)\n mat.set(i, j, sc.nextDouble());\n sc.close();\n return mat;\n }\n catch (Exception e) {\n e.printStackTrace();\n return null;\n }\n }\n}\n\nclass Test {\n public static void main(String[] args) {\n if (args.length != 2) return;\n Matrix A = Matrix.read(args[0]);\n Matrix B = Matrix.read(args[1]);\n print(A);\n print(B);\n }\n\n private static void print(Matrix mat) {\n int row = mat.getRow(), col = mat.getCol();\n for (int i = 0; i < row; i++) {\n for (int j = 0; j < col; j++)\n System.out.printf(\"%8.3f\", mat.get(i, j));\n System.out.println();\n }\n System.out.println();\n }\n}\n```\n\n \n\njava Test file1.txt file2.txt の実行結果 \n\n\n\n```\n 1.000 7.000\n 5.000 3.000\n\n 1.100 2.200 3.300 4.400 5.500\n 6.600 7.700 8.800 9.900 10.000\n 11.000 12.000 13.000 14.000 15.000\n```\n\n \n\nファイルの先頭に row と col の値がなくてもできますが、ちょっと面倒です。\n\n", "name": "", "is_accepted": true } ]
8098972a5a054a05ccaa7af739188f85
jsファイルをhtmlで読み込みたいです。 http://it-challe.com/drill-down-menu/ を参考にしてドリルダウンメニューを作っています。 ``` <div class="list-menu"> <ul class="menu menu-parent"> <li> <a class="menu-item">食事・デザート<i class="fa fa-chevron-right"></i><span class="post-count">(5)</span></a> <ul class="menu-child"> <li> <a class="menu-item">肉料理<i class="fa fa-chevron-right"></i><span class="post-count">(3)</span></a> <ul class="menu-child"> <li><a href="#">ステーキ</a></li> <li><a href="#">すき焼き</a></li> <li><a href="#">焼き鳥</a></li> </ul> </li> <li> <a class="menu-item">デザート<i class="fa fa-chevron-right"></i><span class="post-count">(2)</span></a> <ul class="menu-child"> <li><a href="#">ケーキ</a></li> <li><a href="#">プリン</a></li> </ul> </li> </ul> </li> <li> <a class="menu-item">旅行<i class="fa fa-chevron-right"></i><span class="post-count">(1)</span></a> <ul class="menu-child"> <li> <a>海外旅行</a> </li> <li> <a class="menu-item">国内旅行<i class="fa fa-chevron-right"></i><span class="post-count">(1)</span></a> <ul class="menu-child"> <li><a href="#">いちご狩り</a></li> </ul> </li> </ul> </li> <li> <a>ビジネス</a> </li> </ul> </div> ``` とindex.htmlに書いて、 ``` $(function() { // メニュータップ時 $('.menu-item').on('click', function() { // タップしたメニューの下層メニュー var child = $(this).next('.menu-child'); // 表示領域の高さを下層メニューの高さに調整 $('.list-menu').height(child.height()); // アニメーションの終点にCSSを切り替えてスライドさせる child.addClass('is-active'); }); // 1つ上の階層に戻るメニューを各下層メニューに自動追加 $('.menu-child').prepend('<li class="menu-back"><a>1つ戻る<i class="fa fa-chevron-left"></i></a></li>'); // 1つ上の階層に戻るメニューをタップしたとき $('.menu-back').on('click', function() { var parents = $(this).parent(); // アニメーションの終点を削除して始点に切り替えてスライドさせる parents.removeClass('is-active'); // 表示領域の高さを1つ上の階層の高さに戻す $('.list-menu').height(parents.parent().parent().height()); }); }); ``` とmenu.jsに書きました。 このmenu.jsに書いた内容をどのようにしてhtmlに読み込ませれば良いのでしょうか? hmtlの中にjsの内容を書き込むのではなく、htmlファイルとjsは別々で構成したいです。
jsファイルをhtmlで読み込みたい ==================
teratail.com
2020.50
[ { "text": "二つのファイルが同じフォルダ内にあるのであれば、 \n\n`<script src=\"menu.js\"></script>` \n\nを追加してください。\n\n", "name": "", "is_accepted": true } ]
732a4a937aadf5e0530e10f9dd44b100
hugoという静的サイトジェネレーターでローカルサーバーを立ち上げる際、 http://localhost:1313/hoge/で立ち上げることができます。 現在、C:\xampp\apache\confのhttpd.confのDocumentRootは、「C:/xampp/htdocs」となっています。 ネットで調べたところ、http://localhostはhttpd.confのDocumentRootで設定している値のことだと出てきました。つまり、私の環境では、http://localhost=C:/xampp/htdocsということだと思います。 そして、現在、http://localhost:1313/hoge/でhugoで設定したwebページが表示できています。しかし、C:/xampp/htdocs直下に「hoge」フォルダは存在しません。 C:/xampp/htdocs直下にhogeフォルダがないのに、http://localhost:1313/hoge/でアクセスできているのはなぜでしょうか? このhogeフォルダは仮想的なものなのでしょうか? hugoに関することでなくとも、apache辺り?に関することを教えてくださると幸いです。 httpd.conf ``` Define SRVROOT "C:/xampp/apache" ServerRoot "C:/xampp/apache" Listen 80 LoadModule access_compat_module modules/mod_access_compat.so LoadModule actions_module modules/mod_actions.so LoadModule alias_module modules/mod_alias.so LoadModule allowmethods_module modules/mod_allowmethods.so LoadModule asis_module modules/mod_asis.so LoadModule auth_basic_module modules/mod_auth_basic.so LoadModule authn_core_module modules/mod_authn_core.so LoadModule authn_file_module modules/mod_authn_file.so LoadModule authz_core_module modules/mod_authz_core.so LoadModule authz_groupfile_module modules/mod_authz_groupfile.so LoadModule authz_host_module modules/mod_authz_host.so LoadModule authz_user_module modules/mod_authz_user.so LoadModule autoindex_module modules/mod_autoindex.so LoadModule cgi_module modules/mod_cgi.so LoadModule dav_lock_module modules/mod_dav_lock.so LoadModule dir_module modules/mod_dir.so LoadModule env_module modules/mod_env.so LoadModule headers_module modules/mod_headers.so LoadModule include_module modules/mod_include.so LoadModule info_module modules/mod_info.so LoadModule isapi_module modules/mod_isapi.so LoadModule log_config_module modules/mod_log_config.so LoadModule cache_disk_module modules/mod_cache_disk.so LoadModule mime_module modules/mod_mime.so LoadModule negotiation_module modules/mod_negotiation.so LoadModule proxy_module modules/mod_proxy.so LoadModule proxy_ajp_module modules/mod_proxy_ajp.so LoadModule rewrite_module modules/mod_rewrite.so LoadModule setenvif_module modules/mod_setenvif.so LoadModule socache_shmcb_module modules/mod_socache_shmcb.so LoadModule ssl_module modules/mod_ssl.so LoadModule status_module modules/mod_status.so LoadModule version_module modules/mod_version.so <IfModule unixd_module> User daemon Group daemon </IfModule> ServerAdmin postmaster@localhost ServerName localhost:80 <Directory /> AllowOverride none Require all denied </Directory> DocumentRoot "C:/xampp/htdocs" <Directory "C:/xampp/htdocs"> Options Indexes FollowSymLinks Includes ExecCGI AllowOverride All Require all granted </Directory> <IfModule dir_module> DirectoryIndex index.php index.pl index.cgi index.asp index.shtml index.html index.htm \ default.php default.pl default.cgi default.asp default.shtml default.html default.htm \ home.php home.pl home.cgi home.asp home.shtml home.html home.htm </IfModule> <Files ".ht*"> Require all denied </Files> ErrorLog "logs/error.log" LogLevel warn <IfModule log_config_module> LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined LogFormat "%h %l %u %t \"%r\" %>s %b" common <IfModule logio_module> LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio </IfModule> CustomLog "logs/access.log" combined </IfModule> <IfModule alias_module> ScriptAlias /cgi-bin/ "C:/xampp/cgi-bin/" </IfModule> <IfModule cgid_module> </IfModule> <Directory "C:/xampp/cgi-bin"> AllowOverride All Options None Require all granted </Directory> <IfModule headers_module> RequestHeader unset Proxy early </IfModule> <IfModule mime_module> TypesConfig conf/mime.types AddType application/x-compress .Z AddType application/x-gzip .gz .tgz AddHandler cgi-script .cgi .pl .asp AddType text/html .shtml AddOutputFilter INCLUDES .shtml </IfModule> <IfModule mime_magic_module> MIMEMagicFile "conf/magic" </IfModule> Include conf/extra/httpd-mpm.conf Include conf/extra/httpd-multilang-errordoc.conf Include conf/extra/httpd-autoindex.conf Include conf/extra/httpd-languages.conf Include conf/extra/httpd-userdir.conf Include conf/extra/httpd-info.conf Include conf/extra/httpd-vhosts.conf Include "conf/extra/httpd-proxy.conf" Include "conf/extra/httpd-default.conf" Include "conf/extra/httpd-xampp.conf" <IfModule proxy_html_module> Include conf/extra/proxy-html.conf </IfModule> Include conf/extra/httpd-ssl.conf <IfModule ssl_module> SSLRandomSeed startup builtin SSLRandomSeed connect builtin </IfModule> AcceptFilter http none AcceptFilter https none <IfModule mod_proxy.c> <IfModule mod_proxy_ajp.c> Include "conf/extra/httpd-ajp.conf" </IfModule> </IfModule> ```
localhostにhogeフォルダがないのに、 http://localhost:1313/hoge/でwebページが表示されるのはなぜですか? =========================================================================
teratail.com
2020.45
[ { "text": "mokemokechicken様のご回答より、apacheではなく、hugoの方を調べるべきだということが分かりました。 \n\n\nport 1313 の http server が Apache ではなく、hugoなので、c:/xampp/htdocs直下にhogeフォルダがなくても、http://localhost:1313/hoge/でアクセスできるのではないかとのことでした。 \n\n\n確かに。mokemokechicken様のおっしゃるとおり、apacheは関係なく、hugoの方の問題だと思うので、hugoに関する調査を進めていこうと思います。\n\n", "name": "", "is_accepted": true } ]
96087645c10e3d32c868f1c84ba32310
本番サーバと開発環境でRailsアプリからメールを飛ばそうと考えております。 開発環境からはメールが送れたのですが、本番では送れないようです。 enviroments/development.rb ``` # Mail Config config.action_mailer.smtp_settings = { :enable\_starttls\_auto => true, :address => "smtp.gmoserver.jp", :port => 587, :domain => 'smtp.gmoserver.jp', :user\_name => ENV['MAIL\_USER'], :password => ENV['MAIL\_PASS'], :authentication => 'login', } config.action_mailer.default_url_options = { host: 'localhost', port: 3000 } ``` enviroments/production.rb ``` # Mail Config config.action_mailer.smtp_settings = { :enable_starttls_auto => true, :address => "smtp.gmoserver.jp", :port => 587, :domain => 'smtp.gmoserver.jp', :user_name => ENV['MAIL\_USER'], :password => ENV['MAIL\_PASS'], :authentication => 'login', } config.action_mailer.default_url_options = { host: 'honban.com' } ``` これは何が問題なのでしょうか?どちらも環境変数は同じように設定してあります。 それ以外だとconfig.action\_mailer.default\_url\_optionsの問題なのでしょうか??
ActionMailerの設定 ===============
teratail.com
2020.10
[ { "text": "すみません。メールサーバでなく、自分のPCから送られただけでした。設定を見直します。\n\n", "name": "", "is_accepted": true } ]
6666280d534d06ac1af1ddf7f9f218d8
以下のようなURLで、場所に関わらず、"aaa.com"を含む場合に404にしたいです。 https://example.com/aa.cgi?a=http://aaa.com&b=http://bbb.net https://example.com/aa.cgi?a=https://bbb.xyz&b=https://aaa.com 色々調べた結果、こんなこういう表記になったのですが、うんともすんとも言いません。 ``` RewriteEngine On RewriteCond %{REQUEST\_URI} ^.*aaa\.com.* RewriteRule ^.*$ - [NC,R=404,L] ``` どこに原因があるでしょうか。 アドバイスいただければ幸いです。 よろしくお願い致します。
.htaccessで特定の引数をもつものを404にしたい ============================
teratail.com
2020.29
[ { "text": "<https://www.digrart.jp/blog/web/redirect/#blogSec2>\n\n", "name": "", "is_accepted": true } ]
2a320a20aca12ca7ee3f8ad34fad3f74
``` Error:Execution failed for task ':app:transformResourcesWithMergeJavaResForDebug'. > com.android.build.api.transform.TransformException: com.android.builder.packaging.DuplicateFileException: Duplicate files copied in APK META-INF/BCKEY.DSA File1: /Applications/Android Studio.app/Contents/gradle/m2repository/org/bouncycastle/bcprov-jdk15on/1.48/bcprov-jdk15on-1.48.jar File2: /Applications/Android Studio.app/Contents/gradle/m2repository/org/bouncycastle/bcpkix-jdk15on/1.48/bcpkix-jdk15on-1.48.jar ``` appのbuild.gradle ``` apply plugin: 'com.android.application' android { compileSdkVersion 23 buildToolsVersion "21.1.2" packagingOptions { exclude 'META-INF/NOTICE.txt' exclude 'META-INF/LICENSE.txt' exclude 'META-INF/DEPENDENCIES' exclude 'META-INF/NOTICE' exclude 'META-INF/LICENSE' } defaultConfig { applicationId "jp.sub.takelab.twitmorus" minSdkVersion 13 targetSdkVersion 21 } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt' } } } dependencies { compile 'com.android.support:support-v4:23.0.+' compile 'com.android.support:design:23.1.1' compile files('libs/android-smart-image-view-1.0.0.jar') compile files('libs/twitter4j-core-4.0.2.jar') compile 'com.beardedhen:androidbootstrap:1.2.3' compile 'com.android.support:appcompat-v7:23.1.1' compile 'com.android.support:support-v4:23.1.0' compile 'com.google.android.gms:play-services-appindexing:8.3.0' compile 'com.google.gms:google-services:1.5.0-beta2' // [START gms\_compile] //compile 'com.google.android.gms:play-services-analytics:8.3.0' // [END gms\_compile] } //apply plugin: 'com.google.gms.google-services' ``` プロジェクトのbuild.gradle ``` // Top-level build file where you can add configuration options common to all sub-projects/modules. buildscript { repositories { jcenter() } dependencies { classpath 'com.android.tools.build:gradle:2.1.2' //classpath 'com.google.gms:google-services:1.5.0' } } allprojects { repositories { jcenter() } } ``` (コメントアウトは今回追加しようとしたものですが、失敗するため切り分けのためにコメントアウトしました。) 環境はjdk1.8 [duplicate-files-copied-bouncy-castlebcpkix-jdk15on-1-48-jar-how-can-i-resolve](http://stackoverflow.com/questions/36797897/duplicate-files-copied-bouncy-castlebcpkix-jdk15on-1-48-jar-how-can-i-resolve) 回答なし。 この問題に直面した人いませんでしょうか? また解決方法等あったらしりたいです。
AndroidStudioでビルドが通らなくなった 【com.android.builder.packaging.DuplicateFileException】 ================================================================================
teratail.com
2020.29
[ { "text": "dependencesブロックにsupport-v4が2つ記述されているからかもしれません。\n\n", "name": "", "is_accepted": true } ]
b88bd26ce8aa045794b362174ff0a31e
お世話になっております。Ezです。 この度、yum を入れる方法をご教授していただきたく質問させて頂きました。 最近借りたVPSサービスでCentOS6.0が入っているのですが・・・ なんと、yumが入っていないという所でした・・・orz 泣きそうです。 <http://appstars.jp/archive/48> こちらのサイトを参考にしてみたのですが、うまく入りませんでした。 CentOS6.0 64bit サーバーにyumを入れる方法をご存知の方いらっしゃいましたら教えて頂けないでしょうか?
【まさか!】yumが入っていない・・・ ===================
teratail.com
2021.10
[ { "text": "\n```\nyes >> /dev/null\nrpm --import http://ftp.riken.jp/Linux/centos/RPM-GPG-KEY-CentOS-4\n```\nとりあえずこれで放置 \n", "name": "", "is_accepted": true } ]
374b04fa257ac006d498e1fb077825fc
###  前提・実現したいこと Python(Flask,Matplotlib)で、アップロードされたExcelファイルを基にグラフを作成したい ①WebページからExcelテンプレートファイルをダウンロード [![イメージWebページ](https://teratail.storage.googleapis.com/uploads/contributed_images/1e3c37846b173583b16ce2f66e0890ce.png)](https://teratail.storage.googleapis.com/uploads/contributed_images/1e3c37846b173583b16ce2f66e0890ce.png) [![イメージExcelテンプレートファイル](https://teratail.storage.googleapis.com/uploads/contributed_images/4452f11be02c44cd8f08b6463204ad4a.png)](https://teratail.storage.googleapis.com/uploads/contributed_images/4452f11be02c44cd8f08b6463204ad4a.png) ②値を入力したExcelファイルを選択し、送信 [![イメージWebぺージ](https://teratail.storage.googleapis.com/uploads/contributed_images/4912fae76fc6dfd6043872b24ad4c390.png)](https://teratail.storage.googleapis.com/uploads/contributed_images/4912fae76fc6dfd6043872b24ad4c390.png) [![イメージExcel値入力済みファイル](https://teratail.storage.googleapis.com/uploads/contributed_images/7f1bc2848394aec09f96db4b8fd55bab.png)](https://teratail.storage.googleapis.com/uploads/contributed_images/7f1bc2848394aec09f96db4b8fd55bab.png) ③uploadsディレクトリに格納される [![イメージディレクトリ](https://teratail.storage.googleapis.com/uploads/contributed_images/9eabf3a30812ad34e94a6844bdf787b5.png)](https://teratail.storage.googleapis.com/uploads/contributed_images/9eabf3a30812ad34e94a6844bdf787b5.png) ④アップロードされたExcelファイルを元にグラフを作成 [![イメージグラフ](https://teratail.storage.googleapis.com/uploads/contributed_images/931e3224dd840f060add4788e24b095c.png)](https://teratail.storage.googleapis.com/uploads/contributed_images/931e3224dd840f060add4788e24b095c.png) ①~③は問題なく動作しています。 ④は完成イメージです。 ###  エラーメッセージ・該当のソースコード ``` if request.method == 'POST':   file = request.files['file']   UPLOAD_FOLDER = r'C:\\xxx\xxx\xxx\TestProject\uploads'   app.config['UPLOAD\_FOLDER'] = UPLOAD_FOLDER  if file: filename = secure_filename(file.filename) file.save(os.path.join(app.config['UPLOAD\_FOLDER'], filename)) wb = xlrd.open_workbook(r"C:\\xxx\xxx\xxx\TestProject\uploads\test.xlsx") sheets = wb.sheets() month = np.array(sheets['Sheet1'].cell(row=i, column=0).value for i in range(1, 13)) sale = np.array(sheets['Sheet1'].cell(row=i, column=1).value for i in range(1, 13)) cost = np.array(sheets['Sheet1'].cell(row=i, column=2).value for i in range(1, 13)) benefit = sale - cost #プロットの処理が続く ``` エラー例① ``` sheets = wb.sheets() month = np.array([sheets['Sheet1'].cell(row=i, column=0).value for i in range(1, 13)]) sale = np.array([sheets['Sheet1'].cell(row=i, column=1).value for i in range(1, 13)]) cost = np.array([sheets['Sheet1'].cell(row=i, column=2).value for i in range(1, 13)]) benefit = sale - cost plt.plot(month, sale) plt.plot(month, cost) plt.plot(month, benefit) # month行でエラー → TypeError: list indices must be integers or slices, not str ``` エラー例② ``` sheets = wb.sheets() month = np.array(sheets['Sheet1'].cell(row=i, column=0).value for i in range(1, 13)) sale = np.array(sheets['Sheet1'].cell(row=i, column=1).value for i in range(1, 13)) cost = np.array(sheets['Sheet1'].cell(row=i, column=2).value for i in range(1, 13)) benefit = sale - cost plt.plot(month, sale) plt.plot(month, cost) plt.plot(month, benefit)   #benefit行でエラー → TypeError: unsupported operand type(s) for -: 'generator' and 'generator' ``` ###  試したこと 下記のコードは、正しく動作し冒頭にある④のグラフが作成されます ``` w = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) x = np.array([10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10]) y = np.array([7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7]) z = x - y plt.plot(w, x, label='sale') plt.plot(w, y, label='cost') plt.plot(w, z, label='benefit') ``` ###  環境 開発環境:PyCharm サーバ :localhost ブラウザ:Chrome
アップロードされたExcelファイルを基にグラフを作成したい ==============================
teratail.com
2020.50
[ { "text": "①rangeの範囲指定訂正 \n\n②xlrd.open\\_workbookではなくopenpyxlのload\\_workbookを使用 \n\n\n上記の方法で、問題が解消されました。 \n\n\n\n```\nwb = load_workbook(r\".\\uploads\\test.xlsx\")\nsheet = wb['Sheet1']\nmonth = np.array([sheet.cell(row=i, column=1).value for i in range(2, 14)])\n```\n", "name": "", "is_accepted": true } ]
4800d33fb425423956afc52a82c782ab
### 前提・実現したいこと antを実行したいのですが、下記エラーが出てしまいます java1.7と1.8を切り替えて使用したいため、 brew install caskroom/cask/brew-cask brew tap caskroom/versions しまして、 brew cask install java brew cask install java7 していますが、 1.7の場合にantが失敗します antのバージョンも切り替える必要がある??? ### 発生している問題・エラーメッセージ ``` $ export JAVA_HOME=$(/usr/libexec/java_home -v 1.7) $ java -version java version "1.7.0\_80" Java(TM) SE Runtime Environment (build 1.7.0_80-b15) Java HotSpot(TM) 64-Bit Server VM (build 24.80-b11, mixed mode) $ javac -version javac 1.7.0_80 $ ant -version Exception in thread "main" java.lang.UnsupportedClassVersionError: org/apache/tools/ant/launch/Launcher : Unsupported major.minor version 52.0 at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:800) at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142) at java.net.URLClassLoader.defineClass(URLClassLoader.java:449) at java.net.URLClassLoader.access$100(URLClassLoader.java:71) at java.net.URLClassLoader$1.run(URLClassLoader.java:361) at java.net.URLClassLoader$1.run(URLClassLoader.java:355) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:354) at java.lang.ClassLoader.loadClass(ClassLoader.java:425) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308) at java.lang.ClassLoader.loadClass(ClassLoader.java:358) at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:482) $ export JAVA_HOME=$(/usr/libexec/java_home -v 1.8) $ java -version java version "1.8.0\_121" Java(TM) SE Runtime Environment (build 1.8.0_121-b13) Java HotSpot(TM) 64-Bit Server VM (build 25.121-b13, mixed mode) $ javac -version javac 1.8.0_121 $ ant -version Apache Ant(TM) version 1.10.1 compiled on February 2 2017 ``` ### 試したこと 環境変数のANT\_HOMEやPATH、CLASSPATHあたりをいじりましたが、状況変わらず ### 補足情報(言語/FW/ツール等のバージョンなど) macOS: 10.12.2 (Sierra)
antでjava.lang.UnsupportedClassVersionError ==========================================
teratail.com
2021.17
[ { "text": "自己解決しました \n\n\nantの対象は1.7, 1.8で切り替えたいのですが、ant自身の実行は1.8固定でないとNGでした \n\nですので、JAVA\\_HOMEは変更しつつ、JAVACMDを固定することで解決しました \n\n\n私の場合ですと、 \n\nexport JAVACMD=$(/usr/libexec/java\\_home -v 1.8)\"/jre/bin/java\" \n\nを実行しておくことで、 \n\nexport JAVA\\_HOME=$(/usr/libexec/java\\_home -v 1.7) \n\nexport JAVA\\_HOME=$(/usr/libexec/java\\_home -v 1.8) \n\nで切り替えられるようにしています\n\n", "name": "", "is_accepted": true }, { "text": "[Ant.apache - Frequently Asked Questions - Which version of Java is required to run Apache Ant?](http://ant.apache.org/faq.html#java-version) \n\n\n\n\n| Ant Version | Minimum Java Version |\n| --- | --- |\n| 1.1 up to 1.5.4 | 1.1 |\n| 1.6.0 up to 1.6.5 | 1.2 |\n| 1.7.0 up to 1.7.1 | 1.3 |\n| 1.8.0 up to 1.8.3 | 1.4 |\n| Any 1.9.x release and the git branch 1.9.x | 1.5 |\n| Any 1.10.x release and the current git master branch | 1.8 |\n\n", "name": "", "is_accepted": false } ]
329937187dcd6a9309cee8579b60893f
###  前提・実現したいこと UICollectionViewで1行目は横幅一杯に1枚、2行目以降は1行に2枚画像を表示する画面を開発しています。 [![イメージ説明](https://teratail.storage.googleapis.com/uploads/contributed_images/42f82adf089b0d585a6f40c43f7653ce.png)](https://teratail.storage.googleapis.com/uploads/contributed_images/42f82adf089b0d585a6f40c43f7653ce.png) ###  発生している問題・エラーメッセージ 初回表示はされるですが、画面を下にスクロールし、再度一番上に戻ると1行目の横幅が半分になり、途中の行の片方の画像の横幅が広がってしまいます。スクロールしても最初に表示された状態を保つためにはどのようにすべきでしょうか。 [![イメージ説明](https://teratail.storage.googleapis.com/uploads/contributed_images/03680da8b0eda5f2fa9724c1ba266f4e.png)](https://teratail.storage.googleapis.com/uploads/contributed_images/03680da8b0eda5f2fa9724c1ba266f4e.png) ### 該当のソースコード [PagingMenuController](https://github.com/kitasuke/PagingMenuController)を使用しており、メインのビューコントロラーから`imageUrlList`をセットして`MyViewController`を呼び出しています ``` class MyViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { var imageUrlList: Array<String>! override func loadView() { super.loadView() // Do any additional setup after loading the view, typically from a nib. let myCollectionView = UICollectionView(frame: CGRect(origin: CGPoint.zero, size: self.view.frame.size), collectionViewLayout: UICollectionViewFlowLayout()) myCollectionView.backgroundColor = UIColor.white myCollectionView.register(MyCollection.self, forCellWithReuseIdentifier: "MyCell") myCollectionView.delegate = self myCollectionView.dataSource = self self.view.addSubview(myCollectionView) } func collectionView(\_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { if indexPath.row == 0 { return CGSize(width: collectionView.frame.width, height: collectionView.frame.height * 0.3) } return CGSize(width: collectionView.frame.width * 0.5, height: collectionView.frame.height * 0.3) } func collectionView(\_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let collection = collectionView.dequeueReusableCell(withReuseIdentifier: "MyCell", for: indexPath) as! MyCollection let url = imageUrlList[indexPath.row] let thumbnail = collection.contentView.viewWithTag(MyCollection.TAG\_THUMBNAIL) as! ThumbnailImageView thumbnail.loadImage(urlString: url) return collection } } class MyCollection: UICollectionViewCell { static let TAG\_THUMBNAIL: Int = 0 required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder)! } override init(frame: CGRect) { super.init(frame: frame) initView(width: frame.size.width, height: frame.size.height) } func initView(width: CGFloat, height: CGFloat) { let thumbnail: ThumbnailImageView = ThumbnailImageView(frame: CGRect(x: 0, y: 0, width: width, height: height * 0.3)) thumbnail.tag = MyCollection.TAG\_THUMBNAIL self.contentView.addSubview(thumbnail) } } class ThumbnailImageView: UIImageView { let CACHE\_SEC: TimeInterval = 60 * 60 * 24 // 1 day var baseWidth: CGFloat = 0 var baseHeight: CGFloat = 0 required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder)! } override init (frame: CGRect) { super.init(frame: frame) } func loadImage(urlString: String) { self.alpha = 0 let req = URLRequest(url: NSURL(string: urlString)! as URL, cachePolicy: .returnCacheDataElseLoad, timeoutInterval: CACHE\_SEC); let session = URLSession(configuration: URLSessionConfiguration.default, delegate: nil, delegateQueue: OperationQueue.main); session.dataTask(with: req, completionHandler: { (data, resp, err) in if ((err) == nil) { // Success self.image = UIImage(data: data!); UIView.animate(withDuration: 1.0) { () -> Void in self.alpha = 1 } } else { // TODO: show default if error print("AsyncImageView:Error \(err?.localizedDescription)"); } }).resume(); } } ``` ### 試したこと セルのサイズを変更している`collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize`の引数のindexPathが描画したセルの順番と合っていないのかと疑いブレークポイントを貼ってデバッグしましたが、スクロール時にブレークポイントに引っかかりませんでした。 ### 補足情報(言語/FW/ツール等のバージョンなど) * Swift 3 * xcode 8.2.1
UICollectionViewDelegateFlowLayoutで変更したセルのサイズがスクロールすると変化する ==========================================================
teratail.com
2019.51
[ { "text": "CollectionViewはセルを再利用しますので、ちゃんと初期化し直さないと前回表示した状態が残ってしまいます。 \n\n今回の件は、ThumbnailImageViewのframeが最初に生成した時に設定した時のままなためかと思います。 \n\n\n例えば1番目のセルを再度表示した時に画像が半分になるのは、(例えば)6番目のセルを表示した時の大きさのままなためです。 \n\n同じように途中のセルが横幅いっぱいになるのは、最初に1番目のセルを表示した時の大きさのまま(MyCollectionをはみ出している)ためです。 \n\n\n対応策は2つあります。 \n\nどちらを使用するかは場合によります。1行目のセルとそれ以外は横幅以外に違いがないなら対応策1の方が簡単かと思いますが。 \n\n\n###  対応策1\n\n\nどうやらThumbnailImageViewはセルの横幅いっぱいになればいいみたいですから、`autoresizingMask`を設定する。 \n\nつまり、MyCollection の`initView(width:, height:)`に \n\n\n\n```\nthumbnail.autoresizingMask = [.flexible​Width]\n```\n\nを追加する。 \n\n(コードは試してないのでエラーが出るかもです) \n\n\n###  対応策2\n\n\n1行目とそれ以外でセルのidentifierを別にして、再利用する際に横幅いっぱいのセルと半分のセルを混在させなくする。 \n\n\n具体的には、 \n\n\n\n```\noverride func loadView() {\n // ...前略\n myCollectionView.backgroundColor = UIColor.white\n myCollectionView.register(MyCollection.self, forCellWithReuseIdentifier: \"MyCell\")\n myCollectionView.register(MyCollection.self, forCellWithReuseIdentifier: \"MyCellTop\") // <- この行を追加\n // 以下略...\n}\n\nfunc collectionView(\\_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {\n\n let identifier = indexPath.row == 0 ? \"MyCellTop\" : \"MyCell\"\n let collection = collectionView.dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath) as! MyCollection\n // 以下略...\n}\n```\n\nとすればとりあえず動かすことはできるかと思います。 \n\n(例によって動作確認はしてないのでエラーが出たら適宜修正してください) \n\n\n###  蛇足\n\n\n内容とは関係ないですが、`static let TAG_THUMBNAIL: Int = 0`となっていますが、UIViewのtagは0がデフォルト値なので、0をセットしても意味がありません。 \n\n1以上の値にした方がいいかと思います。\n\n", "name": "", "is_accepted": true } ]
0ff0f22540f526960e689b8acdcf5747
**追記です。 どうやらProgressBarを追加したのが原因のようです。ProgressBarのHeightを1dpにしたところ治りました。 しかし、1dpにしたのでは当然表示されないので意味がありません。 ProgressBarをvisibleで表示→非同期で画像をURLからロードして終わったらvisible=goneの画像を戻してprogressbarを隠す、という風にしています。 xmlの書き方とか処理の順番とかそういったことで何とかなりそうな気がするので、現在調べています。** 原因に全く心当たりがないので質問します。 AndroidでListViewからタップしてintentで画面遷移をするのですが、その時に何故か少しスクロールした状態で遷移します。 どのセルをタップしてもだいたい250dp以上遷移した状態で始まり、動作としては問題ないのですが、どう考えてもおかしいので修正したいです。 しかし、全く心当たりがありません。以前はこのようなことはなかったのですが、最近アプリをテストしていたところ、気がついたらこうなっていたので、何をいじったらこうなったか?というのはイマイチ不明です。 画面遷移はMainActivityからsetOnItemClickListenerで飛んでいます。                 ImageCache.clearCache();                 Item item = mAdapter.getItem(i);                 Intent intent = new Intent(getApplication(), ShopDetailActivity.class);                 LocationParcelable parcelable = new LocationParcelable();                 parcelable.mLocation = location;                 intent.putExtra("ItemSerializable", item);                 intent.putExtra("location", parcelable);                 int requestCode = RESULT\_SUBACTIVITY;                 startActivity(intent); こんな感じです。得に何の変哲もないintentのような気がします。 問題のShopDetailActivityのxmlはかなり入れ子になっています。 <LinearLayout     xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:tools="http://schemas.android.com/tools"     android:layout\_width="match\_parent"     android:layout\_height="wrap\_content"     android:orientation="vertical"     android:gravity="top"     tools:context="hoge.ShopDetailActivity">     <ScrollView         android:layout\_width="match\_parent"         android:layout\_height="0dp"         android:layout\_weight="1"         android:fillViewport="true">         <LinearLayout             android:layout\_width="match\_parent"             android:layout\_height="wrap\_content"             android:orientation="vertical">                 <ProgressBar                     android:id="@+id/progressbar\_shopimage"                     android:layout\_width="match\_parent"                     android:layout\_height="300dp"                     android:elevation="6dp"                     android:background="#000000"                     />                 <ImageView                     android:id="@+id/shopImageView"                     android:layout\_width="match\_parent"                     android:layout\_height="300dp"                     android:background="#000000"                     android:elevation="6dp"                     android:visibility="gone"                     android:contentDescription="@string/imagedesc"/>             <LinearLayout                 android:orientation="vertical"                 android:background="#F2EBDB"                 android:layout\_width="match\_parent"                 android:layout\_height="match\_parent">                 //ここに3つくらいListViewが入っています             </LinearLayout>         </LinearLayout>     </ScrollView>     <LinearLayout         android:layout\_width="match\_parent"         android:layout\_height="wrap\_content"         android:orientation="vertical"         >         <View         android:background="@drawable/background\_shadow"         android:layout\_width="match\_parent"         android:layout\_height="1dp" />         <LinearLayout             android:background="#EDE6D6"             android:layout\_width="match\_parent"             android:layout\_height="wrap\_content"             android:padding="10dp"             android:orientation="horizontal"             >             //ここにボタンが2個、下部に固定されるような形にしています         </LinearLayout>     </LinearLayout> </LinearLayout> 大枠はこんな感じです。 何かこう、そういうような現象が起こるようなものに心当たりのある方はどうかよろしくお願いします。 ShopDetailActivity http://yasato.sakura.ne.jp/sda.txt
Androidで画面遷移時に何故か少しスクロールする ==========================
teratail.com
2019.47
[ { "text": "ScrollViewの中にListViewを入れると予想外の動きをするのでやめた方が良いですね。 \n\nとりあえず、ListViewをコメントアウトして実行してみてはどうでしょうか。\n\n", "name": "", "is_accepted": true } ]
f136a32a0f1c97927799a8c29b2fbd37
Aサイトから読み込んだ記事をBサイトに自動で投稿させたいです。 また、そのAサイトの記事を更新したらBサイトで自動生成された記事も更新されるようにしたいです。 今の段階でのソースです。 ``` global $wpdb; $results = $wpdb->get_results(" SELECT post\_title FROM wp\_posts "); foreach ($results as $post) { $page_exists = $post->post_title; } //その他DB接続設定 $another_db_user = 'user'; $another_db_pass = 'pass'; $another_db_name = 'name'; $another_db_host = 'localhost'; $another_tb_prefix = 'wp\_'; $mydb = new wpdb($another_db_user,$another_db_pass,$another_db_name,$another_db_host); $mydb->set_prefix($another_tb_prefix); //一覧情報取得 $result = $mydb->get_results(" SELECT m0.post\_title, m0.id, m0.post\_name, m0.guid FROM ( select post\_title, id, guid, post\_name from wp\_posts where post\_type = 'bio' AND post\_status = 'publish' ) AS m0 "); foreach ($result as $value) { if( $value->post_title == $page_exists ) { //何もしない } else { $my_access = Array( 'post\_author' => '1', 'post\_title' => ''.$value->post_title.'', 'post\_status' => 'publish', 'comment\_status' => 'closed', 'ping\_status' => 'closed', 'post\_name' => ''.$value->post_name.'', 'post\_type' => 'page', 'post\_parent' => '115822', 'page\_template' => 'template-profile-info.php' ); wp_insert_post($my_access); } } ``` **これだと記事は重複されて繰り返し自動投稿します。** ### 別のソースの案 ``` $this_posts = get_posts( array( 'post\_type' => 'page', 'page\_template' => 'template-profile-info.php' ) ); $this_post_titles = wp_list_pluck( $this_posts, 'post\_title' ); // set the DB creds $another_db_user = 'user'; $another_db_pass = 'pass'; $another_db_name = 'name'; $another_db_host = 'localhost'; $another_tb_prefix = 'wp\_'; // setup the DB connection $mydb = new wpdb( $another_db_user, $another_db_pass, $another_db_name, $another_db_host ); $mydb->set_prefix( $another_tb_prefix ); //一覧情報取得 $result = $mydb->get_results(" SELECT m0.post\_title, m0.id, m0.post\_name, m0.guid FROM ( select post\_title, id, guid, post\_name from wp\_posts where post\_type = 'bio' AND post\_status = 'publish' ) AS m0 "); foreach ( $result as $value ) { if ( in_array( $value->post_title, $this_post_titles ) ) { } else { $my_access = array( 'post\_author' => '1', 'post\_title' => $value->post_title, 'post\_status' => 'publish', 'comment\_status' => 'closed', 'ping\_status' => 'closed', 'post\_name' => $value->post_name, 'post\_type' => 'page', 'post\_parent' => '115822', 'page\_template' => 'template-profile-info.php' ); wp_insert_post( $my_access ); } } ``` ### さらに別のソースの案 ``` function wpse\_20160318\_do\_db\_sync() { // query the DB global $wpdb; $result = $wpdb->get_results( " SELECT post\_name FROM wp\_posts WHERE post\_status = 'publish' AND post\_type = 'page' " ); // for all the results, let's check against the slug. foreach ( $result as $r ) { // see if we can find it... $post = get_page_by_path( $r->post_name ); } // set the DB creds $another\_db\_user = 'user'; $another\_db\_pass = 'pass'; $another\_db\_name = 'name'; $another\_db\_host = 'localhost'; $another\_tb\_prefix = 'wp\_'; // setup the DB connection $mydb = new wpdb( $another\_db\_user, $another\_db\_pass, $another\_db\_name, $another\_db\_host ); $mydb->set_prefix( $another\_tb\_prefix ); //一覧情報取得 $results = $mydb->get_results(" SELECT m0.post\_title, m0.id, m0.post\_name, m0.guid FROM ( select post\_title, id, guid, post\_name from wp\_posts where post\_type = 'bio' AND post\_status = 'publish' ) AS m0 "); foreach ( $results as $value ) { if ( ! $post ) { // We're cool, let's create this one. $my\_access = Array( 'post\_author' => '1', 'post\_title' => ''.$value->post_title.'', 'post\_status' => 'publish', 'comment\_status' => 'closed', 'ping\_status' => 'closed', 'post\_name' => ''.$value->post_name.'', 'post\_type' => 'page', 'post\_parent' => '115822', 'page\_template' => 'template-profile-info.php' ); wp_insert_post($my\_access); } else { // No need to duplicate this one } } } // using on init to make sure the DB is ready to go add_action( 'init', 'wpse\_20160318\_do\_db\_sync' ); ```
外部のWordpressから読み込んだ記事を別のWordpressに自動で投稿したいです ============================================
teratail.com
2019.43
[ { "text": "自己解決しました。 \n\n\n### 完成したソースはこちらです\n\n\n\n```\nfunction profile_info() {\n\n // set the DB creds\n $another_db_user = 'user';\n $another_db_pass = 'pass';\n $another_db_name = 'name';\n $another_db_host = 'localhost';\n $another_tb_prefix = 'wp\\_';\n\n $another_post_type = 'your\\_post\\_type';\n $another_post_status = 'publish';\n\n $mydb = new wpdb( $another_db_user, $another_db_pass, $another_db_name, $another_db_host );\n $mydb->set_prefix( $another_tb_prefix );\n $result = $mydb->get_results(\n \"\n SELECT ID, post\\_title, post\\_name, guid, post\\_content, post\\_excerpt, post\\_date, post\\_date\\_gmt, post\\_modified, post\\_modified\\_gmt\n FROM wp\\_posts\n WHERE post\\_status = '$another\\_post\\_status'\n AND post\\_type = '$another\\_post\\_type'\n \"\n );\n\n $another_db_post_id_meta_key = 'another\\_db\\_post\\_id';\n\n $post_type = 'page';\n $mods = array (\n 'post\\_status' => 'publish',\n 'post\\_author' => '1',\n 'comment\\_status' => 'closed',\n 'ping\\_status' => 'closed',\n 'page\\_template' => 'your\\_template.php',\n 'post\\_parent' => 'post\\_parent\\_ID',\n 'post\\_type' => $post_type,\n );\n\n foreach ( $result as $r ) {\n\n $post_title = wp_strip_all_tags( $r->post_title );\n\n // see if we can find it by title...\n $post = get_page_by_title( $post_title, OBJECT, $post_type );\n\n if ( ! $post ) {\n\n // title wasn't found... but let's check the meta\n $meta_args = array (\n 'post\\_type' => array ( $post_type ),\n 'meta\\_query' => array (\n array (\n 'key' => $another_db_post_id_meta_key,\n 'compare' => '=',\n 'type' => 'NUMERIC',\n 'value' => $r->ID,\n ),\n ),\n );\n $meta_posts = get_posts( $meta_args );\n\n // set the post to the first item in the list, if it isn't empty\n if ( ! empty( $meta\\_posts ) ) {\n list( $post ) = $meta\\_posts;\n }\n }\n\n\n if ( ! $post ) {\n\n // Can't find the post, let's create this one.\n\n // Data from another DB\n $clone = array (\n 'post_title' => $post\\_title,\n 'post_name' => $r->post\\_name,\n 'post_excerpt' => $r->post\\_excerpt,\n 'post_modified' => $r->post\\_modified,\n 'post_modified_gmt' => $r->post\\_modified\\_gmt,\n );\n\n // Merge with our defaults\n $args = array\\_merge( $clone, $mods );\n\n // create new post\n $post\\_id = wp\\_insert\\_post( $args );\n\n if ( $post\\_id instanceof WP\\_Error ) {\n // failed to create new post\n // wp\\_die( 'Failed to create ' . $post\\_id );\n }\n else {\n // new post created\n $post = get\\_post( $post\\_id );\n\n // add clone tag that we can check later\n add\\_post\\_meta( $post->ID, $another\\_db\\_post\\_id\\_meta\\_key, $r->ID, false );\n }\n }\n else {\n // no need to dup\n }\n }\n}\n// using on init to make sure the DB is ready to go\nadd\\_action( 'init', 'profile_info' );\n```\n", "name": "", "is_accepted": true } ]
ba065ddb7e93c33db8422b92da6637d0
[![イメージ説明](https://teratail-v2.storage.googleapis.com/uploads/contributed_images/ed13f6185ef05487721d6deba3593c51.jpeg)](https://teratail-v2.storage.googleapis.com/uploads/contributed_images/ed13f6185ef05487721d6deba3593c51.jpeg) 添付画像のようなウィンドウ幅によって表示行数とコラム数が変わるフレキシブルなリストをCSSで作りたいのですが、 以下のポイントでどう記述すれば実現できるか思いつかずどなたかアイディアをいただけると嬉しいです。 ・タイトル枠の最後以外は右端が三角の形になる。リストの最後の内容のタイトルには角が無い。 ・内容のボックスの高さは画像は揃えてないが揃えても問題ない。 ``` <!DOCTYPE html> <html lang="ja"> <head> <meta charset="utf-8"> <title>list test</title> <style> li.flex-item1 h1:first-child { padding-left: 1em; border-radius: 5px 0 0 5px; } li.flex-item1 h1::after, li.flex-item1 h1::before { position: absolute; top: 50%; right: -1.5em; margin-top: -1.48em; content: ''; border-top: 1.48em solid transparent; border-bottom: 1.48em solid transparent; border-left: 1.5em solid; } ul { display: flex; padding:0; margin:0; list-style: none; min-width:200px; flex-wrap: wrap; display: flex; flex-direction: row; justify-content: center; align-items: stretch; align-items: flex-start; } li { padding:0; margin:0; background-color:lightgrey; } h1.flex-title{ font-size:110%; background-color: orange; padding:0; margin:0; } .flex-item1 { margin-bottom:20px; } </style> </head> <body> <ul> <li class="flex-item1"> <h1 class="flex-title">Title 1</h1> xxxxxxxxxxxx</br> xxxxxxxxxxx</br> xxxxxxxxxxxxxxxxx</li> <li class="flex-item1"> <h1 class="flex-title">Title 2</h1> xxxxxxxxxxx</li> <li class="flex-item1"> <h1 class="flex-title">Title 3</h1>xxxxxxxxxxx</li> <li class="flex-item1"> <h1 class="flex-title">Title 1</h1> xxxxxxxxxxx</li> <li class="flex-item1"> <h1 class="flex-title">Title 2</h1> xxxxxxxxxxx</li> <li class="flex-item1"> <h1 class="flex-title">Title 3</h1>xxxxxxxxxxx</li> </ul> </body> </html> ```
画像のようなフレックスなリストを作りたい ====================
teratail.com
2020.45
[ { "text": "\n> \n> タイトル枠の最後以外は右端が三角の形になる。リストの最後の内容のタイトルには角が無い。 \n> \n> \n> \n\n\n最後だけにスタイルを設定するには、`:last-child`を使うといいでしょう。 \n\n[:last-child - CSS: カスケーディングスタイルシート | MDN](https://developer.mozilla.org/ja/docs/Web/CSS/:last-child) \n\n\n\n\n---\n\n\n\n> \n> 内容のボックスの高さは画像は揃えてないが揃えても問題ない。 \n> \n> \n> \n\n\n高さを固定にするには、`height`を設定すればよいのでは。 \n\n[height - CSS: カスケーディングスタイルシート | MDN](https://developer.mozilla.org/ja/docs/Web/CSS/height) \n\n\n### 質問の追記にあわせて追記\n\n\n[サンプル](https://jsfiddle.net/Lhankor_Mhy/y3t9ks2o/) \n\nサンプルでは不要なCSSを削っているのでご注意ください。 \n\n\n\n\n---\n\n\n\n> \n> タイトル枠の最後以外は右端が三角の形になる。リストの最後の内容のタイトルには角が無い。 \n> \n> \n> \n\n\n\n```\n li.flex-item1:not(:last-child) h1::after {\n content: '';\n width: 10px;\n display: block;\n background:\n linear-gradient(to bottom left, transparent 45%, white 50%, orange 55%) no-repeat top left/100% 50%,\n linear-gradient(to top left, transparent 45%, white 50%, orange 55%) no-repeat bottom right/100% 50%;\n height: 27px;\n float: right;\n position: relative;\n right: -10px;\n }\n```\n\n\n\n> \n> 内容のボックスの高さは画像は揃えてないが揃えても問題ない。 \n> \n> \n> \n\n\n\n```\n li {\n min-height:200px;\n }\n```\n", "name": "", "is_accepted": true } ]
857283d6b3abbd470266bd54c5143c1e
PHPとGDライブラリを使って画像を加工するスクリプトを書いています。 スクリプトを使ってぼかしのようなエフェクトを施したいのですが、 ``` ImageFilter($im, IMG_FILTER_GAUSSIAN_BLUR); ``` <http://php.net/manual/ja/function.imagefilter.php> だと、画像全体がぼかされてしまいます。 そうではなくて、ユーザが指定した一部の範囲だけぼかしをかけたいのです。 何かいい方法はないでしょうか?
[PHP] GDによる画像の一部へのエフェクト =======================
teratail.com
2021.10
[ { "text": "ちょっとトリッキーですが、画像の特定の範囲を新しい画像としてコピーし、そこにぼかしをかけます。\n \nそしてその結果をマージすればOKです。\n \nだいたい以下のような感じです。\n \n\n \n\n```\n// ぼかし範囲(とりあえずここでは固定値)\n$x = 100;\n$y = 100;\n\n// 画像の幅・縦(とりあえずここでは固定値)\n$w = 1920;\n$h = 1280;\n\n// メイン処理\n$im2 = imagecreate($w, $h);\nimagecopy($im2,$im,0,0,$x,$y,$w,$h);\nimagefilter($im, IMG_FILTER_GAUSSIAN_BLUR);\nimagecopy($im,$im2,$x,$y,0,0,$w,$h);\n\n// 出力\nimagepng($im);\nimagedestroy($im);\n```\n", "name": "", "is_accepted": true } ]
9d6ff64891e19c5ee8a456d794d879df
Googleドライブをよく利用させる方。 Permissionの管理をどうされていますか? 共有ファイルが多くなり、だれと共有したか、効率的に確認する術がありません。 不本意に共有してしまい、大事にならないように管理したいと考えています。 よい管理方法があれば、教えてください。 (既存ツールはなさそうですので、APIを利用しての作りこみが必要なんでしょうかね) ーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーー 無償でDriveを使っています。有償のAPPSであればあるのですかね。
GoogleDriveのPermmision管理について ============================
teratail.com
2021.31
[ { "text": "私の場合、権限毎にフォルダを分けています。\n \n\n \npubulic/Family/Private/部署1/部署2など。ざっくりとした権限で管理する。そうできないものは、短期のファイル共有かファイル共有しないか。\n \n\n \nそれでも管理はめんどくさいので、そもそもpermission管理は面倒臭いんだろうなとあきらめています。 \n", "name": "", "is_accepted": false } ]
ca7baa03f9ad7e57133a2f94946fe7c4
ajaxで以下のように組もうと考えているのですが、 curl -u で指定するように ajaxでもパスワードを指定したいのですが、どうすればいいのでしょうか ``` $.ajax({ type: 'POST', url: '', data: {"app": 999,}, headers: { 'Content-Type': 'application/json', }, }).then(function(response){ console.log(response) }) ```
curlコマンドをajaxで使う際にパスワードを指定したい =============================
teratail.com
2020.50
[ { "text": "[jQueryの公式サイトの`$.ajax()`のページ](http://api.jquery.com/jquery.ajax/)に記載があります。 \n\n\n\n```\n$.ajax({\n username: 'myname',\n password: 'mypassword'\n});\n```\n\n**補足** \n\nちなみに、Google検索で「jquery ajax パスワード」と調べても、日本語で情報がでてきます。 \n\n今回のように、おおよそのキーワードが予想できるときには、一度検索してみると、自力解決できる頻度があがると思います。\n\n", "name": "", "is_accepted": true } ]
bdbf970433bfcd98b42d559a704e0608
### 前提・実現したいこと Asp.net(c#)でOracle databaseをコネクトしてWeb applicationを作っています。(プラットフォームはVisual Studio2015 Communityです) Sql developerでfunctionを作ったので、Web application上でユーザーにテキストボックス入力を促し、ボタンクリックでラベルにfunctionの結果表示をするC#の書き方を知りたいです。 *結果を読み取るのはデータベースに接続したままでも、Adapterを使ってDisconnectした状態でもどちらでも構いません。 ユーザーインターフェースにこだわりはありません。 ### 該当のソースコード **Sql (function)** ``` create or replace function get\_cAccess ( p\_recipeId in number ) return char is access\_type recipe.privateAccess%type; r_access recipe.privateAccess%type; begin select privateAccess into access\_type from recipe where recipe\_id=p\_recipeId; if access_type='Y' then access_type:='N'; elsif access_type='N' then access_type:='Y'; end if; update recipe set privateAccess=access\_type where recipe\_id=p\_recipeId returning privateAccess into r\_access; return r_access; end; ``` --- **Asp.netのcode behind file(C#)(抜粋)** ``` protected void Button1\_Click(object sender, EventArgs e) { using (OracleConnection conn = new OracleConnection("RecipeConnectionString")) { using (OracleCommand cmd = new OracleCommand("get\_cAccess", conn)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add("@p\_recipeId", OracleDbType.Int32).Value = TextBox1.Text; cmd.Parameters.Add("@access\_r", OracleDbType.Char, 1).Direction = ParameterDirection.Output; conn.Open(); cmd.ExecuteNonQuery(); conn.Close(); Label1.Text = "Your recipe's accesstype is private 'Y': public 'N' : " + cmd.Parameters["@access\_r"].Value.ToString(); } } } } ``` ### 前提・実現したいこと ここに質問したいことを詳細に書いてください (例)PHP(CakePHP)で●●なシステムを作っています。 ■■な機能を実装中に以下のエラーメッセージが発生しました。 ### 発生している問題・エラーメッセージ ``` Webアプリケーションは表示されるのですが、P_recipeIdを入力してボタンをクリックすると、cmd.ExecuteNonQueryのところに「Oracle exception was unhandled by user 」が出ます。ちなみにWeb.configのConnectionString名は'recipeConnectionString'です。サーバーにはつながっています。あと、同じページに表示したGridviewの中のデータなどもきちんと表示されております。Functionは完成していて、Sql developer上でP_recipeIdをインプットするとr_accessはきちんとアップデートされます。 ```
Webアプリケーションにfunctionの結果表示をするC#の書き方(Asp.net, Oracle) ===================================================
teratail.com
2020.34
[ { "text": "回答していただいたみなさまありがとうございました。 \n\n今日プロフェッサーに聞いたところ、OracleはパラメーターにAddする時に一回一回変数を宣言しないといけないとのことでした。(ロジックはわからないそうです) \n\n\n\n```\nprotected void Button1\\_Click(object sender, EventArgs e)\n {\n try\n {\n string connString = ConfigurationManager.ConnectionStrings[\"RecipeConnectionString\"].ConnectionString;\n\n OracleConnection conn = new OracleConnection(connString);\n\n OracleCommand cmd = new OracleCommand();\n cmd.Connection = conn;\n\n cmd.CommandType = CommandType.StoredProcedure;\n cmd.CommandText = \"get\\_cAccess\";\n cmd.BindByName = true;\n\n cmd.Parameters.Add(\"p\\_recipeId\", OracleDbType.Int16, ParameterDirection.Input).Value = Convert.ToInt16(TextBox1.Text);\n OracleParameter newpara=cmd.Parameters.Add(\"r\\_access\", OracleDbType.Char, ParameterDirection.ReturnValue);\n newpara.Size = 1;\n conn.Open();\n using (var dr = cmd.ExecuteReader())\n {\n Label1.Text = cmd.Parameters[\"r\\_access\"].Value.ToString();\n }\n conn.Close();\n }\n catch (Exception ex)\n {\n Label1.Text = \"Connection doesn't open\";\n }\n}\n```\n\n \n\n全体的にコードを変えましたが、問題となるのは \n\n\n\n```\nOracleParameter newpara=cmd.Parameters.Add(\"r\\_access\", OracleDbType.Char, ParameterDirection.ReturnValue);\n newpara.Size = 1;\n```\n\n \n\nここで、SqlClientだと \n\n\n\n```\ncmd.Parameters.Add(\"r\\_access\", OracleDbType.Char....);\n```\n\n \n\nで良かったんですが、オラクルだとなぜかダメだということでした。\n\n", "name": "", "is_accepted": true } ]
fa57a17cd0ba18f621661cbee790bdfa
### 前提・実現したいこと Pythonのseleniumでチェックボックスにチェックを入れたいのですが、 うまくいきません。。。 追記 ``` test = driver.find_element_by_id('mypage\_setting\_proids\_1') print(test.is_selected()) ``` こんな感じでやるとFalseが取得できるので、 要素は上記でいいはずなのですが、チェック(クリック)ができません。。。。 ### 発生している問題・エラーメッセージ ``` selenium.common.exceptions.ElementNotInteractableException: Message: element not interactable (Session info: chrome=80.0.3987.149) ``` ### 該当のソースコード チェックしたいチェックボックスのHTMLは以下です。 テスト1にチェックを入れたいです。 ``` <form method="post" id="mypageSettingForm" action="https://~~"> <legend>テスト</legend> <div class="form-group proids"> <input type="checkbox" name="proids[]" id="mypage\_setting\_proids\_1" value="1" /> <label for="mypage\_setting\_proids\_1">テスト1</label> <input type="checkbox" name="proids[]" id="mypage\_setting\_proids\_2" value="2" /> <label for="mypage\_setting\_proids\_2">テスト2</label> <input type="checkbox" name="proids[]" id="mypage\_setting\_proids\_3" value="3" /> <label for="mypage\_setting\_proids\_3">テスト3</label> <input type="checkbox" name="proids[]" id="mypage\_setting\_proids\_4" value="4" /> <label for="mypage\_setting\_proids\_4">テスト4</label> <input type="checkbox" name="proids[]" id="mypage\_setting\_proids\_5" value="5" /> </form> ``` 取得用ソースは以下です。 ``` driver.find_element_by_id('mypage\_setting\_proids\_1').click() ``` ### 試したこと xpathにしたり、find\_element\_by\_css\_selectorでチェックしようとしたりしたのですが、 うまくチェックができません。 ### 補足情報(FW/ツールのバージョンなど) Pytgon3.7
Pythonのseleniumでチェックボックスにチェックを入れたい ==================================
teratail.com
2020.16
[ { "text": "driver.execute\\_script(\"arguments[0].click();\", driver.find\\_element\\_by\\_id(\"mypage\\_setting\\_proids\\_1\")) \n\n\n上記のやり方で解決できました!\n\n", "name": "", "is_accepted": true } ]
6e289408d56f464125e48d5591ec84ca
**unityでの、sendinputが上手に動作しません。unityのexeファイルを作成し、 exeを起動してwindowsへキーストローク出力がしたい。 できるだけ簡単に実装したい。** ### keybd\_eventではスクリプトでのキーストロークの検知はできたが、exeに落とし込んでキーストロークの出力を試したが反応なし。 keybd\_eventでの使用は推奨されていないのでsendinputでの実装を考えたが、 exeファイルの作り方がおかしかったのでkeybd\_eventの出力ができなかったのかなとも未だにわだかまりが。 今回はunityでのsendinputの実装を可能にしたい。 **unityでの参考書物があれば教えていただきたい。unity以外は読みつくしたと思う。 回答お願いします。** ### できれば完全に動くコードが欲しい。 ``` using System.Collections; using System.Collections.Generic; using UnityEngine; using System.Runtime.InteropServices; public class check1 : MonoBehaviour { [DllImport("user32.dll")] private extern static void SendInput(uint nInputs, ref INKey pInputs , int cbsize); [StructLayout(LayoutKind.Sequential)] private struct KEYBDINPUT { public byte wVk; public short wScan; public int dwFlags; public int time; public int dwExtraInfo; }; [StructLayout(LayoutKind.Sequential)] struct INKey { public int type; // 0 = INPUT\_MOUSE, // 1 = INPUT\_KEYBOARD, // 2 = INPUT\_HARDWARE public KeyIN ks; } [StructLayout(LayoutKind.Explicit)] private struct KeyIN { [FieldOffset(0)] public KEYBDINPUT ki; }; private const int INPUT_KEYBOARD = 0x1; [DllImport("user32.dll", EntryPoint = "MapVirtualKeyA")] private extern static int MapVirtualKey( int wCode, int wMapType); // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { if (Input.GetKeyDown(KeyCode.K)) { Debug.Log("押した"); const int num = 2; INKey[] ingo = new INKey[num]; ingo[0].type = INPUT_KEYBOARD; ingo[0].ks.ki.wVk = 0x41; ingo[0].ks.ki.wScan = 0x4; ingo[0].ks.ki.dwFlags = 0x1 | 0x0; SendInput(num, ref ingo[0], Marshal.SizeOf(ingo[0])); if (Input.GetKey(KeyCode.A)) { Debug.Log("記念日"); ingo[1].type = INPUT_KEYBOARD; ingo[1].ks.ki.wVk = 0x41; ingo[1].ks.ki.wScan = 0x4; ingo[1].ks.ki.dwFlags = 0x1 | 0x2; SendInput(num, ref ingo[0], Marshal.SizeOf(ingo[0])); } } } } ```
unityでのsendinput ================
teratail.com
2021.10
[ { "text": "原因は32bitと64bitの構造体アラインの違いみたいです。 \n\n細かく見てないですが、WIN32API呼び出し系はpinvoke.netのをパクると手堅いです。 \n\n\n定義例 \n\n\n\n```\n[StructLayout(LayoutKind.Sequential)]\nstruct MOUSEINPUT\n{\n public int dx;\n public int dy;\n public uint mouseData;\n public uint dwFlags;\n public uint time;\n public IntPtr dwExtraInfo;\n}\n\n[StructLayout(LayoutKind.Sequential)]\nstruct KEYBDINPUT\n{\n public ushort wVk;\n public ushort wScan;\n public uint dwFlags;\n public uint time;\n public IntPtr dwExtraInfo;\n}\n\n[StructLayout(LayoutKind.Sequential)]\nstruct HARDWAREINPUT\n{\n public int uMsg;\n public short wParamL;\n public short wParamH;\n}\n\n[StructLayout(LayoutKind.Explicit)]\nstruct MouseKeybdHardwareInputUnion\n{\n [FieldOffset(0)]\n public MOUSEINPUT mi;\n\n [FieldOffset(0)]\n public KEYBDINPUT ki;\n\n [FieldOffset(0)]\n public HARDWAREINPUT hi;\n}\n\n[StructLayout(LayoutKind.Sequential)]\nstruct INPUT\n{\n public uint type;\n public MouseKeybdHardwareInputUnion mkhi;\n}\n\n/// <summary>\n/// Synthesizes keystrokes, mouse motions, and button clicks.\n/// </summary>\n[DllImport(\"user32.dll\")]\nstatic extern uint SendInput(uint nInputs,\n [MarshalAs(UnmanagedType.LPArray), In] INPUT[] pInputs,\n int cbSize);\n```\n\n'A'を押して離す使用例 \n\n\n\n```\nkeyInput.type = 1;\n\nkeyInput.mkhi.ki.wScan = 0;\nkeyInput.mkhi.ki.time = 0;\nkeyInput.mkhi.ki.dwFlags = (int)1; // KEYDOWN相当\nkeyInput.mkhi.ki.dwExtraInfo = (IntPtr)0; // 面倒だったので適当。本当はGetMessageExtraInfo();\nkeyInput.mkhi.ki.wVk = (ushort)65; // 仮想キーコードA\n\nInputList[0] = keyInput;\n\nkeyInput.mkhi.ki.dwFlags = (int)3; // KEYUP相当\n\nInputList[1] = keyInput;\n\nSendInput((uint)2, InputList, Marshal.SizeOf(InputList[0]));\n```\n\n参考リンク \n\n<https://stackoverflow.com/questions/6830651/sendinput-and-64bits>\n\n", "name": "", "is_accepted": true }, { "text": "wwbQzhMkhhgEmhUさんとのやりとりを聞いた限りでは、Unityでやる意味は無いように感じられます。 \n\n同じゲームではないかと思っているかもしれませんが、Unityは表示や当たり判定などの処理を行うものであり、マウスのマクロ機能(ですよね?)を作るのには、むしろ足枷になります。\n\n", "name": "", "is_accepted": false } ]
50ef52f1d07cb4e9d7e1b300a064f33e
### 前提・実現したいこと module Kazをmodule Test2にincludeして 名前を小文字で出力したい。 ### 発生している問題・エラーメッセージ 現状では、Classにincludeすれば予想通りに小文字(”car”)が出力されるが、 moduleにincludeすると大文字(”Car”)で標示される。 ### 該当のソースコード ``` module Kaz listA = ["Car", "Train"] # method generate listA.each do |c| define\_method "#{c}" do eval "#{c}.new" end end # class generate listA.each do |vahi| Object.const\_set vahi, Class.new(){ attr\_accessor :name def initialize @name = self.class.name.downcase end } end end class Test include Kaz end a = Test.new p a.Car.name => "car" module Test2 include Kaz p Car.name=> "Car" end ``` ### 補足情報(言語/FW/ツール等のバージョンなど) ruby 2.4.0p0 (2016-12-24 revision 57164) [x86\_64-darwin16]
Moduleにincludeする場合とClassにincludeする場合で、結果が違うのだが、どうしてかな? ======================================================
teratail.com
2019.43
[ { "text": "`a.Car.name`では、`a.Car`という**メソッド呼び出し**であり、Test2モジュールの中の`Car.name`は`Car`という**定数呼び出し**です。KazモジュールにはCarという定数※とCarというインスタンスメソッドの**同じ名前で違うもの**が同時に存在し、定数のCarはCarという**クラス**で、メソッド呼び出しはCarをnewした**インスタンス**です。クラスにはデフォルトで`name`メソッドがあり、自分の名前(クラス名)を返すので、どちらもエラーになりません。`name`の代わりに`class`とすると何のクラスのオブジェクトなのかがよくわかると思います。 \n\n\n※ Car定数が定義されているのはObjectですが、定数参照により辿り着くことができるため、全ての場所にCar定数が存在することになります。 \n\n\nより単純化した、下記のコードで説明します。 \n\n\n\n```\nmodule M\n def X\n 1\n end\n X = 0\nend\n\nclass A\n include M\nend\na = A.new\np a.X\n\nmodule B\n include M\n p X\nend\n```\n\nMモジュールには二つの`X`が存在します。 \n\n\n* Xメソッド … 1を返す\n* X定数 ... 0\n\n\nAクラスもBモジュールもMモジュールをincludeしていますので、上と同じようにXメソッドとX定数が定義されます。(Xメソッドはインスタンスメソッドであることに注意してください) \n\n\n`a.X`としたとき、`.`があるため、Xはaのメソッド呼び出しとして解釈されます。`a`はAクラスのインスタンスなので、Aクラスのメソッドを探します。ちょうどincludeしたMモジュールにXメソッドありましたので、それを使って`1`を返します。 \n\n\n`X`としたとき、`.`とかがなく大文字から始まるため、Xは定数呼び出しとして解釈されます。[定数参照の優先順位](https://docs.ruby-lang.org/ja/latest/doc/spec=2fvariables.html#prio)に従って探し、includeしたMモジュールにX定数がありましたので、それを使って`0`を返します。 \n\n\n通常※、メソッド名を大文字から始めることは推奨されていませんので、このような混乱を起こすことはほとんどありません。 \n\n\n※ `String(1)`のようなクラス名関数という考え方があるため、大文字から始まるメソッド名が絶対に悪いわけではありません。\n\n", "name": "", "is_accepted": true } ]
886bc56499746b20c2c1f888096fa499
前提 == いろいろな参考サイトを閲覧して、Dockerfile docker-compose.yml Gemfileを生成。 実行コマンド ====== $ docker-compose run web bundle exec rails new . --force --database=mysql --skip-bundle $ docker-compose build $ docker-compose up -d 試行錯誤したこと ======== * キャッシュが貯まるという記事を得て実行 docker-compose build --no-cache にてコマンドを実行してみた * このコマンドを実行したら良いという情報を得て実行RUN gem install mysql2 -v '0.5.2' --source 'https://rubygems.org/' -- --with-cppflags=-I/usr/local/opt/openssl/include --with-ldflags=-L/usr/local/opt/openssl/lib * mysql-devel が必要ということで、RUN apt-get 時に mysql-develを実行 結果エラーになりました。「E: Unable to locate package mysql-devel」 --- ファイル内容 ====== Dockerfile docker-compose.yml Gemfileはそれぞれ下記に記載しております。 ``` FROM ruby:2.6.5 ENV LANG C.UTF-8 RUN apt-get update -qq && apt-get install -y \ build-essential \ nodejs \ mysql-devel \ && rm -rf /var/lib/apt/lists/* RUN gem install bundler WORKDIR /tmp ADD Gemfile Gemfile ADD Gemfile.lock Gemfile.lock RUN bundle update RUN bundle config --local build.mysql2 "--with-ldflags=-L/usr/local/opt/openssl/lib --with-cppflags=-I/usr/local/opt/openssl/include" RUN bundle install --path=vendor/bundle RUN gem update ENV APP_HOME /myapp RUN mkdir -p $APP\_HOME WORKDIR $APP\_HOME ADD . $APP\_HOME ``` ``` version: '3' services: web: build: . ports: - "3000:3000" command: bundle exec rails s -p 3000 -b '0.0.0.0' volumes: - .:/myapp - bundle:/usr/local/bundle depends\_on: - db db: image: mysql:5.7 environment: MYSQL\_ROOT\_PASSWORD: password ports: - '3306:3306' volumes: - mysql\_data:/var/lib/mysql volumes: bundle: mysql\_data: ``` ``` source 'https://rubygems.org' git_source(:github) { |repo| "https://github.com/#{repo}.git" } ruby '2.6.5' # Bundle edge Rails instead: gem 'rails', github: 'rails/rails' gem 'rails', '~> 6.0.0' # Use mysql as the database for Active Record gem 'mysql2', '>= 0.4.4' # Use Puma as the app server gem 'puma', '~> 3.11' # Use SCSS for stylesheets gem 'sass-rails', '~> 5' # Transpile app-like JavaScript. Read more: https://github.com/rails/webpacker gem 'webpacker', '~> 4.0' # Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks gem 'turbolinks', '~> 5' # Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder gem 'jbuilder', '~> 2.7' # Use Redis adapter to run Action Cable in production # gem 'redis', '~> 4.0' # Use Active Model has\_secure\_password # gem 'bcrypt', '~> 3.1.7' # Use Active Storage variant # gem 'image\_processing', '~> 1.2' # Reduces boot times through caching; required in config/boot.rb gem 'bootsnap', '>= 1.4.2', require: false group :development, :test do # Call 'byebug' anywhere in the code to stop execution and get a debugger console gem 'byebug', platforms: [:mri, :mingw, :x64\_mingw] end group :development do # Access an interactive console on exception pages or by calling 'console' anywhere in the code. gem 'web-console', '>= 3.3.0' gem 'listen', '>= 3.0.5', '< 3.2' # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring gem 'spring' gem 'spring-watcher-listen', '~> 2.0.0' end group :test do # Adds support for Capybara system testing and selenium driver gem 'capybara', '>= 2.15' gem 'selenium-webdriver' # Easy installation and use of web drivers to run system tests with browsers gem 'webdrivers' end # Windows does not include zoneinfo files, so bundle the tzinfo-data gem gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64\_mingw, :jruby] ```
DockerでRuby on Rails環境を構築中に「not find gem mysql2」でハマっています ========================================================
teratail.com
2021.43
[ { "text": "mysql-develというパッケージが存在しないためです。 \n\nDockerのruby:2.6.5のイメージはDebian busterがベースなので、インストールするパッケージはdefault-libmysqlclient-devではないかと思われます。 \n\n", "name": "", "is_accepted": true }, { "text": "これは試されましたでしょうか \n\n\nUbuntuでUnable to locate packageのエラー解決法 \n\n<https://qiita.com/hatorijobs/items/c503840c13672e12d188>\n\n", "name": "", "is_accepted": false } ]
80bc9a1822924026ca0000b77cef6706
Cetos7をVirtualBox上で動かして yum update yum install xxx を試してみたところ 下記エラーが出力され、実行できません。 ``` 読み込んだプラグイン:fastestmirror base | 3.6 kB 00:00:00 extras | 3.4 kB 00:00:00 http://ftp.riken.jp/Linux/centos/7/updates/x86_64/repodata/repomd.xml: [Errno 12] Timeout on http://ftp.riken.jp/Linux/centos/7/updates/x86_64/repodata/repomd.xml: (28, 'Operation too slow. Less than 1000 bytes/sec transferred the last 30 seconds') 他のミラーを試します。 http://ftp.riken.jp/Linux/centos/7/updates/x86_64/repodata/repomd.xml: [Errno 12] Timeout on http://ftp.riken.jp/Linux/centos/7/updates/x86_64/repodata/repomd.xml: (28, 'Operation too slow. Less than 1000 bytes/sec transferred the last 30 seconds') 他のミラーを試します。 http://ftp.riken.jp/Linux/centos/7/updates/x86_64/repodata/repomd.xml: [Errno 12] Timeout on http://ftp.riken.jp/Linux/centos/7/updates/x86_64/repodata/repomd.xml: (28, 'Operation too slow. Less than 1000 bytes/sec transferred the last 30 seconds') 他のミラーを試します。 ・ ・ ・ 他のミラーを試します。 http://ftp.riken.jp/Linux/centos/7/updates/x86_64/repodata/repomd.xml: [Errno 12] Timeout on http://ftp.riken.jp/Linux/centos/7/updates/x86_64/repodata/repomd.xml: (28, 'Operation too slow. Less than 1000 bytes/sec transferred the last 30 seconds') 他のミラーを試します。 One of the configured repositories failed (CentOS-7 - Updates), and yum doesn't have enough cached data to continue. At this point the only safe thing yum can do is fail. There are a few ways to work "fix" this: 1. Contact the upstream for the repository and get them to fix the problem. 2. Reconfigure the baseurl/etc. for the repository, to point to a working upstream. This is most often useful if you are using a newer distribution release than is supported by the repository (and the packages for the previous distribution release still work). 3. Run the command with the repository temporarily disabled yum --disablerepo=updates ... 4. Disable the repository permanently, so yum won't use it by default. Yum will then just ignore the repository until you permanently enable it again or use --enablerepo for temporary usage: yum-config-manager --disable updates or subscription-manager repos --disable=updates 5. Configure the failing repository to be skipped, if it is unavailable. Note that yum will try to contact the repo. when it runs most commands, so will have to try and fail each time (and thus. yum will be be much slower). If it is a very temporary problem though, this is often a nice compromise: yum-config-manager --save --setopt=updates.skip\_if\_unavailable=true failure: repodata/repomd.xml from updates: [Errno 256] No more mirrors to try. http://ftp.riken.jp/Linux/centos/7/updates/x86_64/repodata/repomd.xml: [Errno 12] Timeout on http://ftp.riken.jp/Linux/centos/7/updates/x86_64/repodata/repomd.xml: (28, 'Operation too slow. Less than 1000 bytes/sec transferred the last 30 seconds') http://ftp.riken.jp/Linux/centos/7/updates/x86_64/repodata/repomd.xml: [Errno 12] Timeout on http://ftp.riken.jp/Linux/centos/7/updates/x86_64/repodata/repomd.xml: (28, 'Operation too slow. Less than 1000 bytes/sec transferred the last 30 seconds') ・ ・ ・ ・ http://ftp.riken.jp/Linux/centos/7/updates/x86_64/repodata/repomd.xml: (28, 'Operation too slow. Less than 1000 bytes/sec transferred the last 30 seconds') http://ftp.riken.jp/Linux/centos/7/updates/x86_64/repodata/repomd.xml: [Errno 12] Timeout on http://ftp.riken.jp/Linux/centos/7/updates/x86_64/repodata/repomd.xml: (28, 'Operation too slow. Less than 1000 bytes/sec transferred the last 30 seconds') ``` [やってみたこと] ・DNSの設定 → 8.8.8.8 ・デフォルトゲートウェイの設定 ・CentOS-Base.repoを下記のようにbaseurlを変更後 yum clean all ``` # CentOS-Base.repo # # The mirror system uses the connecting IP address of the client and the # update status of each mirror to pick mirrors that are updated to and # geographically close to the client. You should use this for CentOS updates # unless you are manually picking other mirrors. # # If the mirrorlist= does not work for you, as a fall back you can try the # remarked out baseurl= line instead. # # [base] name=CentOS-$releasever - Base #mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=os&infra=$infra #baseurl=http://mirror.centos.org/centos/$releasever/os/$basearch/ baseurl=http://ftp.riken.jp/Linux/centos/$releasever/os/$basearch/ gpgcheck=1 gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7 #released updates [updates] name=CentOS-$releasever - Updates #mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=updates&infra=$infra #baseurl=http://mirror.centos.org/centos/$releasever/updates/$basearch/ baseurl=http://ftp.riken.jp/Linux/centos/$releasever/updates/$basearch/ gpgcheck=1 gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7 #additional packages that may be useful [extras] name=CentOS-$releasever - Extras #mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=extras&infra=$infra #baseurl=http://mirror.centos.org/centos/$releasever/extras/$basearch/ baseurl=http://ftp.riken.jp/Linux/centos/$releasever/extras/$basearch/ gpgcheck=1 gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7 #additional packages that extend functionality of existing packages [centosplus] name=CentOS-$releasever - Plus #mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=centosplus&infra=$infra #baseurl=http://mirror.centos.org/centos/$releasever/centosplus/$basearch/ baseurl=http://ftp.riken.jp/Linux/centos/$releasever/centosplus/$basearch/ gpgcheck=1 enabled=0 gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7 ``` pingによるインターネットへの疎通は正常に行えます。 ``` ping google.com PING google.com (216.58.199.238) 56(84) bytes of data. 64 bytes from kix05s02-in-f238.1e100.net (216.58.199.238): icmp_seq=1 ttl=54 time=8.46 ms 64 bytes from kix05s02-in-f238.1e100.net (216.58.199.238): icmp_seq=2 ttl=54 time=10.7 ms 64 bytes from kix05s02-in-f238.1e100.net (216.58.199.238): icmp_seq=3 ttl=54 time=4.84 ms ping yahoo.com PING yahoo.com (72.30.35.10) 56(84) bytes of data. 64 bytes from media-router-fp2.prod1.media.vip.bf1.yahoo.com (72.30.35.10): icmp_seq=1 ttl=44 time=189 ms 64 bytes from media-router-fp2.prod1.media.vip.bf1.yahoo.com (72.30.35.10): icmp_seq=2 ttl=44 time=187 ms 64 bytes from media-router-fp2.prod1.media.vip.bf1.yahoo.com (72.30.35.10): icmp_seq=3 ttl=44 time=187 ms ``` [環境] ・ホストOS Windows Server 2012 R2 Standard ・VirtualBox 5.2.8 [ブリッジ接続] ・ゲストOS CentOS Linux release 7.4.1708 (Core) ご教示のほど宜しくお願い致します。
Cetnos7 yum が使えない =================
teratail.com
2019.43
[ { "text": "CentOS-Base.repoのbaseurlを \n\nhttp://ftp.riken.jp/Linux/centos/$releasever/xxxx/$basearch/ではなく \n\nftp://ftp.riken.jp/Linux/centos/$releasever/xxxx/$basearch/にしたところ \n\nとりあえずの問題解決。 \n\n\n[補足] \n\ncurl http://ftp.riken.jp/Linux/centos/ は失敗 curl: (52) Empty reply from server \n\ncurl http://ftp.riken.jp/Linux/ は成功  \n\ncurl ftp://ftp.riken.jp/Linux/centos/ は成功 \n\nホストOSのブラウザでhttp://ftp.riken.jp/Linux/centos/は表示可能 \n\n\n理研のサーバーがプロトコル(HTTP)ではじく仕様ならブラウザでも表示できないはず。。謎です。。。 \n\n\n[2018/04/24追記] \n\n上記でもyumが正常に動作しないことがありました。 \n\nVirtualBoxのネットワーク設定をブリッジ接続からNATに変更したところ正常な動作を確認しました。 \n\n※CentOS-Base.repoの内容はすべて初期状態に戻しました。 \n\nブリッジ接続により他の通信と干渉していたのか等々は現在追求中です。\n\n", "name": "", "is_accepted": true } ]
35f720b7bdcc8a439b86c124eb1b0831
お世話になっております。 ただいまLaravel Homesteadの環境構築を行っております。 こちらのサイトを参考にさせていただいてます。 <http://foresta.me/?p=74> 端的に申し上げますと「homestead up」でvagrantを立ち上げる際にエラーが発生します。 ``` [エラー] Bringing machine 'default' up with 'virtualbox' provider... There are errors in the configuration of this machine. Please fix the following errors and try again: shell provisioner: * Shell provisioner `args` must be a string or array. ``` 同じような事象が発生した方や、エラーに検討がつく方がいましたら、知恵をお借りしたいです。 Googleでエラー内容を検索したりしましたが、解決できませんでした。 よろしくお願い致します。 以下に補足として情報を記載しておきます。 ・PC:mac ・virtual boxのバージョン:5.0.4 ・vagrantのバージョン:1.7.4 ・laravel homesteadのバージョン:2.1.8 ・OS:Ubuntu (14.04.3 LTS) ・「vagrant up」でも同じエラーが出る ・「vagrant list」「homestead list」は問題なく実行できる ・homestead.yamlは以下の記述です。 ``` --- ip: "192.168.10.10" memory: 2048 cpus: 1 provider: virtualbox authorize: ~/.ssh/id_rsa.pub key: - ~/.ssh/id_rsa folders: - map: /Users/my_user_name/my_cookbook/work/laravel to: /home/vagrant/Code/laravel sites: - map: homestead.app to: /home/vagrant/Code/laravel/public ``` ・VagrantFileは以下の記述です。 ``` require 'json' require 'yaml' VAGRANTFILE_API_VERSION = "2" confDir = $confDir ||= File.expand_path("~/.homestead") homesteadYamlPath = confDir + "/Homestead.yaml" homesteadJsonPath = confDir + "/Homestead.json" afterScriptPath = confDir + "/after.sh" aliasesPath = confDir + "/aliases" require File.expand_path(File.dirname(__FILE__) + '/scripts/homestead.rb') Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|     if File.exists? aliasesPath then         config.vm.provision "file", source: aliasesPath, destination: "~/.bash_aliases"     end     if File.exists? homesteadYamlPath then         Homestead.configure(config, YAML::load(File.read(homesteadYamlPath)))     elsif File.exists? homesteadJsonPath then         Homestead.configure(config, JSON.parse(File.read(homesteadJsonPath)))     end     if File.exists? afterScriptPath then         config.vm.provision "shell", path: afterScriptPath     end end ```
Laravel Homesteadの環境構築をしたが「homestead up」ができない =============================================
teratail.com
2021.25
[ { "text": "自己解決しました。\n \nyamlファイルで設定しているpathが違ったようです。\n \n\"create project\"で作成したlaravelのプロジェクトを参照しなければならないのに、自分で勝手に作った(mkdir)空のディレクトリを参照しておりました。\n \n\n \n「folders:」で設定しなければいけないpathの私の認識不足による問題でした。。。\n \nmap:は、共有フォルダ(自分でつくるもの)だと思っていた。\n \n\n \n[homestead.yaml]\n \n\n```\n[修正箇所抜粋]\nfolders:\n× - map: /Users/my_user_name/my_cookbook/work/laravel\n◯ - map: /Users/my_user_name/my_cookbook/laravel\n× to: /home/vagrant/Code/laravel\n◯ to: /home/vagrant/laravel\n\nsites:\n- map: homestead.app\n× to: /home/vagrant/Code/laravel/public\n◯ to: /home/vagrant/laravel/public\n```\n", "name": "", "is_accepted": true } ]
a244d6cd26f753b89f229abac3f3d2ba
現在PHPの勉強をしている初心者のものです。 基礎的な問題なのかもしれないのですが調べても分からなかった為、質問をさせてください。 【目的】 CSRF対策を実装したいです。 【実行した事】 ドットインストールやネットで調べた事を参考にして CSRF対策を行っているコードを書いてみました。 【問題点】 $\_SESSION['token']と$\_POST['token'] をチェックする時に$\_POST['token']をvar\_dump($\_POST['token'])をした所、 ``` Notice: Undefined index: token NULL ``` と表示されました。 --- 【問題のコードです】 **【otoiawase1.php】** ``` <?php session_start(); ?> ``` ``` <span>お問い合わせ</span> <div class="otoiawase-box" style="padding:30px"> <form class="form-horizontal" action="otoiawase2.php" method="post" style="margin-bottom:15px;"> <div class="form-group"> <label class="control-label" for="email">お名前</label> <input type="text" name="toiawase\_name" class="form-control" placeholder="お名前"> </div> <div class="form-group"> <label class="control-label" for="email">Email</label> <input type="email" name="toiawase\_email" class="form-control" required placeholder="Email"> </div> <div class="form-group"> <label class="control-label" for="email">内容</label> <textarea name="toiawase\_body" class="form-control" maxlength="1000" minlength="5" required cols=40 rows=10></textarea> </div> <div class="form-group"> <input type="submit" value="送信" class="btn btn-primary"> </div> </form> </div> <input type="hidden" name="token" value="<?= $\_SESSION['token']; ?>"> ``` 【otoiawase2.php】 ``` session_start(); try { $db = new \PDO(DSN, DB_USERNAME, DB_PASSWORD); $db->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); echo "データベースへの接続が出来ました"; }catch (\PDOException $e) { echo $e->getMessage(); exit; } if (!isset($_SESSION['token'])) { $_SESSION['token'] = bin2hex(openssl_random_pseudo_bytes(16)); } var_dump($_SESSION['token']); var_dump($_POST['token']); if ( !isset($_SESSION['token']) || !isset($_POST['token']) || $_SESSION['token'] !== $_POST['token'] ) { throw new \Exception('不正なトークンを使用しています。'); } $otoiawasename = $_POST['toiawase\_name']; $otoiawaseemail = $_POST['toiawase\_email']; $otoiawasebody = $_POST['toiawase\_body']; $sql = "insert into otoiawase (name, mail, otoiawase, created) values (:name,:mail,:otoiawase,now()) ON DUPLICATE KEY UPDATE created = now() "; $stmt = $db->prepare($sql); $stmt->execute([ ':name' => $otoiawasename, ':mail' => $otoiawaseemail, ':otoiawase' => $otoiawasebody ]); ``` このコードで「$\_POST['token']」だけが「NULL」となっていて ネットで何時間も調べても解決方法が見つからず、 CSRF対策に利用することが出来ずに困っています。 どこか間違っている箇所やおかしな場所がありましたら教えて頂けると嬉しいです。 $\_SESSION['token']のvar\_dumpの結果:string(32) "a60e17dc5d139bce60620b6e39489cff" $\_POST['toiawase\_name'] $\_POST['toiawase\_email'] $\_POST['toiawase\_body'] も利用する事が出来て、mysqlでお問い合わせからのデータを保存する事が出来ています。 「$\_POST['token']」だけがいくら試しても「NULL」のままです。 簡単な事で見落としがあるのか、根本的な問題なのか・・・。 ご存知の方がいらっしゃいましたら、お力を貸して頂けると嬉しいです。 --- 教えて頂いた通り <input type="hidden" name="token" value="<?= $\_SESSION['token']; ?>"> </form> </div> とすると1回は成功してきちんと$\_SESSION['token']が表示されたのですが、 再度試してみるとまた同じように Notice: Undefined index: token in NULL とエラーが表示され、$\_SESSION['token']の中身のデータが送られていない状態になっていました。 また、IEでも試してみると同じように Notice: Undefined index: token  のエラーが表示されていました。 1度成功したのに、またエラーが表示されるようになり 何が何だか分からずに頭がこんがらがってきました。 何かお気づきの点などがありましたら、お力を貸して頂けると嬉しいです。
【PHP】【CSRF対策】$\_POST['token']のデータが送信されていない問題の解決方法【初心者】 ======================================================
teratail.com
2021.17
[ { "text": "\n```\n </form>\n </div>\n <input type=\"hidden\" name=\"token\" value=\"<?= $\\_SESSION['token']; ?>\">\n```\n\n \n\nではなく、 \n\n\n\n```\n <input type=\"hidden\" name=\"token\" value=\"<?= $\\_SESSION['token']; ?>\">\n </form>\n </div>\n```\n\n \n\nでもなく、 \n\n\n\n```\n <input type=\"hidden\" name=\"token\" value=\"<?php echo $\\_SESSION['token']; ?>\">\n </form>\n </div>\n```\n\n \n\nでどうですか?\n\n", "name": "", "is_accepted": true }, { "text": "otoiawase1.phpの最後 \n\n\n\n```\n </form>\n </div>\n <input type=\"hidden\" name=\"token\" value=\"<?= $\\_SESSION['token']; ?>\">\n```\n\n \n\nを \n\n\n\n```\n <input type=\"hidden\" name=\"token\" value=\"<?= $\\_SESSION['token']; ?>\">\n </form>\n</div>\n```\n\n \n\nとするといいです。\n\n", "name": "", "is_accepted": false } ]
7470583d07694953aa02cee461bf4573
pipでインストールしたライブラリとソースを落としてきて、setup.pyでインストールしたものを併用するにはどうすれば良いのでしょうか? 具体的に問題にぶつかったのは、pipで`GPyOpt`というライブラリをインストールしていたのですが、 ``` pip install GPyOpt ``` どうやらバグがあり、開発版では治っているらしいという情報を手に入れたので`GPyOpt`をソースから利用しようとして ``` git clone https://github.com/SheffieldML/GPyOpt.git cd GPyOpt python setup.py develop ``` よく分からなくなってしまいました。
pipで手に入れたライブラリとsetup.pyでマニュアルインストールしたライブラリの併用 =============================================
teratail.com
2020.34
[ { "text": "`git clone`せずに`pip`で直接更新する方法があるので、そちらを試してみてくださいな。 \n\n\n\n```\npip install -U https://github.com/SheffieldML/GPyOpt/archive/master.zip\n```\n\n \n\nPythonをユーザーディレクトリにインストールしたなら以下のコマンドで。 \n\n\n\n```\npip install -U https://github.com/SheffieldML/GPyOpt/archive/master.zip --user\n```\n", "name": "", "is_accepted": true } ]
a2d2b8fcc7ffcd8953ef4abdc1392d86
他言語間でのプロセス間通信について。 c++を用いて開発を行っていますが今回画像処理の部分でpythonで記述したコードを使用したいと思いました。 この時, pythonのプロセスを立ち上げておいてc++からプロセス間通信によりデータを受け渡して処理を行う, もしくはOSにsignalを送るようなプログラミングをしてしまうことはコーティングスタンダード的に許されることなのでしょうか? C++への関数の変換も考えましたが見た感じ複雑そうだったので...
他言語間でのプロセス間通信について =================
teratail.com
2021.21
[ { "text": "独立した機能を持ったプロセス同士であれば、言語を気にする必要は全くないと思います。\n \nただ、通信するデータの形式によってはその形式を苦手な言語もあるかと思うので、考慮が必要です。 \n", "name": "", "is_accepted": false }, { "text": "C++からPythonのコードを呼び出したいのでしたら以下のリンクのようにPythonの埋め込みの方が柔軟な処理を実現できると思います。\n \n\n \nPython2系の場合\n \n[他のアプリケーションへの Python の埋め込み](http://docs.python.jp/2/extending/embedding.html)\n \n[C/C++ から Python を動的に扱う](http://d.hatena.ne.jp/mscp/20090919/1261917834)\n \n\n \nPython3系の場合\n \n[他のアプリケーションへの Python の埋め込み](http://docs.python.jp/3.4/extending/embedding.html)\n \n\n \nですがPython側でプロセス常駐するのでしたらこの方法は使えませんので、プロセス間通信など他の手段が必要でしょう。\n \nこの辺りはコーディングスタンダードよりも設計寄りですので、許す、許されないという話ではないと考えます。\n \n \n", "name": "", "is_accepted": false }, { "text": "プログラミング言語の違いって、どちらかと言えば **プログラマー側の都合**(プログラムの書きやすさ)のためにあるのであり、一度実行を開始してしまえば、コンピューター(OS)側からすれば **プロセス** の一つに過ぎません。(OSから見れば実行中のプログラムがどんな言語で作成されたものかは分かりません。)\n \nですので、言語の違いを気にする理由は何もありません。\n \n\n \n大抵のOSは、プロセス同士が **相互通信するための仕組み** として **パイプ** とか **ソケット** というものがあります。([ご参考](http://software.ed.sie.dendai.ac.jp/csystem/wiki.cgi/csystem2006?page=%A5%D7%A5%ED%A5%BB%A5%B9%B4%D6%C4%CC%BF%AE#p7))\n \n同一PC上で使用するならパイプの方が高速だという意見もありますが、いずれにしても、これらは **プロセス間通信** のために **OS側が標準で準備している仕組み** なので、ごく一般的な方法として利用されています。\n \n\n \nC系の言語はもちろんのこと、Pythonにもこれらの仕組みを利用するための方法が用意されていますので、ますは概要を調べて「何ができるか」「どのように実装すればよいか」のイメージをつかむところから始められると良いと思います。\n \n [Pythonでsubprocessを使って複数のコマンドをパイプでつなぐ](http://sucrose.hatenablog.com/entry/20110328/p1)\n \n [ソケットプログラミング HOWTO](http://docs.python.jp/3/howto/sockets.html)\n \n\n \nただし、ソケットプログラミングは、正しく理解して取り組まないとバグの温床になるので、プロセス常駐の必要がないのであれば **shiena**さんの回答にある通り、**Pythonの埋め込み** による連携の方が良いと思います。 \n", "name": "", "is_accepted": false }, { "text": "実行されるソフトから見た場合、プロセス間通信は単にOS(や処理系)の一機能でしかありません。\n \nなので、もちろん\n \nC<=>C++\n \nC++<=>Python\n \nのようなことも可能でしょう。\n \n\n \nただし、その言語自体がプロセス間通信に対応している必要はあります。 \n", "name": "", "is_accepted": false } ]
c22f96f13e4450cabc778202a6d32849
**favicon(ファビコン)で404エラーが出ているからファビコンを設定してと言われたけど、どうしていいかわかりません。** 以下のようなエラーが出ているようです。 File does not exist: /usr/local/apache/htdocs/favicon.ico ブラウザのお気に入りで表示される画像の事だという事はわかりました。 ネットとかで調べたのですが、あまり経験がないので、詳しい事はわからないのです。 今のところ、 ・16×16ピクセルのjpegやpng画像を用意する(ペイントではなく、ソフト使いました) ・ICO形式に変換してくれるサイトで、icoファイルに変換 ・ICO形式のファイルを作成 ・出来上がった画像をサーバに反映 までは行えました。 **後はヘッダに設定するだけのようなのですが、私が担当しているHTMLファイルの一覧を見ても、どこにもヘッダ情報がついていないのです。。** **テンプレートを書くために、スマーティと言う物を使っています。** いつもなら他の開発者さんにお願いするのですが、しばらく不在なので自分でやらなければいけません。 ここからどうしたらよいでしょうか?
favicon(ファビコン)で404エラーが出ているので対応や設定方法を教えてください ===========================================
teratail.com
2021.43
[ { "text": "**お話から察すると、おそらくフレームワークを使ってサイトを作られているのかと思いますので、以下のように試してみてください。**\n \n\n \n**※既にできている、又は代用できる手段をご存知の場合、その項目は飛ばして進めてください。**\n \n\n \n・使っているサイトの情報を、WinSCPなどを使ってローカルに落としてください\n \n 具体的には、cakeとかsymfonyと言うフォルダがあれば、そのフォルダ以下、よくわからなければappとかのフォルダがあれば、その階層にあるフォルダとファイルです。\n \n(わかるのであれば、プログラムやテンプレのファイルだけで大丈夫です。画像ファイル等大きいファイルはなるべく省いてください。)\n \n・テキストエディタ(秀丸とかサクラエディタとか)を使って、<head>の単語が含まれたファイルがどこにあるか検索してみてください。\n \n        秀丸を例にすると、上のメニューから「検索」->「grepの実行」で\n \n        「検索する文字列」に<head>を、検索するファイルに「*.*」を\n \n        検索フルフォルダに「先ほどダウンロードしたフォルダ」を設定してください。\n \n        該当ファイルが見つかったらF10のキーを押すとそのファイルの編集画面に飛びます。\n \n・ヘッダ情報の中に、以下のように記載を追加します。\n \n        <link rel=\"shortcut icon\" href=\"自分の使っているサイト.com/画像を格納したフォルダ/指定したファイル.ico\" type=\"image/vnd.microsoft.icon\" />\n \n・追加したヘッダのファイルを、サーバに反映します。\n \n\n \n上記ような形で設定すれば、ファビコンの設定が完了していると思います。\n \nブラウザをリロードするなどして試してみてください。\n \n\n \nあまり慣れていないようですので、編集前のファイルは必ずバックアップしておいてくださいね。\n \n\n \nちなみに、faviconを設定しなくてもエラーが出なくする方法があります。\n \n**Apacheの場合、httpd.confに以下を追加して再起動すればエラーログに出なくなります。**\n \n\n \nRedirect 404 /favicon.ico\n \nErrorDocument 404 \"Not Found favicon\" \n", "name": "", "is_accepted": true }, { "text": "headerが無いなら自分で追加しましょう。\n \n\n \nめんどうならhtdocs直下に、作ったfaviconを置いておけば反映されると思います。\n \n当座をそれでしのいでエンジニアが戻ってきたら任せるのはどうですか?\n \n\n \n \n", "name": "", "is_accepted": false } ]
56bb973fac6b3b877bce1e2c3c1f1f9b
### 前提・実現したいこと PHPの設定ファイルに設定を追加したところ、PHPでバージョン確認をcliから確認するとエラーが出るようになってしまいました Warningなので気にしなくてもいいかなと思いますが、気になったので解決策がわかる有識者の方、どなたかよろしくお願いします。 ### 発生している問題・エラーメッセージ ``` # php -v PHP Warning: Module 'openssl' already loaded in Unknown on line 0 Warning: Module 'openssl' already loaded in Unknown on line 0 PHP Warning: Module 'pdo\_pgsql' already loaded in Unknown on line 0 Warning: Module 'pdo\_pgsql' already loaded in Unknown on line 0 PHP Warning: Module 'pdo\_sqlite' already loaded in Unknown on line 0 Warning: Module 'pdo\_sqlite' already loaded in Unknown on line 0 PHP Warning: Module 'pdo\_mysql' already loaded in Unknown on line 0 Warning: Module 'pdo\_mysql' already loaded in Unknown on line 0 PHP Warning: Module 'mongodb' already loaded in Unknown on line 0 Warning: Module 'mongodb' already loaded in Unknown on line 0 ``` 追記: コメントありがとうございます。わたくしが追加した設定の一覧は以下のものになります。よろしくお願いいたします。 ``` extension = php_openssl.dll extension = php_pdo_pgsql.dll extension = php_pdo_sqlite.dll extension = php_pdo_mysql.dll extension = php_mongo.dll ```
PHP7でcliでエラー発生 ==============
teratail.com
2020.10
[ { "text": "[PHP php -i | grep php.iniとするとWarningがでる原因はなんでしょうか?](https://teratail.com/questions/3007) \n\n\nが参考になると思います。 \n\n\n恐らく、PHPとそのモジュールをインストールする際にパッケージマネージャーが設定してくれている内容を重複して設定してしまっているように思います。 \n\n\n一度ご自身で設定した内容を削除した状態で該当の機能が動作するかを確認することをお勧めします。\n\n", "name": "", "is_accepted": true } ]
8abb79e4473fe6ad308480097782f182
HttpURLConnectionクラスを使って外部サーバへHTTP接続するプログラムを作成中です。 一定時間で応答がなければタイムアウトさせるようにしたいのですが、 タイムアウトを設定するメソッドで、**setReadTimeout**と**setConnectTimeout**の違いがいまいちよくわかりません。 どう違うのでしょうか?
javaでHTTP接続する場合のタイムアウト設定について ============================
teratail.com
2021.10
[ { "text": "以下の違いがあります。\n \n\n \n**setReadTimeout・・・データ取得にかかる時間**\n \nサーバーへリクエストを投げてからレスポンスが返ってくるまでの時間の上限を設定します。\n \n \n \n**setConnectTimeout・・・接続そのものにかかる時間**\n \nサーバーとの通信の接続が確立するまでにかかる時間の上限を設定します。 \n", "name": "", "is_accepted": true } ]
b88b0928002c27267ec5d99d74c7b9f1
HTMLタグ付きの2つのテキストブロックがあり、それらの比較を表示しようとしています。 2つのテキストブロックをマージし、片方から何が追加・削除されたのかをハイライトしたいです。 既にプレーンテキストの比較は、**PEAR Text\_Diffクラス**を使って表示することは出来たのですが、 **htmlタグ**がそこに混じっただけで、一気にややこしくなってしまいます。 クラスが語形や文字を基礎とした比較アルゴリズムを使うので、どうしてもhtmlタグが壊れ ``` <p><span class="hoge"> </</span>p> ``` のような、汚い結果になってしまいます。 **オリジナルの有効なHTMLマークアップを維持しつつ、テキストの比較を生成する方法**ってありますか? こちらで思いつくことは、 ・それぞれのhtmlタグを検索し、非標準文字で置換える このような原始的なマークダウンで比較を表示し、非標準文字をオリジナルのタグへ戻す。 フィードバックなどお願いします! よろしくお願いします!
2つのHTMLテキストブロックの比較を表示する方法 =========================
teratail.com
2021.10
[ { "text": "問題は、あなたのdiffプラグラムが**既存のHTMLタグを個別の文字として認識**されてしまっているようです。\n \n\n \nもし、お使いのエンジンが単語限度で機能することに限る能力があるならば、それがHTMLタグを1つの「語」としてみなすような関数をオーバーライドすることが出来れば参照して下さい。\n \n\n \nまたは質問者さんが提案されたように、HTMLタグを未使用のUnicode値と一致させ、それらを集めたルックアップ辞書を作ってみてもいいかもしれません。(使えそうなユーザー定義レンジもあると思います。)\n \n\n \nしかしこれを実行した場合、変更されたマークアップはその前後のワードが変更したかのように表示されます。なぜかというと、トークン化プログラムで**Unicode**文字もそのワードの一部となってしまうからです。\n \n\n \nトークンUnicode文字の前後にスペースを入れることで、HTMLタグへの変更とプレーンテキストへの変更を区別することができます。 \n", "name": "", "is_accepted": true } ]
d45f91e6318e5a1c7d75a53cb88cd5f0
ffmpegで品質をパラメータ1個で変えられるようなオプションは ありませんか? (音声や動画のビットレートを一々指定するのではなく)
ffmpegで簡単に品質を変えるパラメータはありますか? ============================
teratail.com
2021.21
[ { "text": "crfオプションが該当するオプションです。\n \n\n \nffmpeg -i hoge.avi -crf 10 hoge.mp4\n \n\n \n数字が小さいほど品質がよくなります。\n \n(コーデックにより、取りうる値が違います) \n", "name": "", "is_accepted": true } ]
92a62bc2f63328ba4110b93b6342d17e
開発環境: Visual Studio 2008 (VB.NET) 古いヴァージョンですが、ご存知の方教えて下さい。 NB.NETでComboBoxを作成したときに ``` DropDownStyle = DropDownList ``` とすると、 [![イメージ説明](https://teratail-v2.storage.googleapis.com/uploads/contributed_images/91a241f1c7e2e788e4a7915847bf510c.png)](https://teratail-v2.storage.googleapis.com/uploads/contributed_images/91a241f1c7e2e788e4a7915847bf510c.png) 上記のように灰色の背景色になります。 これを、 ``` ComboBox1.BackColor = Color.LightSkyBlue ``` としても、設定が反映されません。 DropDownListのときに背景色を変更する方法はありませんか?
VB.NETのコンボボックスの背景色を変えたい =======================
teratail.com
2021.04
[ { "text": "\n```\nComboBox1.FlatStyle = FlatStyle.Flat\n```\n\n \n\nとすると、お望みの見た目に近づきませんか?\n\n", "name": "", "is_accepted": false } ]
f8859134b25344eac9e3c1c4e64b70b3
###  質問 PHPでは$\_SERVERを使用する↓ことで遷移前の1つ前のページのURLを取得できることを前に学んだのですが、 Pythonにはこういった便利な変数みたいなものは特にないのでしょうか? ``` <?php echo $\_SERVER['HTTP\_REFERER']; ?> ``` 色々調べてみたのですが、結果に表示されるものがPHPばかりだったため、もし見逃していたらと思い投稿しました。 ###  やりたいこと URLからあるサイトの記事にアクセスした際に非ログインだったためログインページに飛ばされるところまではできています しかし、そのログイン後にTOPページに飛んでしまうため、再度みたかった記事を探さなければなりません。 1つ前のURLw取得しておき、redirectでもともとアクセスしたURLに遷移するようにしたいと思っています。 Pythonの特徴的にあまりこういった1ページ前のuRL取得などの処理は行わないのが一般的なのでしょうか? ###  追記(11/14 17:00) request.refferrerというものがあることを知りました。 しかし、ログイン後の各ページの移動の際にはきちんと前のページのURLを取得することができますが、ログイン前の状態でログイン後に遷移可能なページのURLを直接叩いても取得されず、Noneとなってしまいます。 ログイン後に遷移できるページには @login\_requiredを使用しているため、そもそもURLが取れないのでしょうか...? ``` @login_manager.unauthorized_handler def unauthorized(): app.logger.info('ログイン失敗') print(request.referrer) return redirect(url_for('login', next=request.referrer)) ``` ↑の`print(request.referrer)`がNoneになります ↓遷移可能なページの処理を記載しているところ ``` @app.route('/') @login\_required def home(): ``` ###  追記(11/15 15:00) request.urlというものを知りました。 ``` @login_manager.unauthorized_handler def unauthorized(): app.logger.info('ログイン失敗') print(request.url) return redirect(url_for('login', next=request.url)) ``` ↑のようにrequest.referrerからrequest.urlに変更したところ前のページのURLを取得することができました。 リダイレクト先のdef loginでも ``` @app.route('/login', methods=['GET', 'POST']) def login(next=None): print(request.url) ~~~ ``` と記載すると1つ前のURLが取れているように見えます。 その後、1つ前のURLを保持した状態でログインをすると ``` @app.route('/login', methods=['GET', 'POST']) def login(next=None): print(request.url) ~~~ ``` ↑のprint文において、先ほどは取れていたURLではなく http://~~~~~/loginのようにログインページが1つ前のページ扱いになってしまいます。 何がおかしい(何が起きている)のかわからず困っています...。 詳しい方よろしくお願いいたします。 ###  追記(11/16 10:00) ``` @app.route('/login', methods=['GET', 'POST']) def login(next=None): print(request.url) ``` ↑を実行すると、 > > > > > > > > > > > > http://[IPアドレス]/contents/1 > > > > > > のように1つ前のURLを取得できます > > > > > > > > > > > > > > > > > > しかし、その状態でログインを行うと > > > > > > > > > > > > http://[IPアドレス]/login > > > > > > のようにloginページが1つ前のページ扱いとなってしまいます... > > > > > > > > > > > > > > > > > >
PythonでのURL値の取得 ===============
teratail.com
2021.10
[ { "text": "ログイン前に訪問したページ \n\n\n\n```\[email protected]('/')\ndef hogehoge():\n if not current_user.is\\_authenticated:\n session['hoge\\_url'] = request.url\n return current_app.login_manager.unauthorized()\n```\n\nログイン内 \n\n\n\n```\nif session['hoge\\_url']:\n next_url = session['hoge\\_url']\n session['hoge\\_url'] = ''\n return redirect(next_url)\nreturn redirect(url_for('hogehoge'))\n```\n\n公式ドキュメントを見たところ`@login_required`ではなく \n\n\n\n```\nif not current_user.is\\_authenticated:\nreturn current_app.login\\_manager.unauthorized()\n```\n\n \n\nを使うと良いとのことだったのでこちらを使用したらうまくいきました。 \n\nありがとうございました。\n\n", "name": "", "is_accepted": true } ]
323e3b9667fe4de4a85866cc96e0abb0
いつもお世話になっています Javascriptでのイベント処理にてわからないことがありましたので、質問させて頂きました サムネイルの様に、複数枚並んだ画像全てにイベント処理を実装したく、下記のようなコードを記述しましたが、上手くいきませんでした(show関数が実行されなかったり、iが配列の最大値の時のみ実行されたりします) この記述がなぜ上手くいかないのか、どうすれば上手くいくのかを、教えて頂ければと思います お手数ですが、よろしくお願い申し上げます ``` // 関数定義 function show(x){     console.log(x); } // イベント処理 var img = document.getElementsByTagName('img'); for(var i = 0; i < img.length; i++){     img[i].onclick = function(){         show(i);     }; } ```
JavaScriptにて、配列の要素一つ一つにイベントを実装したい =================================
teratail.com
2021.43
[ { "text": "`click` が呼び出された時点で呼び出される変数 `i` が `for` 文を通過した後に参照される為ですね。\n \n変数 `i` を束縛する方法はいくつかありますが、[handleEvent](https://developer.mozilla.org/ja/docs/Web/API/EventTarget/addEventListener#The_value_of_this_within_the_handler) を使用する方法はどうでしょうか。\n \n([JSFiddle](http://jsfiddle.net/m627kwag/) にもサンプルをUPしました。)\n \n\n \n\n```\n<img src=\"sample-1.jpg\" alt=\"sample1\">\n<img src=\"sample-2.jpg\" alt=\"sample2\">\n\n<script>\n(function () {i\n  function handleClick (event) {\n    console.log(this.x);\n  }\n  \n  var imgs = document.getElementsByTagName('img');\n  \n  for (var i = 0, l = imgs.length; i < l; ++i) {\n    imgs[i].addEventListener('click', {x: i, handleEvent: handleClick}, false);\n  }\n}());\n</script>\n```\n\n \n`handleEvent` は `addEventListener` に備わった機能なので第一引数の `event` オブジェクトと併用できます。\n \n\n \n\n\n---\n\n**(2015/09/08 19:14追記)**\n \nもし、IE8- にも対応させるならクロージャで変数束縛する方法があります。\n \n([JSFiddle](http://jsfiddle.net/m627kwag/6/)にサンプルUPしました。)\n \n\n \n\n```\n(function () {\n  function createHandleClick (i) {\n    return function handleClick (event) {\n      console.log(i, event.type);\n    };\n  }\n\n  function addEvent (element, type, listener) {\n    if (element.addEventListener) {\n      element.addEventListener(type, listener, false);\n    } else if (element.attachEvent) {\n      element.attachEvent('on' + type, listener);\n    } \n  }\n\n  function init () {\n    var imgs = document.getElementsByTagName('img');\n  \n    for (var i = 0, l = imgs.length; i < l; ++i) {\n      addEvent(imgs[i], 'click', createHandleClick(i));\n    }\n  }\n\n  init();\n}());\n```\n\n \n\n\n---\n\n**(2015/09/08 23:00追記)**\n \n[data-* 属性](https://developer.mozilla.org/ja/docs/Web/HTML/Global_attributes#data-*)で index を割り振っておくのも一つの手段だと思います。\n \n([JSFiddle](http://jsfiddle.net/m627kwag/8/)にサンプルUPしました)\n \n\n \n\n```\n<img src=\"sample-1.jpg\" alt=\"sample1\" data-i=\"1\">\n<img src=\"sample-2.jpg\" alt=\"sample2\" data-i=\"2\">\n\n<script>\n(function () {\n  function handleClick (event) {\n    var img = event.target || event.srcElement; // target要素を得る(Standard || IE8-)\n    console.log(img.getAttribute('data-i'), event.type); // data-*属性を参照\n  }\n\n  function addEvent (element, type, listener) {\n    if (element.addEventListener) {   // Standard\n      element.addEventListener(type, listener, false);\n    } else if (element.attachEvent) { // IE8-\n      element.attachEvent('on' + type, listener);\n    } \n  }\n\n  function init () {\n    var imgs = document.getElementsByTagName('img');\n  \n    for (var i = 0, l = imgs.length; i < l; ++i) {\n      addEvent(imgs[i], 'click', handleClick);\n    }\n  }\n\n  init();\n}());\n</script>\n```\n\n \nimg要素の親要素ノードでバブリングを利用してキャプチャすると更にスマートになります。 \n", "name": "", "is_accepted": true }, { "text": "どういう処理を行うかわかりませんが、\n \n私なら次のように書きます。\n \n\n \nポイントは2つあるんですが、\n \n1つ目は基本ですがimgタグの後にscriptタグを書く\n \n2つ目はiの評価がクリック時に行われる書き方なのでbindでその時の値を渡しておく\n \nって感じです。\n \nそれぞれshow関数が実行されない件と、iが配列の最大値で実行される件の対策です。\n \n参考になると良いのですが。\n \n\n \n\n```\n<img src=\"image.jpg\" width=\"20px\">\n<img src=\"image2.jpg\" width=\"20px\">\n<script>\n// 関数定義\nfunction show(x){\n    console.log(x);\n}\n\n// イベント処理\nvar img = document.getElementsByTagName('img');\n\nfor(var i = 0; i < img.length; i++){\n    img[i].onclick = show.bind(img[i], i)\n}\n</script>\n```\n", "name": "", "is_accepted": false }, { "text": "jQueryを使ったサンプルをあげます。\n \n\n \n\n```\n<img class=\"thumbnail\" src=\"image.jpg\" width=\"20px\">\n<img class=\"thumbnail\" src=\"image2.jpg\" width=\"20px\">\n\n<script>\n$(document).ready(function(){\n  // thumbnailクラスが付いているものすべてをjQueryオブジェクで取得\n  var $thumbnails = $('.thumbnail');\n  \n  // クリックイベントを定義\n  $thumbnails.on('click', function(e) {\n    // 実処理関数にjQueryオブジェクトで引き渡す\n    clickEvent($(this));\n  });\n  \n  /**\n   * サムネイルクリックイベント\n   * param $n サムネイル画像タグのjQueryオブジェクト\n   *\n   **/\n  var clickEvent = function($n) {\n    console.log($n.attr('src'));\n  };\n});\n</script>\n```\n\n \nコメントを充実させたので、少し長く見えますが、実コードはすごくシンプルになります。\n \njQueryの導入や賛否は置いておいて。。。。 \n", "name": "", "is_accepted": false } ]
a1e35e6df87dd54c2b947911401671c1
↓でGoFイテレータパターンから各インターフェースを除外し、コンパイルが通るようにしました。しかしこの状態でも、ここから集約役割(本棚)の実装が変わっても(ex.配列→ArrayList)正常に動いてしまいます。 なのでインターフェースいらないじゃんって思ってしまったのですが、オブジェクト指向**設計**においては必要なのですよね?その理由を教えて下さい。 ``` //メイン public class Main { public static void main(String[] args) { BookShelf bookShelf = new BookShelf(4); bookShelf.appendBook(new Book("Around the World in 80 Days")); bookShelf.appendBook(new Book("Bible")); bookShelf.appendBook(new Book("Cinderella")); bookShelf.appendBook(new Book("Daddy-Long-Legs")); //Iterator it = bookShelf.iterator(); BookShelfIterator it = bookShelf.iterator(); while (it.hasNext()) { Book book = (Book)it.next(); System.out.println(book.getName()); } } } ``` ``` //数えるモノ(書籍) public class Book { private String name; public Book(String name) { this.name = name; } public String getName() { return name; } } ``` ``` //集約役割(本棚) //public class BookShelf implements Aggregate { public class BookShelf { private Book[] books; private int last = 0; public BookShelf(int maxsize) { this.books = new Book[maxsize]; } public Book getBookAt(int index) { return books[index]; } public void appendBook(Book book) { this.books[last] = book; last++; } public int getLength() { return last; } // public Iterator iterator() { public BookShelfIterator iterator() { return new BookShelfIterator(this); } } ``` ``` //イテレータ役割 //public class BookShelfIterator implements Iterator { public class BookShelfIterator { private BookShelf bookShelf; private int index; public BookShelfIterator(BookShelf bookShelf) { this.bookShelf = bookShelf; this.index = 0; } public boolean hasNext() { if (index < bookShelf.getLength()) { return true; } else { return false; } } public Object next() { Book book = bookShelf.getBookAt(index); index++; return book; } } ```
GoFのイテレータパターンが、インターフェースがなくても機能を満たしてしまう =======================================
teratail.com
2021.17
[ { "text": "こんにちは。 \n\n\nGoFのデザインパターンに詳しくはないのですが、「GoFイテレータパターン」には2つのメリットがあると思います。 \n\n\n1. イテレータ自体 \n\n配列や線形リストを同じ使い方で枚挙できるので、あるコレクションの実装を変更しても使う側のプログラムを変更しなくてもよい。\n2. イテレータ・インタフェースを継承したコレクション \n\nこれは1.の使い方で使えることを保証されるので、使いやすい。\n\n\nnyahonyahoさんの実装は1.のメリットを使ってますが、2.のメリットがありません。 \n\n例えば、本棚(BookShelf)を使ったことがある人が、薬品庫(ChemicalCloset)を使う時もあると思います。その時、ChemicalClosetの実装者が、例えばgetIterator()でイテレータを返却するような実装をしていると結構嫌と思います。 \n\n逆も同じです。ChemicalClosetを使った事がある人が、BookShelfを使う時、getIterator()ではなくiterator()を使わないといけなくなります。 \n\n\nそれよりは、IEnumeratorのようなインターフェースでiterator()を定義しておき、コレクションを実装する時はIEnumeratorを継承することにしておくと、上記問題をさけることができます。\n\n", "name": "", "is_accepted": true }, { "text": "集約役割(本棚)の実装が複数同時に存在するとき困ります。 \n\n追加/削除可能な本棚と \n\n追加オンリーな本棚とか \n\n本のIdが連番になっている本棚とか \n\n\nイテレータの実装が複数同時に存在するときもやっぱり困ります。 \n\n順番に取り出すとか \n\n逆順に取り出すとか\n\n", "name": "", "is_accepted": false } ]
021622364b8dd829975109177c3c7596
``` private Material equirectangularMaterial; this.equirectangularMaterial = new Material(Shader.Find(@"Hidden\CubeToEquirectangular")); ``` Shader.Findという関数を使ってシェーダーファイルを読み込もうとしています。ビルド前は上記のように書いてうまくいっているのですがビルド後に実行するとNullReferenceExceptionになり実行できません。 調べてみるとShader.Findはビルド後はこういう動作をするので、Inspecterでhttps://qiita.com/shirai/items/3d2e3ff9e0d9a55a2e23のようにすると解決するらしいのですが、なんとかスクリプト上でビルド後もシェーダーファイルを読み込むことはできないのでしょうか?ビルドされたものに処理を差し込みたいのでスクリプト上で解決したいのです。 Unity5.6.2f1です。よろしくお願いします。 追記 処理が差し込めないのはStereoEquirectangularTextureUpdaterだけなので、StereoCubemapUpdaterで作ったCubemapLeft,CubemapRightをファイルかなにかに出力して、後でそのファイルをシェーダーファイルを読み込める環境で処理すればできないでしょうか。 それで質問なのですが、StereoCubemapUpdaterでつくったCubemapLeft,CubemapRightをStereoEquirectangularTextureUpdaterで再度利用するためにはどんな形式で出力して保存すればいいのでしょうか? ``` void savePng(String filename, int count, RenderTexture saveRT) { Texture2D tex = new Texture2D(saveRT.width, saveRT.height, TextureFormat.RGB24, false); RenderTexture.active = saveRT; tex.ReadPixels(new Rect(0, 0, saveRT.width, saveRT.height), 0, 0); tex.Apply(); // Encode texture into PNG byte[] bytes = tex.EncodeToPNG(); UnityEngine.Object.Destroy(tex); var name = @"C:\Users\Username\Desktop\unity\Captures\" + filename + count.ToString("0") + ".png"; //Write to a file in the project folder File.WriteAllBytes(name, bytes); } ``` とりあえず上記の関数でCubemapLeftをpngにしてみたのですが、下のような画像になってしまってキューブマップではないと思います。 [![イメージ説明](https://teratail-v2.storage.googleapis.com/uploads/contributed_images/541e24da6bdb9b744dfa94db1ed89d25.png)](https://teratail-v2.storage.googleapis.com/uploads/contributed_images/541e24da6bdb9b744dfa94db1ed89d25.png) 本当に度々申し訳ありません。わかりにくい文章で恐縮ですが時間があるときでよいので回答よろしくお願いします。 追記 ``` void Update() { Texture2D tex; private Color[] CubeMapColors; string path = @"C:\Users\Username\Desktop\unity\Captures\"; CubemapFace[] cubemapFaces = { CubemapFace.PositiveX, CubemapFace.NegativeX, CubemapFace.PositiveY, CubemapFace.NegativeY, CubemapFace.PositiveZ, CubemapFace.NegativeZ }; foreach (CubemapFace face in cubemapFaces) { name = path + @"Right\" + "frame" + framecount.ToString("0") + face.ToString() + ".png"; tex = ReadTexture(name, 1024, 1024); CubeMapColors = tex.GetPixels(); cubemapRight.SetPixels(CubeMapColors, face); cubemapRight.Apply(); } } byte[] ReadPngFile(string path) { FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read); BinaryReader bin = new BinaryReader(fileStream); byte[] values = bin.ReadBytes((int)bin.BaseStream.Length); bin.Close(); return values; } Texture2D ReadTexture(string path, int width, int height) { byte[] readBinary = ReadPngFile(path); Texture2D texture = new Texture2D(width, height,TextureFormat.RGB24, false); texture.LoadImage(readBinary); return texture; } ``` すみませんが最後にもう一つだけ質問してよろしいでしょうか。 Cubemap.SetPixelsを使って6枚の画像をRenderTextureにセットするスクリプトを書いてみたのですが、RenderTextureにうまくセットできていないようです。ファイルから画像を読み込むことはできているようです。Cubemap.SetPixelsの使い方かヒントを教えていだだけないでしょうか。 質問ばかりで申し訳ありませんが時間のあるときでいいのでよろしくお願いします。
シェーダーファイルをShader.Findで読み込むとビルド後動作しない ====================================
teratail.com
2019.43
[ { "text": "では、インスペクター上で参照をセットしておくことは可能でしょうか? \n\nスクリプトに`[SerializeField] private Shader equirectangularShader;`のようにフィールドを追加して、インスペクター上の欄にプロジェクトビューからシェーダーファイルをドラッグ&ドロップし、マテリアル作成部分では`this.equirectangularMaterial = new Material(this.equirectangularShader);`という風にするのではどうでしょう。 \n\n\n**追記** \n\nすみませんが、独自のシェーダーを持ち込む方法はわかりませんでした... \n\nアプローチを変えて、「[Unity5.6.2f1でメインカメラの両目の映像をレンダリングしたい](https://teratail.com/questions/215439)」で申し上げた正距円筒図法展開をビルトインシェーダーのみで行えないか検討してみました。 \n\nデフォルトの状態ですとAlways Included Shadersに`Hidden/CubeCopy`が入っています。もしそのゲームでそこがいじられていなければ、それを使うことができるんじゃないかともくろみました。 \n\n\n`CubeCopy`は単純に入力されたUV座標からキューブマップをサンプリングして出力するだけのシェーダーですので、円筒図法展開に利用するには入力するメッシュをちょっと工夫してやることになるでしょう。 \n\nそこで頂点座標は四角い展開図の形、UV座標は3次元の球体の形のメッシュを作り、それを[DrawMeshNow](https://docs.unity3d.com/jp/560/ScriptReference/Graphics.DrawMeshNow.html)で描画することにしました。 \n\n前回の`StereoEquirectangularTextureUpdater`をベースにしており相変わらず`SerializeField`やらを使っていますので、ご質問者さんの用途には直接利用できないかもしれません。使えそうな部分だけご参考にしていただきたく思います。 \n\n\n\n```\nusing System;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic class StereoEquirectangularTextureUpdaterBuiltinShader : MonoBehaviour\n{\n public enum Arrangement\n {\n TopAndBottom,\n SideBySide\n }\n\n public enum FieldOfView\n {\n Full,\n Half\n }\n\n [SerializeField] private StereoCubemapUpdater stereoCubemapUpdater;\n [SerializeField] private RenderTexture equirectangularTexture;\n [SerializeField] private bool useLocalDirection;\n [SerializeField] private Arrangement arrangement;\n [SerializeField] private FieldOfView fieldOfView;\n [SerializeField] private int sphereNetDivision = 16;\n\n private RenderTexture cubemapLeft;\n private RenderTexture cubemapRight;\n private Material equirectangularMaterial;\n private Mesh sphereNet;\n private List<Vector3> sphereNetUvs;\n private List<Vector3> rotatedSphereNetUvs;\n private Mesh hemisphereNet;\n private List<Vector3> hemisphereNetUvs;\n private List<Vector3> rotatedHemisphereNetUvs;\n\n // 球面の展開図を表すメッシュを生成するメソッド\n // divisionを大きくするほど正確に展開できるはずだが、その分頂点数が増えるので\n // ローカル展開の場合のUV更新にかかるコストが大きくなると思われる\n private Mesh CreateSphereNet(int division, bool asHemisphere, out List<Vector3> uvs)\n {\n var deltaAngle = Mathf.PI / division;\n var divisionX = (asHemisphere ? 1 : 2) * division;\n var divisionY = division;\n var divisionXPlus1 = divisionX + 1;\n var divisionYPlus1 = divisionY + 1;\n var deltaX = 2.0f / divisionX;\n var deltaY = 2.0f / divisionY;\n var x = new float[divisionXPlus1];\n var phi0 = -(asHemisphere ? 0.5f : 1.0f) * Mathf.PI;\n var sinPhi = new float[x.Length];\n var cosPhi = new float[x.Length];\n var y = new float[divisionYPlus1];\n var theta0 = -0.5f * Mathf.PI;\n var sinTheta = new float[y.Length];\n var cosTheta = new float[y.Length];\n for (var i = 0; i <= divisionX; i++)\n {\n var angle = phi0 + (deltaAngle * i);\n sinPhi[i] = Mathf.Sin(angle);\n cosPhi[i] = Mathf.Cos(angle);\n x[i] = (deltaX * i) - 1.0f;\n }\n\n for (var i = 0; i <= divisionY; i++)\n {\n var angle = theta0 + (deltaAngle * i);\n sinTheta[i] = Mathf.Sin(angle);\n cosTheta[i] = Mathf.Cos(angle);\n y[i] = (deltaY * i) - 1.0f;\n }\n\n var vertices = new Vector3[divisionXPlus1 * divisionYPlus1];\n uvs = new List<Vector3>(vertices.Length);\n for (var j = 0; j <= divisionY; j++)\n {\n var o = j * divisionXPlus1;\n for (var i = 0; i <= divisionX; i++)\n {\n vertices[o + i] = new Vector3(x[i], y[j], 0.0f);\n uvs.Add(new Vector3(sinPhi[i] * cosTheta[j], sinTheta[j], cosPhi[i] * cosTheta[j]));\n }\n }\n\n var triangles = new int[divisionX * divisionY * 6];\n for (var j = 0; j < divisionY; j++)\n {\n var o = j * divisionX;\n for (var i = 0; i < divisionX; i++)\n {\n var k = (o + i) * 6;\n triangles[k] = (divisionXPlus1 * j) + i;\n triangles[k + 1] = (divisionXPlus1 * (j + 1)) + i;\n triangles[k + 2] = triangles[k] + 1;\n triangles[k + 3] = triangles[k + 1] + 1;\n triangles[k + 4] = triangles[k + 2];\n triangles[k + 5] = triangles[k + 1];\n }\n }\n\n var net = new Mesh();\n net.vertices = vertices;\n net.SetUVs(0, uvs);\n net.triangles = triangles;\n net.MarkDynamic();\n return net;\n }\n\n private void Start()\n {\n this.cubemapLeft = this.stereoCubemapUpdater.CubemapLeft;\n this.cubemapRight = this.stereoCubemapUpdater.CubemapRight;\n this.equirectangularMaterial = new Material(Shader.Find(\"Hidden/CubeCopy\"));\n this.sphereNet = this.CreateSphereNet(this.sphereNetDivision, false, out this.sphereNetUvs);\n this.hemisphereNet = this.CreateSphereNet(this.sphereNetDivision, true, out this.hemisphereNetUvs);\n this.rotatedSphereNetUvs = new List<Vector3>(this.sphereNetUvs);\n this.rotatedHemisphereNetUvs = new List<Vector3>(this.hemisphereNetUvs);\n }\n\n private void LateUpdate()\n {\n // 描画先座標の移動・伸縮はMatrix4x4で表現する\n Matrix4x4 leftVertexTransform;\n Matrix4x4 rightVertexTransform;\n switch (this.arrangement)\n {\n case Arrangement.TopAndBottom:\n leftVertexTransform = Matrix4x4.TRS(\n new Vector3(0.0f, 0.5f, 0.0f),\n Quaternion.identity,\n new Vector3(1.0f, 0.5f, 1.0f));\n rightVertexTransform = Matrix4x4.TRS(\n new Vector3(0.0f, -0.5f, 0.0f),\n Quaternion.identity,\n new Vector3(1.0f, 0.5f, 1.0f));\n break;\n case Arrangement.SideBySide:\n leftVertexTransform = Matrix4x4.TRS(\n new Vector3(-0.5f, 0.0f, 0.0f),\n Quaternion.identity,\n new Vector3(0.5f, 1.0f, 1.0f));\n rightVertexTransform = Matrix4x4.TRS(\n new Vector3(0.5f, 0.0f, 0.0f),\n Quaternion.identity,\n new Vector3(0.5f, 1.0f, 1.0f));\n break;\n default:\n throw new ArgumentOutOfRangeException();\n }\n\n // ローカル展開の場合はUV座標を回転しメッシュに再設定する\n var rotation = this.stereoCubemapUpdater.transform.rotation;\n switch (this.fieldOfView)\n {\n case FieldOfView.Full:\n if (this.useLocalDirection)\n {\n for (var i = 0; i < this.sphereNetUvs.Count; i++)\n {\n this.rotatedSphereNetUvs[i] = rotation * this.sphereNetUvs[i];\n }\n\n this.sphereNet.SetUVs(0, this.rotatedSphereNetUvs);\n }\n else\n {\n this.sphereNet.SetUVs(0, this.sphereNetUvs);\n }\n\n this.sphereNet.RecalculateBounds();\n break;\n case FieldOfView.Half:\n if (this.useLocalDirection)\n {\n for (var i = 0; i < this.hemisphereNetUvs.Count; i++)\n {\n this.rotatedHemisphereNetUvs[i] = rotation * this.hemisphereNetUvs[i];\n }\n\n this.hemisphereNet.SetUVs(0, this.rotatedHemisphereNetUvs);\n }\n else\n {\n this.hemisphereNet.SetUVs(0, this.hemisphereNetUvs);\n }\n\n this.hemisphereNet.RecalculateBounds();\n break;\n default:\n throw new ArgumentOutOfRangeException();\n }\n\n // メッシュをレンダーテクスチャ上にレンダリング\n if (this.equirectangularMaterial.SetPass(0))\n {\n var activeTexture = RenderTexture.active;\n RenderTexture.active = this.equirectangularTexture;\n var net = this.fieldOfView == FieldOfView.Full ? this.sphereNet : this.hemisphereNet;\n GL.PushMatrix();\n GL.LoadProjectionMatrix(Matrix4x4.identity);\n this.equirectangularMaterial.mainTexture = this.cubemapLeft;\n Graphics.DrawMeshNow(net, leftVertexTransform);\n this.equirectangularMaterial.mainTexture = this.cubemapRight;\n Graphics.DrawMeshNow(net, rightVertexTransform);\n GL.PopMatrix();\n RenderTexture.active = activeTexture;\n }\n }\n}\n```\n\n注意点として、前回の独自シェーダーによる方法ではピクセル単位の正確さで展開されるのに対し、今回の方法では展開に使うメッシュをある程度細かくしないとゆがみが目立ってしまう弱点があります。 \n\nたとえば`sphereNetDivision`を4に下げると、こんな風になってしまいます... \n\n\n[![図](https://teratail-v2.storage.googleapis.com/uploads/contributed_images/30eb4042c900fe89326bf2b7fe1f005d.gif)](https://teratail-v2.storage.googleapis.com/uploads/contributed_images/30eb4042c900fe89326bf2b7fe1f005d.gif) \n\n\n**キューブマップをファイルに保存する件について追記** \n\n以前申し上げましたように、キューブマップには6つの面があります。保存メソッドを下記のようにしてみるとどうでしょうか? \n\n\n\n```\nvoid savePng(string filename, int count, RenderTexture saveRT)\n{\n CubemapFace[] cubemapFaces =\n {\n CubemapFace.PositiveX, CubemapFace.NegativeX,\n CubemapFace.PositiveY, CubemapFace.NegativeY,\n CubemapFace.PositiveZ, CubemapFace.NegativeZ\n };\n Texture2D tex = new Texture2D(saveRT.width, saveRT.height, TextureFormat.RGB24, false);\n\n foreach (CubemapFace face in cubemapFaces)\n {\n Graphics.SetRenderTarget(saveRT, 0, face);\n tex.ReadPixels(new Rect(0, 0, saveRT.width, saveRT.height), 0, 0);\n tex.Apply();\n\n // Encode texture into PNG\n byte[] bytes = tex.EncodeToPNG();\n\n var name = @\"C:\\Users\\Username\\Desktop\\unity\\Captures\\\" + filename + count.ToString(\"0\") + face.ToString() + \".png\";\n //Write to a file in the project folder\n File.WriteAllBytes(name, bytes);\n }\n\n UnityEngine.Object.Destroy(tex);\n}\n```\n\n \n\n保存された画像からキューブマップを作る場合、書き出し時と逆に[Cubemap.SetPixels](https://docs.unity3d.com/jp/560/ScriptReference/Cubemap.SetPixels.html)の`face`をそれぞれの[CubemapFace](https://docs.unity3d.com/jp/560/ScriptReference/CubemapFace.html)に切り替えながら計6回セットしてやることになるかと思います。 \n\n\n**画像ファイルからキューブマップを作る件について追記** \n\n\n提示いたしましたコードの`cubemapLeft`や`cubemapRight`は[Cubemap](https://docs.unity3d.com/560/Documentation/ScriptReference/Cubemap.html)型ではなく「[dimension](https://docs.unity3d.com/560/Documentation/ScriptReference/RenderTexture-dimension.html)を[Cube](https://docs.unity3d.com/560/Documentation/ScriptReference/Rendering.TextureDimension.Cube.html)にした`RenderTexture`型」です。これは`Texture2D`と普通の`RenderTexture`との関係と同様で、前者は画像ファイルなどCPU側のデータをGPU側でのテクスチャとして使えるように送り込む用途、後者はGPU側でテクスチャ上にレンダリングを行う用途に適していると言えるでしょう。 \n\n今回のケースでは画像ロード先のキューブマップが`RenderTexture`である必要はないので、`Cubemap`に変更してはいかがでしょうか。 \n\n\n\n```\nprivate Cubemap cubemapLeft;\nprivate Cubemap cubemapRight;\n```\n\n \n\nそして初期化時も`Cubemap`を作るようにしてやれば、`cubemapLeft`や`cubemapRight`に対して`SetPixels`が使えるようになるはずです。 \n\n\n\n```\nthis.cubemapLeft = new Cubemap(1024, TextureFormat.RGB24, false);\nthis.cubemapRight = new Cubemap(1024, TextureFormat.RGB24, false);\n```\n\n \n\nそれ以降の円筒投影する`Graphics.Blit(this.cubemapRight, this.equirectangularTexture, this.equirectangularMaterial);`の部分では`cubemapLeft`や`cubemapRight`が`RenderTexture`であっても`Cubemap`であっても区別せず扱えるはずですので、コードはそのままでいいかと思います。\n\n", "name": "", "is_accepted": true } ]
6e72aca1551afd984ee11d0f0c761cd9
JAVA初心者です。配列を使って以下のようなプログラムを作成しました。 import java.util.Scanner; public class Saishouchi {     public static void main (String[] args) {         Scanner stdin = new Scanner(System.in);         int i = 0;         int j = 0;         int values[] = new int[30];         System.out.print("数値を入力 ");         for(; i < values.length ; i++ ){             values[i] = stdin.nextInt();                    //数値を30個 以下入力             //0が入力されたら終了             if(values[i] == 0) {                 break;             }         }         int min = values[0];         for(; j < i; j++) {             if(values[j] < min) {                 min = values[j];             }         }         System.out.print( "最小値:"+min+" インデックス: "+ j);     } } 標準入力によって入力されたいくつかの数値の中の 最小値を表示し、そのインデックスも表示したいのですが、インデックスの方がうまく表示されません。 どのようにしたら良いでしょうか。 わかる方いらっしゃいましたら、ご教授ください。 よろしくお願いします。
JAVA 配列に関する質問 =============
teratail.com
2021.31
[ { "text": "\n```\n        int min = values[0]; \n        int minIndex = 0;  //最小値となるインデックス値を保持\n        for(; j < i; j++) { \n            if(values[j] < min) { \n                minIndex = j;\n                min = values[j]; \n            } \n        } \n        System.out.print( \"最小値:\"+min+\" インデックス: \"+ minIndex); \n```\n", "name": "", "is_accepted": true }, { "text": "for文の中でminの変数に値を取得しているが、\n \nインデックスの値を保持していない。\n \n\n \nSystem.out.printで最小値・インデックスを\n \n出力する時点でインデックスの値は\n \nfor文が終わった時点の値を保持しているので、\n \n最小値の位置とインデックスが合わない状態と\n \nなってしまう。\n \n \n", "name": "", "is_accepted": false } ]
cd31182cce279a9d0f2cd8db321d7e35
### 前提・実現したいこと はじめまして、ここで初めて質問させていただきます Pythonでサイトをスクレイピングしようと思っています そこでBeautifulSoup4をインストールしてスクレイピングしようと思ったのですがいくらやってもエラーが出てしまいます おそらくBeautifulSoupというモジュールはないという主旨のエラーだと思うのですがどうやったら解決しますか、プログラムも初心者なのでできたら分かりやすく教えていただけますか スペック Windows8.1 Python3.6.3 Pycharm ### 発生している問題・エラーメッセージ ``` C:\Users\私のユーザー名\PycharmProjects\untitled1\venv\Scripts\python.exe C:/Users/私のユーザー名/PycharmProjects/untitled1/nikkei.py Traceback (most recent call last): File "C:/Users/私のユーザー名/PycharmProjects/untitled1/nikkei.py", line 3, in <module> import BeautifulSoup ModuleNotFoundError: No module named 'BeautifulSoup' Process finished with exit code 1 ``` ### 該当のソースコード ``` #coding: UTF-8 import urllib import BeautifulSoup url = "https://www.nikkei.com/" html = urllib.urlopen(url) soup = BeautifulSoup(html, "html.parser") title_tag = soup.span print (title_tag) ``` ### 試したこと BeautifulSorpのとこだけ波線が出ていたので認識してないと思いました importの前にfrom bs4をつけていましたが同じエラーが出ました ``` from bs4 import BeautifulSoup ``` BeautifulSoupの他にBeautifulSoup4、beautifulsorp、beautifulsorp4と入力してみましたがまた同じエラーが出ました インストールしたときにコマンドプロンプトでpipでインストールしようとしたんですが ``` C:\Users\私のユーザー名>pip install beautifulsoup4 Collecting beautifulsoup4 Using cached beautifulsoup4-4.6.0-py3-none-any.whl Installing collected packages: beautifulsoup4 Exception: Traceback (most recent call last): File "c:\program files\python36\lib\site-packages\pip\basecommand.py", line 21 5, in main status = self.run(options, args) File "c:\program files\python36\lib\site-packages\pip\commands\install.py", li ne 342, in run prefix=options.prefix_path, File "c:\program files\python36\lib\site-packages\pip\req\req_set.py", line 78 4, in install **kwargs File "c:\program files\python36\lib\site-packages\pip\req\req_install.py", lin e 851, in install self.move_wheel_files(self.source_dir, root=root, prefix=prefix) File "c:\program files\python36\lib\site-packages\pip\req\req_install.py", lin e 1064, in move_wheel_files isolated=self.isolated, File "c:\program files\python36\lib\site-packages\pip\wheel.py", line 345, in move_wheel_files clobber(source, lib_dir, True) File "c:\program files\python36\lib\site-packages\pip\wheel.py", line 316, in clobber ensure_dir(destdir) File "c:\program files\python36\lib\site-packages\pip\utils\\__init__.py", line 83, in ensure_dir os.makedirs(path) File "c:\program files\python36\lib\os.py", line 220, in makedirs mkdir(name, mode) PermissionError: [WinError 5] アクセスが拒否されました。: 'c:\\program files\\py thon36\\Lib\\site-packages\\beautifulsoup4-4.6.0.dist-info' ``` と出ていたので管理者権限でコマンドプロンプトを開き同じくインストールしたらそのときはインストールできました ``` C:\WINDOWS\system32>pip install beautifulsoup4 Collecting beautifulsoup4 Using cached beautifulsoup4-4.6.0-py3-none-any.whl Installing collected packages: beautifulsoup4 Successfully installed beautifulsoup4-4.6.0 ``` ``` C:\WINDOWS\system32>pip list DEPRECATION: The default format will switch to columns in the future. You can us e --format=(legacy|columns) (or define a format=(legacy|columns) in your pip.con f under the [list] section) to disable this warning. asn1crypto (0.23.0) beautifulsoup4 (4.6.0) cffi (1.11.2) cryptography (2.1.3) idna (2.6) pip (9.0.1) pycparser (2.18) pyOpenSSL (17.4.0) setuptools (28.8.0) six (1.11.0) ``` 管理者権限でインストールしたことをおもいだしたので Program filesのアクセス権をフルコントロールしてみましたが同じ結果になりました もう一度再インストールしてみましたが管理者権限のコマンドプロンプトでしか受付せず結果同じエラーになってしまいます
[python]BeautifulSoup4をインストールしても反応しない =====================================
teratail.com
2021.25
[ { "text": "pip listの結果からbeautifulsoup4自体のインストールはできているようです。多分素のpythonを直接使うとimportできると思います。問題はPyCharmの設定にあるのだと思います。 \n\n\n詳しくないので推測ですが...PyCharmでプロジェクトを作るとvenvというフォルダーがプロジェクト直下にできていることからPyCharmではプロジェクト毎に異なる環境を作れるようになっているのだと思います。つまりプロジェクト作成直後は「pythonをインストールしただけの状態」になっているのだろうと思います。実際に`from bs4 import BeautifulSoup`とやると「モジュールがない」とエラーになります。 \n\n\nそこで「PyCharm import できない」で検索したところ対処法が書いてあるページがヒットしました。 \n\n\n対処は(自分に分かった限り)2つほどあるようで \n\n\n対処1:当該プロジェクトにネットワークからモジュールを個別インストール \n\n\nFile>Settings...>Project:プロジェクト名>Project Inspectorとし \n\n右上のProject Interpreter:でPython 3.6(プロジェクト名)を選択した状態で右のほうの緑の'+'ボタンを押す。利用可能なモジュール一覧がでる(これはインターネットの向う側のどっかのリポジトリーに登録されているものの一覧だと思います)ので、ここでモジュールを選択してインストール。最後に右下のApplyボタン&OK \n\n\n対処2:当該プロジェクトのPython環境をPCのデフォルトに合わせてしまう \n\n\nFile>Settings...>Project:プロジェクト名>Project Inspectorとし \n\n右上のProject Interpreter:でPython 3.6(C:\\Program Files\\Python\\Python36\\python.exe)を選択してApplyボタン&OK \n\n\n対処1だとせっかくPCへインストールしたものをわざわざ個別にインストールすることになるのでしょうからHDDがもったいない気がします。とりあえず対処2にしておくとPCへインストールした全てのモジュールがそのプロジェクトでimportできるようになるみたいです。 \n\n\nなお、常に対処2をするのがめんどくさい場合 \n\n\nFile>Default Settings...>Project Inspectorで対処2と同じ操作をすると新規プロジェクトを作成した場合、PCの環境と常にあった状態にすることもできそうです(やってないので想像です)\n\n", "name": "", "is_accepted": true }, { "text": "タイポです。 \n\n\nhttps://www.crummy.com/software/BeautifulSoup/ \n\n\n\n> \n> You can install Beautiful Soup 4 with pip install beautifulsoup4. \n> \n> \n> \n\n\n\n```\npip install beautifulsoup4\n```\n\nそれから \n\n\n\n```\nfrom bs4 import BeautifulSoup\n```\n\nです。\n\n", "name": "", "is_accepted": false }, { "text": "上記の書いたのは動きませんでしたので下記に動いたのを訂正します \n\n\n\n```\n#coding: UTF-8\nimport urllib.request\nfrom bs4 import BeautifulSoup\n\nurl = \"https://www.nikkei.com/\"\n\nhtml = urllib.request.urlopen(url)\n\nsoup = BeautifulSoup(html, \"html.parser\")\n\ntitle_tag = soup.span\n\nprint (title_tag)\n```\n", "name": "", "is_accepted": false } ]
9497677f1e414fb0ea4ac3d947ef2b91
ajaxのコードを書いて、サーバ上のphpファイルを実行したいのですが、ここで実行したいphpファイルは他のマシンを用意して、それをサーバとして使い、そこにphpファイルを設置するか、virtualbox等を入れて仮想環境上にphpファイルを置くか、どちらかということになるのでしょうか。 それとも上記の方法を使わずともphpファイルを実行させることは可能でしょうか。
サーバとajax通信して、phpファイルを実行したい ==========================
teratail.com
2020.05
[ { "text": "まず最初に、Ajaxのことは忘れてください。\n \n\n \nPHPが実行できる環境はお持ちですか?\n \nお持ちでないようでしたら最初に以下のステップで用意してください。\n \n1. サーバの用意\n \n2. Apache, PHPのインストールと設定\n \n3. PHPのコードを書いて動かす\n \n\n \n最終的な目標(外部に公開するのか、イントラなのか、ローカルで動けば良いのか…など)が不明ですが、サーバはレンタルサーバでも、AWSなどのクラウドでも、ご自身の端末でvirtualboxなどで運用されてもかまいません。いずれも動作します。\n \n\n \n次のApacheとPHPのインストールや設定は、Googleなどで「Apache PHP インストール」で検索するとたくさん出てきます。\n \nhttps://www.google.co.jp/search?q=apache+php+%E3%82%A4%E3%83%B3%E3%82%B9%E3%83%88%E3%83%BC%E3%83%AB\n \n\n \nここまでできたらPHPのコードを書いて、実際に動作するか確認してみましょう。\n \n\n```\n<?php\n//hello.php\necho json_encode(array('str'=>'world'));\n```\n\n \n\n \nさて、ここからAjaxの話しに入ります。\n \n先ほど作ったPHPのファイルを呼び出すために、最初は以下のようにHTMLを置いてください。\n \n* 同じドメイン\n* 同じ階層\n\n\n \n\n```\n<script src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js\"></script>\n<script>\n$.getJSON(\"hello.php\", function(json){\n  alert(\"Hello \" + json.str);\n});\n</script>\n```\nPHPの\"world\"の部分を変更すると、Ajaxでの実行結果も変わると思います。\n \n呼び出し元のHTMLと、呼び出し先のPHPでドメインが異なると、セキュリティの関係で別途設定を行ったり、JSONPなどを用いるなどの必要が出てきますので、最初は同一ドメインで行われるのがトラブルが少なくて良いかと思います。 \n", "name": "", "is_accepted": true } ]
959616996de9f9710bbc75705f10257c
質問 -- Tensorflow の実装に興味があってソースコードをいろいろといじってみたいと考えています。Cで書かれている部分も見たいため、ソースコードをGitHubからcloneしてきているのですが、ソースコードをいじるたびにビルドするには時間がかかりすぎるため、ビルドすることなく、ソースコードと同じディレクトリにTensorflowを試すために自分が書いたコードを置いていろいろと試してみたいと思っています。 ``` ├── test.py # <- tensorflowを試すために自分が書いたコード └── tensorflow ├── ACKNOWLEDGMENTS ├── ADOPTERS.md ├── AUTHORS ├── BUILD ├── CODEOWNERS ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── ISSUES.md ├── ISSUE_TEMPLATE.md ├── LICENSE ├── README.md ├── RELEASE.md ├── SECURITY.md ├── WORKSPACE ├── arm_compiler.BUILD ├── configure ├── configure.cmd ├── configure.py ├── models.BUILD ├── tensorflow ├── third_party └── tools ``` ディレクトリ構成は上のようになっていて、`test.py`が自分が書いたコードです。この状態でTensorflowを下のようにインポートしようとすると ``` import tensorflow.tensorflow as tf ``` 下のようなエラーが出ます。 ``` Traceback (most recent call last): File "test.py", line 1, in <module> import tensorflow.tensorflow as tf File "/home/yudai/Documents/Python/MachineLearning/TF2\_test/tensorflow/tensorflow/\_\_init\_\_.py", line 24, in <module> from tensorflow.python import pywrap_tensorflow # pylint: disable=unused-import ModuleNotFoundError: No module named 'tensorflow.python' ``` `test.py`から見ると`tensorflow.python`のパスは`tensorflow.tensorflow.python`なのでこのようなエラーが出てると思い、`test.py`をtensorflowディレクトリに入れ、次のようにインポートするコードを変更してみました。 ``` import tensorflow as tf ``` しかし、これを実行すると、 ``` File "/home/yudai/Documents/Python/MachineLearning/TF2\_test/tensorflow/tensorflow/python/platform/self\_check.py", line 25, in <module> from tensorflow.python.platform import build_info ImportError: cannot import name 'build\_info' from 'tensorflow.python.platform' (/home/yudai/Documents/Python/MachineLearning/TF2_test/tensorflow/tensorflow/python/platform/__init__.py) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "test.py", line 1, in <module> import tensorflow as tf File "/home/yudai/Documents/Python/MachineLearning/TF2\_test/tensorflow/tensorflow/\_\_init\_\_.py", line 24, in <module> from tensorflow.python import pywrap_tensorflow # pylint: disable=unused-import File "/home/yudai/Documents/Python/MachineLearning/TF2\_test/tensorflow/tensorflow/python/\_\_init\_\_.py", line 49, in <module> from tensorflow.python import pywrap_tensorflow File "/home/yudai/Documents/Python/MachineLearning/TF2\_test/tensorflow/tensorflow/python/pywrap\_tensorflow.py", line 25, in <module> from tensorflow.python.platform import self_check File "/home/yudai/Documents/Python/MachineLearning/TF2\_test/tensorflow/tensorflow/python/platform/self\_check.py", line 27, in <module> raise ImportError("Could not import tensorflow. Do not import tensorflow " ImportError: Could not import tensorflow. Do not import tensorflow from its source directory; change directory to outside the TensorFlow source tree, and relaunch your Python interpreter from there. ``` このようにソースディレクトリからはTensorflowをインポート出来ないと怒られます。 これはTensorflowはビルドする以外に使う方法は無いということなのでしょうか?初心者であまり良くわかってないのですが解説をよろしくお願いいたします。
Tensorflow をビルドすることなく使えるか? ==========================
teratail.com
2020.50
[ { "text": "\n> \n> これはTensorflowはビルドする以外に使う方法は無いということなのでしょうか? \n> \n> \n> \n\n\nはい。C言語やアセンブラのソースが含まれるものですので、ビルドしないと使えません。 \n\n\n(「ソースコードをいじる」というのは、Tensorflow自体を改造する、ということで間違いないでしょうか)\n\n", "name": "", "is_accepted": true } ]
3749d270132a2d0dc6608c38b837c512
いつもお世話になります。 標記について、教えていただきたいことがあります。 現在、下記のようなデータがあります。 | 主コード | hoge | | --- | --- | | 100 | AAA | | 100 | AAA | | 101 | AAA | | 102 | BBB | | 102 | BBB | | 102 | AAA | このようなとき、下記のようなデータにしたいです。 | 主コード | hogeのAAA数 | hogeのBBB数 | | --- | --- | --- | | 100 | 2 | 0 | | 101 | 1 | 0 | | 102 | 1 | 2 | 以下のようなコードで動作すると思いましたが、エラーが発生しました。 ``` df <- df %>% group_by(主コード) %>% summarise(hogeのAAAの数 = count(hoge="AAA")) df <- df %>% group_by(主コード) %>% summarise(hogeのBBBの数 = count(hoge="BBB")) ``` ``` Error in summarise_impl(.data, dots) : Evaluation error: argument "x" is missing, with no default. ``` どのようにすれば実現できるのか、教えていただければと思います。 どうぞよろしくお願い致します。
[R]条件付きのグループ単位の集計方法 ===================
teratail.com
2020.45
[ { "text": "以下のようなデータフレームがあったとして \n\n\n\n```\nhoge <- c(\"AAA\", \"AAA\", \"AAA\", \"BBB\", \"BBB\", \"AAA\")\ncode <- c(100, 100, 101, 102, 102, 102)\ndfR <- data.frame(code, hoge)\n```\n\n \n\n①tapply()を使って分類(カウントには、summary()かtable()を使用) \n\n②do.call()でデータフレームに変換 \n\n\n\n```\ndo.call(rbind, tapply(dfR$hoge, dfR$code, summary))\n```\n\n \n\nこんな感じでいかがでしょうか。 \n\n", "name": "", "is_accepted": true } ]
24460cddc7b2c50278a7eaa13c6bc5e0
nuxt.jsで作成したアプリケーションをHerokuへデプロイしたのですがアプリケーションが立ち上がりません。 ローカルでビルドした時には生成される/.nuxt ディレクトリがproduction環境のビルドでは生成されていません。どこを見ればいいのでしょうか😭 ``` 2019-04-12T08:26:05.918052+00:00 heroku[web.1]: Starting process with command `npm run start` 2019-04-12T08:26:07.854015+00:00 app[web.1]: 2019-04-12T08:26:07.854033+00:00 app[web.1]: > [email protected] start /app 2019-04-12T08:26:07.854035+00:00 app[web.1]: > nuxt start 2019-04-12T08:26:07.854037+00:00 app[web.1]: 2019-04-12T08:26:08.481707+00:00 app[web.1]: 2019-04-12T08:26:08.481750+00:00 app[web.1]: 08:26:08 FATAL No build files found in /app/.nuxt/dist/server. 2019-04-12T08:26:08.481752+00:00 app[web.1]: Use either nuxt build or builder.build() or start nuxt in development mode. 2019-04-12T08:26:08.481754+00:00 app[web.1]: 2019-04-12T08:26:08.481755+00:00 app[web.1]: Use either nuxt build or builder.build() or start nuxt in development mode. 2019-04-12T08:26:08.481758+00:00 app[web.1]: at VueRenderer.ready (node_modules/@nuxt/vue-renderer/dist/vue-renderer.js:2494:13) 2019-04-12T08:26:08.481759+00:00 app[web.1]: 2019-04-12T08:26:08.501811+00:00 app[web.1]: 2019-04-12T08:26:08.501815+00:00 app[web.1]: ╭─────────────────────────────────────────────────────────────────────────────────────╮ 2019-04-12T08:26:08.501817+00:00 app[web.1]: │ │ 2019-04-12T08:26:08.501819+00:00 app[web.1]: │ ✖ Nuxt Fatal Error │ 2019-04-12T08:26:08.501821+00:00 app[web.1]: │ │ 2019-04-12T08:26:08.501823+00:00 app[web.1]: │ Error: No build files found in /app/.nuxt/dist/server. │ 2019-04-12T08:26:08.501824+00:00 app[web.1]: │ Use either `nuxt build` or `builder.build()` or start nuxt in development mode. │ 2019-04-12T08:26:08.501829+00:00 app[web.1]: │ │ 2019-04-12T08:26:08.501831+00:00 app[web.1]: ╰─────────────────────────────────────────────────────────────────────────────────────╯ 2019-04-12T08:26:08.501832+00:00 app[web.1]: 2019-04-12T08:26:08.521234+00:00 app[web.1]: npm ERR! code ELIFECYCLE 2019-04-12T08:26:08.521644+00:00 app[web.1]: npm ERR! errno 1 2019-04-12T08:26:08.522953+00:00 app[web.1]: npm ERR! [email protected] start: `nuxt start` 2019-04-12T08:26:08.523082+00:00 app[web.1]: npm ERR! Exit status 1 2019-04-12T08:26:08.523323+00:00 app[web.1]: npm ERR! 2019-04-12T08:26:08.523428+00:00 app[web.1]: npm ERR! Failed at the [email protected] start script. 2019-04-12T08:26:08.523550+00:00 app[web.1]: npm ERR! This is probably not a problem with npm. There is likely additional logging output above. 2019-04-12T08:26:08.530132+00:00 app[web.1]: 2019-04-12T08:26:08.530287+00:00 app[web.1]: npm ERR! A complete log of this run can be found in: 2019-04-12T08:26:08.530377+00:00 app[web.1]: npm ERR! /app/.npm/_logs/2019-04-12T08_26_08_524Z-debug.log 2019-04-12T08:26:08.640055+00:00 heroku[web.1]: State changed from starting to crashed 2019-04-12T08:26:08.625855+00:00 heroku[web.1]: Process exited with status 1 ``` ``` Use either `nuxt build` or `builder.build()` or start nuxt in development mode. ``` と書いてあるのでbuildをしてみたのですがBuild succeededとなったもののエラーは変わらずです、、 追記 == 同じコードでNetlifyにデプロイしたところうまくいきました、、!! Herokuで何を間違えてたかはわかっていません。
nuxt.jsのproduction環境でのビルドが上手くできない =================================
teratail.com
2021.39
[ { "text": "こちらの通りにやってみてください。 \n\nhttps://ja.nuxtjs.org/faq/heroku-deployment/\n\n", "name": "", "is_accepted": false } ]
a3e4d4fcfdef7698d98ddd079431a4f0
スポーツのフォームチェック用に、ノートPCについているWebカメラで撮影して、任意の秒数 (1〜30秒くらいまで)を遅らせてからプレビュー画面に再生表示するソフトを開発したいです。 現状はVS Community 2015でC#フォームアプリケーション + AForge.NET 2.2.5を使っています。 まずはAForge.NETの勉強がてらWebカメラで撮影した動画をaviファイルとして保存、 再生する処理を実装する事はできました。 肝心のタイムシフト再生部分で実装方法が分からず困っています。そもそもどのような 考え方でタイムシフト再生が実現できるのか分からないというレベルです。 試した事は、保存しながら数秒後に再生させてみたのですが再生できませんでした。 (開始フレームから進まない) タイムシフト再生のご経験がありましたら方法論だけでも結構ですのでご教示頂きたく、 よろしくお願い致します。 現在のソースを記載致します。撮影〜ファイル保存処理です。最終的にはタイムシフトの プレビューをpictureBoxに表示したいです。 videoSource\_Newframeメソッド内でフレーム毎のBitmapが取得できるので、そのBitmapデータを 使って実現できそうな気もします。 ``` using System; using System.IO; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Drawing.Imaging; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using AForge.Video; using AForge.Video.DirectShow; using AForge.Video.FFMPEG; namespace WindowsFormsApplication1 { public partial class Form1 : Form { private FilterInfoCollection videoDevices; private VideoCaptureDevice videoSource; private VideoFileWriter writer; private string fileName = string.Empty; public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice); writer = new VideoFileWriter(); foreach (FilterInfo device in videoDevices) { comboBox1.Items.Add(device.Name); } videoSource = new VideoCaptureDevice(); } // 撮影開始/停止 private void button1_Click(object sender, EventArgs e) { if (videoSource.IsRunning) { terminate(); } else { videoSource = new VideoCaptureDevice(videoDevices[comboBox1.SelectedIndex].MonikerString); VideoCapabilities cap = videoSource.VideoCapabilities[0]; videoSource.NewFrame += new NewFrameEventHandler(videoSource_Newframe); videoSource.Start(); DateTime dt = DateTime.Now; fileName = dt.ToString("yyyyMMdd_HHmmss") + ".avi"; writer.Open(fileName, cap.FrameSize.Width, cap.FrameSize.Height, cap.AverageFrameRate, VideoCodec.MPEG4); } } public void videoSource_Newframe(object sender, NewFrameEventArgs eventArgs) { Bitmap image = (Bitmap)eventArgs.Frame.Clone(); /////////////////////////////// // このBitmapを使って実現できる? /////////////////////////////// writer.WriteVideoFrame(image); } private void Form1_FormClosing(object sender, FormClosingEventArgs e) { if (videoSource.IsRunning) { terminate(); } } private void terminate() { videoSource.Stop(); writer.Close(); } } } ```
Webカメラを使ったタイムシフト再生の実装方法について ===========================
teratail.com
2019.47
[ { "text": "AForge自体を使ったことがないし、コードも示されていないので、詳しいことはわからないのですが、例えばこちらのサンプルを見て判断するに。 \n\n[C#でAForge.NET Frameworkを導入する方法](http://memo.everyday.jp/archives/356) \n\nファイル出力をもって出力としているようです。 \n\n保存しながら数秒後に再生とありますから、たぶん保存したファイルを保存中に再生しているのだと思いますが、ファイルとして出力する場合、基本的にファイルがすべて出力されないと解析できない場合がほとんどです。 \n\nですので、Closeメソッドで保存を完了しないと完全なファイルではないので読み込めないのではないかと思います。 \n\n\nですので、画像単位でアクセスできるローレベルなAPIかライブラリを使ったほうが良いかもしれません。 \n\n\n例えばですが、フレームごとにBMPファイルで出力するとか、YUV形式のベタな画像データで出力するとか、そういったことができるAPIでないと実現が難しいと思います。\n\n", "name": "", "is_accepted": true } ]
77d5c27c4e951e15f3e2f16f3ec1c3ae
データベースから取得した文字列から 括弧(特定の文字列)でくくられた「HIJKJMN」を抽出してリストアップしたいです。  また、括弧でくくられていない箇所は影響うけたくないです。 ```  $length = 'ABCD)EFG(HIJKJMN)O)PQ)R('; ```
正規表現について ========
teratail.com
2020.05
[ { "text": "この正規表現で$match[1]に格納できていると思います。\n \n\n \n\n```\n $test = preg_match('/(\\(([\\w]+)[^>]*\\))/',$length , $match); \n  var_dump($match); \n```\n\n \n大枠の「HIJKJMN)OPQ」を抽出しつつ文字クラス否定で「)O)PQ)」を除外しています。 \n", "name": "", "is_accepted": true } ]
119b7626798fe24782c26b8c55c42001
皆様、質問がございます。 Atomでターミナルを操作したいと思い下記のコマンドを入力しました。 結果、npmエラーなどが生じてしまいました。 https://github.com/atom-archive/terminal/issues/28 上記サイトを見て対処しようと試みたり、stackoverfrowで同じ問題に対する解決方法をさがしたのですが、どうしても解決できません。 エラーの対象方法をお教え頂ければと思います。 宜しくお願い致します。 ``` $ apm install term2 Installing term2 to /User/.atom/packages ✗ > [email protected] install /private/var/folders/bh/qqktv0_n49vc585f8dn7hq600000gn/T/apm-install-dir-115721-23811-m9y2he/node_modules/term2/node_modules/pty.js > node-gyp rebuild   CXX(target) Release/obj.target/pty/src/unix/pty.o   SOLINK_MODULE(target) Release/pty.node ld: library not found for -lgcc_s.10.5 clang: error: linker command failed with exit code 1 (use -v to see invocation) make: *** [Release/pty.node] Error 1 gyp ERR! build error  gyp ERR! stack Error: `make` failed with exit code: 2 gyp ERR! stack     at ChildProcess.onExit (/Users/Downloads/Atom.app/Contents/Resources/app/apm/node_modules/npm/node_modules/node-gyp/lib/build.js:267:23) gyp ERR! stack     at ChildProcess.emit (events.js:98:17) gyp ERR! stack     at Process.ChildProcess._handle.onexit (child_process.js:820:12) gyp ERR! System Darwin 14.4.0 gyp ERR! command "node" "/Users/Downloads/Atom.app/Contents/Resources/app/apm/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild" gyp ERR! cwd /private/var/folders/bh/qqktv0_n49vc585f8dn7hq600000gn/T/apm-install-dir-115721-23811-m9y2he/node_modules/term2/node_modules/pty.js gyp ERR! node -v v0.10.35 gyp ERR! node-gyp -v v1.0.2 gyp ERR! not ok  npm ERR! Darwin 14.4.0 npm ERR! argv "/Users//Downloads/Atom.app/Contents/Resources/app/apm/bin/node" "/Users/Downloads/Atom.app/Contents/Resources/app/apm/node_modules/npm/bin/npm-cli.js" "--globalconfig" "/Users//.atom/.apm/.apmrc" "--userconfig" "/Users//.atom/.apmrc" "install" "/private/var/folders/bh/qqktv0_n49vc585f8dn7hq600000gn/T/d-115721-23811-j9f77o/package.tgz" "--target=0.22.0" "--arch=x64" npm ERR! node v0.10.35 npm ERR! npm  v2.5.1 npm ERR! code ELIFECYCLE npm ERR! [email protected] install: `node-gyp rebuild` npm ERR! Exit status 1 npm ERR!  npm ERR! Failed at the [email protected] install script 'node-gyp rebuild'. npm ERR! This is most likely a problem with the pty.js package, npm ERR! not with npm itself. npm ERR! Tell the author that this fails on your system: npm ERR!     node-gyp rebuild npm ERR! You can get their info via: npm ERR!     npm owner ls pty.js npm ERR! There is likely additional logging output above. npm ERR! Please include the following file with any support request: npm ERR!     /private/var/folders/bh/qqktv0_n49vc585f8dn7hq600000gn/T/apm-install-dir-115721-23811-m9y2he/npm-debug.log ```
Atomにターミナルをインストールできない。 ======================
teratail.com
2019.43
[ { "text": "`ld: library not found for -lgcc_s.10.5`で検索したところ、Xcode 7にあげないとビルドができないようです。\n \n\n \n参考: [node build fails on OS X 10.11](https://github.com/Homebrew/homebrew/issues/40653) \n", "name": "", "is_accepted": true } ]
2685dafe96a9da1ec09967b31fe157c2
### 前提・実現したいこと ドットインストールを見ながらさくらのvpsにLaravelの環境を構築しようとしています。 indexページは無事に表示されましたが、そこからリンクページに飛ばした時にNot foundになってしまいます。 ドットインストール 「Laravel 5.5入門」#15で詰まりました https://dotinstall.com/lessons/basic\_laravel\_v2 ### 発生している問題・エラーメッセージ indexページはドットインストールと同じようにちゃんと表示されます。 http://〇〇〇 ↓ そこからリンク先のページに飛ぶとnot foundになります http://〇〇〇/posts/1 ↓ ``` Not Found The requested URL /posts/1 was not found on this server. ``` ### 該当のソースコード /var/www/laravel/routes/web.php ``` <?php Route::get('/','PostsController@index'); Route::get('/posts/{id}', 'PostsController@show'); ``` /var/www/laravel/app/Http/Controllers/PostsController.php ``` <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Post; class PostsController extends Controller { public function index() { $posts = Post::latest()->get(); return view('posts.index')->with('posts', $posts); } public function show($id) { $post = Post::findOrFail($id); return view('posts.show')->with('post', $post); } } ``` /var/www/laravel/resources/views/posts/index.blade.php ``` <!DOCTYPE html> <html lang="ja"> <head> <meta charset="utf-8"> <title>Blog Posts</title> <link rel="stylesheet" href="/css/styles.css" /> </head> <body> <div class="container"> <h1>Blog Posts</h1> <ul> @forelse ($posts as $post) <li><a href="{{ action('PostsController@show', $post->id) }}">{{ $post->title }}</a></li> @empty <li>No posts yet</li> @endforelse </ul> </div> </body> </html> ``` /var/www/laravel/resources/views/posts/show.blade.php ``` <!DOCTYPE html> <html lang="ja"> <head> <meta charset="utf-8"> <title>{{ $post->title }}</title> <link rel="stylesheet" href="/css/styles.css"> </head> <body> <div class="container"> <h1>{{ $post->title }}</h1> <p>{!! nl2br(e($post->body)) !!}</p> </div> </body> </html> ``` ### 試したこと Laravel以下のファイルはユーザーapacheにして読み込み書き込みをできるようにしています ### 補足情報(FW/ツールのバージョンなど) PHP 7.1.29 Laravel Framework 5.8.16 CentOS Linux release 7.6.1810 (Core) Server version: Apache/2.4.6 (CentOS) バーチャルホストでポート8001をlaravelにしています Listen 8001 <VirtualHost *:8001> DocumentRoot /var/www/laravel/public </VirtualHost>
Laravelでindex以外のページが表示されない ==========================
teratail.com
2020.50
[ { "text": "アドバイスいただき、DocumentRootのあたりを見直していたところ、 \n\n/etc/httpd/conf/httpd.conf \n\nの記述間違いを発見できました。 \n\n\nバーチャルホストでポート8001をlaravelのフォルダにしていたのですが、 \n\n\n<誤> \n\nListen 8001 \n\n<VirtualHost *:8001> \n\nDocumentRoot /var/www/laravel/public \n\n</VirtualHost> \n\n\n<正> \n\nListen 8001 \n\n<VirtualHost *:8001> \n\nDocumentRoot /var/www/laravel/public \n\n<Directory /var/www/laravel> \n\nAllowOverride All \n\n</Directory> \n\n</VirtualHost> \n\n\n上記のように修正したところ直りました。 \n\nバーチャルホストにもAllowOverride Allを書かないといけませんでした。。 \n\nそもそもの前提段階で間違えており、回答してくださった皆様にはご迷惑をおかけしました。 \n\n\n頂いたアドバイスは知らないことばかりで勉強になりました。ありがとうございました。 \n\n", "name": "", "is_accepted": true }, { "text": "[アプリケーションの設定](https://laravel.com/docs/5.8/installation#configuration)と[Webサーバの設定](https://laravel.com/docs/5.8/installation#web-server-configuration)がちゃんと設定されているか見直してください。 \n\n今回の場合は、特にWebサーバ(Apache)の設定。念のため、Apacheの設定変更後は再起動をお忘れなく。\n\n", "name": "", "is_accepted": false } ]
47d4e7946074f1248f4076cf69ac4f00
タクトスイッチで音のモードを変えられるようにしたいのですがどうしてもわからなくて教えていただけないでしょうか。 3つのタクトスイッチをそれぞれ押すと”ド” ”レ” ”ミ”と鳴りもう一つのタクトスイッチを押すと3つの音が”ファ” ”ソ” ”ラ”と鳴るようにプログラムをしているのですが、切り替えに使うタクトスイッチの初めの切り替えはできたのですが、元に戻す時のプログラムがどうしてもわかりません。どんな仕組みにすればいいですか? まだ始めたばかりでわからないことも多いのですが教えていただけないでしょうか。 ###  作ったプログラム ``` void setup() { pinMode(A2,INPUT\_PULLUP); pinMode(A3,INPUT\_PULLUP); pinMode(A4,INPUT\_PULLUP); pinMode(A5,INPUT\_PULLUP); } int a = 0; int aqw[] = {262,294,330,349,392,440,494}; void loop() { if (digitalRead(A2)==LOW) tone(13,aqw [a],30); if (digitalRead(A3)==LOW) tone(13,aqw [a+1],30); if (digitalRead(A4)==LOW) tone(13,aqw [a+2],30); if (digitalRead(A5)==LOW) a=3;    //ここからが分かりません } ``` ###  試したこと IFやWHILE、FORなどでやってみたりしたのですが、A=1にした時何を条件にして切り替えれば良いのか分かりません.
aruduinoのタクトスイッチのことを教えてください ===========================
teratail.com
2020.34
[ { "text": "こんなかなー。 \n\n\n\n```\nvoid setup()\n{\n pinMode(A2,INPUT\\_PULLUP);\n pinMode(A3,INPUT\\_PULLUP);\n pinMode(A4,INPUT\\_PULLUP);\n pinMode(A5,INPUT\\_PULLUP);\n}\n\nint a = 0;\nint aqw[] = {262,294,330,349,392,440,494};\n\nvoid loop()\n{\n if (digitalRead(A2)==LOW) tone(13,aqw [(a * 3) + 0],30);\n if (digitalRead(A3)==LOW) tone(13,aqw [(a * 3) + 1],30);\n if (digitalRead(A4)==LOW) tone(13,aqw [(a * 3) + 2],30);\n\n if (digitalRead(A5)==LOW)\n {\n a++;\n if(a > 1) { a = 0; }\n }\n}\n```\n", "name": "", "is_accepted": true } ]
90d03a26cd196630eeb96bfebe5d41f1
macからssh接続時、 ``` ssh [email protected] ``` と入力すると ``` ubuntu@hostname:~$ ``` と表示されるのですが、以前はそのまま文字が蛍光色にひかる様になっていましたが 急に光らず、通常の文字のままで表示される様になりました。 そこで ``` source ~/.profile ``` と入力すると文字は蛍光色に戻ります。この作業が毎回必要な状況です。 pythonの仮想環境であるpyenvを操作中にこの様な不具合が出る様になりました。 元に戻るにはどうすれば良いでしょうか? .prolile ``` # ~/.profile: executed by the command interpreter for login shells. # This file is not read by bash(1), if ~/.bash\_profile or ~/.bash\_login # exists. # see /usr/share/doc/bash/examples/startup-files for examples. # the files are located in the bash-doc package. # the default umask is set in /etc/profile; for setting the umask # for ssh logins, install and configure the libpam-umask package. #umask 022 # if running bash if [ -n "$BASH\_VERSION" ]; then # include .bashrc if it exists if [ -f "$HOME/.bashrc" ]; then . "$HOME/.bashrc" fi fi # set PATH so it includes user's private bin directories PATH="$HOME/bin:$HOME/.local/bin:$PATH" ``` .bash\_profile ``` #eval "$(pyenv virtualenv-init -) export PYENV_ROOT="$HOME/.PYENV" export PATH="$PYENV\_ROOT/bin:$PATH" ``` .bashrc ``` # ~/.bashrc: executed by bash(1) for non-login shells. # see /usr/share/doc/bash/examples/startup-files (in the package bash-doc) # for examples # If not running interactively, don't do anything case $- in *i*) ;; *) return;; esac # don't put duplicate lines or lines starting with space in the history. # See bash(1) for more options HISTCONTROL=ignoreboth # append to the history file, don't overwrite it shopt -s histappend # for setting history length see HISTSIZE and HISTFILESIZE in bash(1) HISTSIZE=1000 HISTFILESIZE=2000 # check the window size after each command and, if necessary, # update the values of LINES and COLUMNS. shopt -s checkwinsize # If set, the pattern "**" used in a pathname expansion context will # match all files and zero or more directories and subdirectories. #shopt -s globstar # make less more friendly for non-text input files, see lesspipe(1) [ -x /usr/bin/lesspipe ] && eval "$(SHELL=/bin/sh lesspipe)" # set variable identifying the chroot you work in (used in the prompt below) if [ -z "${debian\_chroot:-}" ] && [ -r /etc/debian_chroot ]; then debian_chroot=$(cat /etc/debian_chroot) fi # set a fancy prompt (non-color, unless we know we "want" color) case "$TERM" in xterm-color|*-256color) color_prompt=yes;; esac # uncomment for a colored prompt, if the terminal has the capability; turned # off by default to not distract the user: the focus in a terminal window # should be on the output of commands, not on the prompt #force\_color\_prompt=yes if [ -n "$force\_color\_prompt" ]; then if [ -x /usr/bin/tput ] && tput setaf 1 >&/dev/null; then # We have color support; assume it's compliant with Ecma-48 # (ISO/IEC-6429). (Lack of such support is extremely rare, and such # a case would tend to support setf rather than setaf.) color_prompt=yes else color_prompt= fi fi if [ "$color\_prompt" = yes ]; then PS1='${debian\_chroot:+($debian\_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ ' else PS1='${debian\_chroot:+($debian\_chroot)}\u@\h:\w\$ ' fi unset color_prompt force_color_prompt # If this is an xterm set the title to user@host:dir case "$TERM" in xterm*|rxvt*) PS1="\[\e]0;${debian\_chroot:+($debian\_chroot)}\u@\h: \w\a\]$PS1" ;; *) ;; esac # enable color support of ls and also add handy aliases if [ -x /usr/bin/dircolors ]; then test -r ~/.dircolors && eval "$(dircolors -b ~/.dircolors)" || eval "$(dircolors -b)" alias ls='ls --color=auto' #alias dir='dir --color=auto' #alias vdir='vdir --color=auto' alias grep='grep --color=auto' alias fgrep='fgrep --color=auto' alias egrep='egrep --color=auto' fi # colored GCC warnings and errors #export GCC\_COLORS='error=01;31:warning=01;35:note=01;36:caret=01;32:locus=01:quote=01' # some more ls aliases alias ll='ls -alF' alias la='ls -A' alias l='ls -CF' # Add an "alert" alias for long running commands. Use like so: # sleep 10; alert alias alert='notify-send --urgency=low -i "$([ $? = 0 ] && echo terminal || echo error)" "$(history|tail -n1|sed -e '\''s/^\s*[0-9]\+\s*//;s/[;&|]\s*alert$//'\'')"' # Alias definitions. # You may want to put all your additions into a separate file like # ~/.bash\_aliases, instead of adding them here directly. # See /usr/share/doc/bash-doc/examples in the bash-doc package. if [ -f ~/.bash_aliases ]; then . ~/.bash_aliases fi # enable programmable completion features (you don't need to enable # this, if it's already enabled in /etc/bash.bashrc and /etc/profile # sources /etc/bash.bashrc). if ! shopt -oq posix; then if [ -f /usr/share/bash-completion/bash_completion ]; then . /usr/share/bash-completion/bash_completion elif [ -f /etc/bash_completion ]; then . /etc/bash_completion fi fi #pyenv export PYENV_ROOT="$HOME/.pyenv" export PATH="$PYENV\_ROOT/bin:$PATH" if command -v pyenv 1>/dev/null 2>&1; then eval "$(pyenv init -)" fi ```
ubuntu ssh接続時bashの文字に色がつかない。 ============================
teratail.com
2020.10
[ { "text": "`.bash_profile`が存在すると`.profile`は読まれません。 \n\n\n`.bash_profile`に、`. \"$HOME/.profile\"`または`. \"$HOME/.bashrc\"`という行を追加すれば良いでしょう。 \n\n", "name": "", "is_accepted": true } ]
107f8b24a994288d4b1eb792e6a70eca
`UIScreen.mainScreen().bounds` を読んでつまづきました。 ``` @availability(iOS, introduced=2.0) class UIScreen : NSObject, UITraitEnvironment, NSObjectProtocol {          // ......          var bounds: CGRect { get } // Bounds of entire screen in points     // ...... ``` この `CGRect { get }` がどういう処理を行うコードかわかりません。 `UIScreen` クラスを読んでいるといたるところに `<Type> { get }` という記述が出てきます。また `NSObjectProtocol` だと `Int { get }` や `String { get }` が。 この `<Type> { get }` の処理についてご存知のかた、回答いただけるとうれしいです。
【Swift】<Type> { get } とはなにか ===========================
teratail.com
2020.29
[ { "text": "こんにちは。\n \n\n \nSwiftに「{ get }」のみで記述されるコードはあるわけではありません。例示の記述は、プロトコルを定義する場合、プロパティの実装に関して getter(getアクセサ)を指定していることを示しています。\n \n\n \nプロトコルは、特定の名前と型をもつインスタンスプロパティやタイププロパティをクラスや構造体に実装するように要求することができます。また、その実装に際しては、getterか setterのいずれか、または両方を指定することができることになっています。\n \n\n \nちなみに、プロトコルでプロパティの実装を要求する場合には、つねに varをつけて宣言します。\n \n\n \nたとえば、Int { get } が使われる場面であれば\n \n\n \n\n```\nstruct SomeStructure {\n  var x = 0.0\n  var y = 0.0\n  var middle: Int {\n  get {\n    return (x + y) / 2\n  }\n  set {\n    x = newValue / 2\n    y = newValue / 2\n  }\n  }\n}\n```\n\n \nとか\n \n\n \n\n```\nstruct SomeStructure {\n  var x = 0.0\n  var y = 0.0\n  var middle: Int { // middleは read-only\n    return (x + y) / 2\n  }\n}\n```\nといった感じです。\n \n\n \nなお、2つ目の例のように読み出しのみ(read-only)のプロパティを定義する場合には、getや setを省略して記述することが可能です。\n \n\n \n以上、ご参考いただければ幸いです。 \n", "name": "", "is_accepted": true } ]
104868efe23ddc1a1b5ad51e1cfaf365
概要 == GeoDjango + postGIS でRESTfulなAPIを作って、GeoJsonを含むjsonデータをpost/getしたいと考えています。 そこで、初期データとしてjsonファイルをロード > > 参考サイト:[Django Rest Framework GISで誰でも簡単RESTful Geo API - monomotiの日記](http://monomoti.hatenablog.jp/entry/2015/12/15/000000) > > > してデータベースに保存された情報をDjangoのコンソール画面で確認したところ、jsonデータのうちGeoJsonの部分だけEWKTの形式に置換されてしまいました。 GeoJsonの状態で保持するにはどうしたら良いでしょうか。 Djangoの管理画面で確認されたpostGISの保持データ ============================== [![イメージ説明](https://teratail-v2.storage.googleapis.com/uploads/contributed_images/5ebd3bb4309b0c71b30046b556d5a5b8.png)](https://teratail-v2.storage.googleapis.com/uploads/contributed_images/5ebd3bb4309b0c71b30046b556d5a5b8.png) ソースコード ====== ロードしたい初期データ ----------- geojsondata.json ``` { "type": "FeatureCollection", "crs": { "type": "label", "properties": { "label": "urn:ogc:def:crs:OGC:1.3:CRS84" } }, "features": [ { "properties": { "category": "バー", "label": "Live bar Teasin'" }, "geometry": { "coordinates": [ 135.5118818, 34.6845511 ], "type": "Point" }, "type": "Feature", "id": 439 }, { "properties": { "category": "カフェ", "label": "伽奈泥庵" }, "geometry": { "coordinates": [ 135.5156035, 34.6695098 ], "type": "Point" }, "type": "Feature", "id": 440 }, { "properties": { "category": "パブ", "label": "Marciero" }, "geometry": { "coordinates": [ 135.502859, 34.703484 ], "type": "Point" }, "type": "Feature", "id": 441 }, { "properties": { "category": "レストラン", "label": "浜勝" }, "geometry": { "coordinates": [ 129.8814474, 32.7435253 ], "type": "Point" }, "type": "Feature", "id": 545 }, { "properties": { "category": "レストラン", "label": "二刀流" }, "geometry": { "coordinates": [ 135.415729, 34.719976 ], "type": "Point" }, "type": "Feature", "id": 547 } ], "type": "FeatureCollection" } ``` 初期データを読み込むためのスクリプト ------------------ load\_data.py ``` import os from django.contrib.gis.utils import LayerMapping from my_app.models import Geometry geojson_mapping = { 'label' : 'label', 'category' : 'category', 'geom' : 'POINT', } geojson_data = os.path.abspath(os.path.join(os.path.dirname(__file__), 'data', 'geojsondata.json')) def run(verbose=True): lm = LayerMapping(Geometry, geojson_data, geojson_mapping, transform=False, encoding='UTF-8') lm.save(strict=True, verbose=verbose) ``` モデル --- models.py ``` from django.contrib.gis.db import models class Geometry(models.Model): label = models.CharField(max_length=50,null=False,blank=True,default="") category = models.CharField(max_length=50,null=False,blank=True,default="") geom = models.PointField(srid=4326) def \_\_str\_\_(self): return self.label ``` シリアライザ ------ serializers.py ``` from rest_framework import serializers from my_app.models import Geometry class GeometrySerializer(serializers.ModelSerializer): class Meta: model=Geometry fields='\_\_all\_\_' read_only_fields=('\_\_all\_\_',) ``` 備考 == データベースのシェルで`CREATE EXTENSION postgis;`してあります 環境 == * python3.6.6 * django2.1.2 * postgreSQL10.5
GeoDjango + postGIS でGeoJsonがEWKTに変換されてしまう ==========================================
teratail.com
2020.50
[ { "text": "migrationsファイルを削除してマイグレートし直したら治りました\n\n", "name": "", "is_accepted": true } ]
e2e63186051664a2b44df4468a3c154a
エラーの理由がわからない。springboot 顧客管理システム 言語 java spring too; suite 顧客管理システムを本通りに作り、githubのソースコードを一字一句コピペしたのに、 エラーが出る。 何がおかしいのかわからない。 以下、エラーのソーースコード よろしくお願い申し上げます。 Exception in thread "main" org.springframework.context.ApplicationContextException: Unable to start embedded container; nested exception is org.springframework.boot.context.embedded.EmbeddedServletContainerException: Unable to start embedded Tomcat     at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:124)     at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:476)     at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:109)     at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:691)     at org.springframework.boot.SpringApplication.run(SpringApplication.java:320)     at org.springframework.boot.SpringApplication.run(SpringApplication.java:952)     at org.springframework.boot.SpringApplication.run(SpringApplication.java:941)     at com.example.App.main(App.java:12) Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration.setFilterChainProxySecurityConfigurer(org.springframework.security.config.annotation.ObjectPostProcessor,java.util.List) throws java.lang.Exception; nested exception is org.springframework.beans.factory.BeanExpressionException: Expression parsing failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'securityConfig': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter.setAuthenticationConfiguration(org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration); nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration.setGlobalAuthenticationConfigurers(java.util.List) throws java.lang.Exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'securityConfig.AuthenticationConfiguration': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: org.springframework.security.core.userdetails.UserDetailsService com.example.SecurityConfig$AuthenticationConfiguration.userDetailsService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'loginUserDetailsService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.example.repository.UserRepository com.example.service.LoginUserDetailsService.userRepository; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userRepository': Cannot create inner bean '(inner bean)#58f7da1a' of type [org.springframework.orm.jpa.SharedEntityManagerCreator] while setting bean property 'entityManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#58f7da1a': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'flyway' defined in class path resource [org/springframework/boot/autoconfigure/flyway/FlywayAutoConfiguration$FlywayConfiguration.class]: Invocation of init method failed; nested exception is org.flywaydb.core.api.FlywayException: Unable to scan for SQL migrations in location: classpath:db/migration     at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:293)     at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1186)     at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)     at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)     at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)     at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)     at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)     at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)     at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:370)     at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1095)     at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:990)     at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504)     at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactortextInitializerLifecycleListener.java:64)     at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:117)     at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:90)     at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5378)     at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)     at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1575)     at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1 略 y.invokeCustomInitMethod(AbstractAutowireCapableBeanFactory.java:1682)     at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1621)     at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1550)     ... 133 more Caused by: org.flywaydb.core.api.FlywayException: Wrong migration name format: V1_create-schema.sql(It should look like this: V1\_2\_\_Description.sql)     at org.flywaydb.core.internal.resolver.MigrationInfoHelper.extractVersionAndDescription(MigrationInfoHelper.java:51)     at org.flywaydb.core.internal.resolver.sql.SqlMigrationResolver.extractMigrationInfo(SqlMigrationResolver.java:139)     at org.flywaydb.core.internal.resolver.sql.SqlMigrationResolver.resolveMigrations(SqlMigrationResolver.java:116)     ... 156 more
エラーの理由がわからない。springboot 顧客管理システム java 一字一句コピペ =============================================
teratail.com
2020.16
[ { "text": "スタックトレースに \n\n**Caused by: org.flywaydb.core.api.FlywayException: Wrong migration name format: V1_create-schema.sql(It should look like this: V1\\_2\\_\\_Description.sql)** \n\n(マイグレーション名が違います。V1_create\\_schema.sqlじゃなくてV1\\_2_Description.sqlであるべきです) \n\n\nって書かれてるのでまずはそれに対応してみては。 \n\n", "name": "", "is_accepted": true } ]
369df3b966fe09fbf47974db5c29d29c
ViewController.swiftに記載のボタンアクションで、別ファイル(ShareManager.swift)に記載したクラスからアクションシートを表示させ、シートをタップするとFacebook、Twitterをシェアするためのダイアログを表示させようとしているのですが、それが表示されません。 アクションシートを表示さるところまではうまく行ってます。 ``` // ViewController.swift import UIKit import Social class ViewController: UIViewController { @IBAction func btnShowAction(sender: AnyObject) { let showAction = shareManager().showActionSheet() presentViewController(showAction as! UIViewController, animated: true, completion: nil) } func showSNS(i: Int) { let dialog = shareManager().setSNS(i) // print(dialog)は返ってきてる presentViewController(dialog as! UIViewController, animated: true, completion: nil) } override func viewDidLoad() { super.viewDidLoad() } } ``` ``` // ShareManager.swift import UIKit import Social class shareManager { func showActionSheet() -> AnyObject { let actionSheet = UIAlertController() actionSheet.addAction( UIAlertAction(title: "Facebook", style: .Default, handler: {(action) -> Void in ViewController().showSNS(0) }) ) actionSheet.addAction( UIAlertAction(title: "Twitter", style: .Default, handler: {(action) -> Void in ViewController().showSNS(1) }) ) actionSheet.addAction( UIAlertAction(title: "キャンセル", style: .Cancel, handler: nil) ) return actionSheet } func setSNS(i: Int) -> AnyObject { var dialog = SLComposeViewController() switch i { case 0: dialog = SLComposeViewController(forServiceType: SLServiceTypeFacebook) case 1: dialog = SLComposeViewController(forServiceType: SLServiceTypeTwitter) default: break } dialog.setInitialText("共有するテキスト") return dialog } } ``` 下記のWarningが出てたのでネットで検索して > > Warning: Attempt to present <SLComposeViewController: 0x1769f2f0> on <test.ViewController: 0x176dc240> whose view is not in the window hierarchy! > > > 表示させるタイミングなのかと思って遅延処理を入れてみたのですが、それでもダメでした。 ``` // ViewController.swift let delayTime = dispatch_time(DISPATCH\_TIME\_NOW, Int64(1 * Double(NSEC\_PER\_SEC))) dispatch_after(delayTime, dispatch_get_main_queue()) { self.presentViewController(dialog as! UIViewController, animated: true, completion: nil) } ``` 環境 Xcode 7.3 Swift 2.2 まだまだ理解できていないこともありますが、よろしくお願いいたします。
Swiftでアクションシート表示後のシートをタップしても動作しない =================================
teratail.com
2021.04
[ { "text": "問題は \n\n`ViewController().showSNS(0)` \n\nです。 \n\nこれは`ViewController()`で新しいインスタンスのViewControllerを生成し、 \n\nその新しいViewControllerの`showSNS()`を呼び出しています。 \n\n現在表示中でない新しいViewControllerを使って画面遷移しようとしているので、 \n\n「whose view is not in the window hierarchy!」 \n\nというエラーになっています。 \n\n現在表示中のViewControllerは、これとは別のViewControllerです。 \n\nその現在表示中のViewControllerを使って画面遷移する必要があります。 \n\n\nとりあえず`showActionSheet()`を`showActionSheet(vc:ViewController)`のように変更してViewControllerをパラメータで受け取れるようにした上で、`ViewController().showSNS(0)`を`vc.showSNS(0)`とし、 \n\n`let showAction = shareManager().showActionSheet(self)`という形で呼び出せば、たぶんうまく表示できると思います。 \n\n", "name": "", "is_accepted": true } ]
c644f4e0e42c0f684566b9cbc18ba353
``` コード #include<stdio.h> int main(void) { FILE *ofp; FILE *wfp; int score = 0, max = 0, min = 100, i = 1, sc; char str[100]; static char *a, *b; ofp = fopen("TEST.txt", "r"); wfp = fopen("RESULT.txt", "w"); if (ofp == NULL || wfp == NULL) { printf("ファイルをオープンできませんでした"); return 1; } else { printf("ファイルをオープンしました\n"); } while (fscanf(ofp, "%s", str) != EOF && (fscanf(ofp, "%d", &sc) != EOF)) { if (max < sc) { max = sc; a = str; printf("最大%s\n", a); } if (min > sc) { min = sc; b = str; printf("最小%s\n", b); } printf(" 最大%s\n", a); printf(" 最小%s\n", b); score += sc; fprintf(wfp, "%s %d\n", str, sc); i++; } fprintf(wfp, "合計%d点 平均%d点\n最大値%s %d\n最小値%s %d\n", score, score / (i - 1), a, max, b, min); fclose(ofp); fclose(wfp); return 0; } ``` TEST.txt A 20 B 40 C 35 D 60 F 70 G 50 H 85 I 65 J 80 K 95 RESULT.txt A 20 B 40 C 35 D 60 F 70 G 50 H 85 I 65 J 80 K 95 合計600点 平均60点 最大値K 95 最小値K 20 最大値と最小値の人の部分が最後のKになります。どうすればa,bに保存されますか?おそらくif関数から出たときにおかしくなっています。
AからJの10名分のテストの成績を記載したファイルTEST.txtを読み込み, 10名の合計点,10名の平均点,最高点(人と点数),最低点(人と点数) を別のファイルに出力するプログラムを作りなさい ===================================================================================================
teratail.com
2021.10
[ { "text": "`b = str;`とした時点で、bはstrのアドレスを指します。 \n\nその後のprintfでstrの先頭アドレスから終端までの文字列が表示されます。 \n\n\nstrの中身をbに代入したい場合は以下のようになります(極力ソースを変更しない前提で)。 \n\n*すみませ、文字化け対策で勝手に英語に変えてしまいました。 \n\n\n\n```\n#include<stdio.h>\nint main(void) {\n FILE *ofp;\n FILE *wfp;\n int score = 0, max = 0, min = 100, i = 1, sc;\n char str[100];\n static char *a, *b, temp;\n ofp = fopen(\"TEST.txt\", \"r\");\n wfp = fopen(\"RESULT.txt\", \"w\");\n if (ofp == NULL || wfp == NULL) {\n printf(\"Cannot Open File\\n\");\n return 1;\n }\n else {\n printf(\"File Opened\\n\");\n }\n while (fscanf(ofp, \"%s\", str) != EOF &&\n (fscanf(ofp, \"%d\", &sc) != EOF)) {\n if (max < sc) {\n max = sc;\n a = str;\n printf(\"Max %s\\n\", a);\n }\n if (min > sc) {\n min = sc;\n temp = *str;\n b = &temp;\n printf(\"Min %s\\n\", b);\n } \n printf(\" Max %s\\n\", a);\n printf(\" Min %s\\n\", b);\n score += sc;\n fprintf(wfp, \"%s %d\\n\", str, sc);\n i++;\n }\n\n fprintf(wfp, \"Sum %d, Ave %d\\n Max %s %d\\nMin %s %d\\n\", score, score / (i - 1), a, max, b, min);\n fclose(ofp);\n fclose(wfp);\n return 0;\n}\n```\n\n変更箇所は以下です。 \n\n\n\n```\nstatic char *a, *b, temp;\ntemp = *str;\nb = &temp;\n```\n\n \n\nただし、この方法では文字列が一文字の場合しか対応できません。\n\n", "name": "", "is_accepted": true }, { "text": "\n> \n> 最大値と最小値の人の部分が最後のKになります \n> \n> \n> \n\n\n\n```\n :\na = str;\n :\nb = str;\n :\n```\n\n \n\na も b も str を指すだけだからです. \n\nポインタや文字列のコピーについて学習・復習されては如何でしょうか.\n\n", "name": "", "is_accepted": false }, { "text": "VSCode等の統合開発環境で該当プログラムを動かして、デバッグを行い、 \n\nステップ実行で変数の値を確認してください。 \n\nそうすれば想定と違っている部分が見えるはずです。 \n\n", "name": "", "is_accepted": false }, { "text": "名前を保存する領域を別に用意して、名前をコピーする手もありますよ。 \n\n\n\n```\n#include <stdio.h>\n#include <string.h>\n\nint main(void) {\n int score, sum_score = 0, max_score = 0, min_score = 100;\n char name[100] = \"\", max_name[100] = \"\" , min_name[100] = \"\" ;\n FILE *rfp = fopen(\"TEST.txt\", \"r\");\n FILE *wfp = fopen(\"RESULT.txt\", \"w\");\n if (rfp == NULL || wfp == NULL) {\n printf(\"Cannot Open File\\n\");\n return 1;\n }\n printf(\"File Opened\\n\");\n int n = 0;\n while (fscanf(rfp, \"%s\", name) == 1 &&\n fscanf(rfp, \"%d\", &score) == 1) {\n if (max_score < score) {\n max_score = score;\n strcpy(max_name, name);\n printf(\"Max %s\\n\", max_name);\n }\n if (min_score > score) {\n min_score = score;\n strcpy(min_name, name);\n printf(\"Min %s\\n\", min_name);\n }\n printf(\" Max %s\\n\", max_name);\n printf(\" Min %s\\n\", min_name);\n sum_score += score;\n fprintf(wfp, \"%s %d\\n\", name, score);\n n++;\n }\n\n fprintf(wfp, \"Sum %d, Ave %d\\nMax %s %d\\nMin %s %d\\n\",\n sum_score, sum_score / n, max_name, max_score, min_name, min_score);\n fclose(rfp);\n fclose(wfp);\n return 0;\n}\n```\n", "name": "", "is_accepted": false } ]
a5e8ee839cdc9e8433d470c96cdfba6a
swiperを使用してスライドを作成しようとしたのですが 複数同時に動かすスライドでfadeがつかえません。 (fadeを指定すると一枚表示になってしまう) 複数枚でfadeのスライドは作れますか? ``` <div class="swiper-container">  <div class="swiper-wrapper">   <div class="swiper-slide"><img src="images/1.jpg" alt=""></div>   <div class="swiper-slide"><img src="images/2.jpg" alt=""></div>   <div class="swiper-slide"><img src="images/3.jpg" alt=""></div>   <div class="swiper-slide"><img src="images/4.jpg" alt=""></div>  </div> <div class="swiper-pagination"></div> <div class="swiper-button-prev prev1"></div> <div class="swiper-button-next next1"></div> ``` ``` var myslidemain = new Swiper('.swiper-container', { slidesPerView: 3, effect: 'fade', loop: true, autoplay: { delay: 3000, stopOnLastSlide: false, disableOnInteraction: false, reverseDirection: false }, navigation: { nextEl: '.swiper-button-next', prevEl: '.swiper-button-prev' }, pagination: { el: '.swiper-pagination', type: 'bullets', clickable: true } }); ```
swiper 複数表示でフェードするスライドができない ===========================
teratail.com
2020.40
[ { "text": "\n> \n> fade effect designed to be used ONLY with slidesPerView: 1 \n> \n> [Effect: 'fade' and slidesPerView: 4 not working together · Issue #2062 · nolimits4web/swiper · GitHub](https://github.com/nolimits4web/Swiper/issues/2062)\n> \n> \n> \n\n", "name": "", "is_accepted": true } ]
1c629d04afe7e9cea84f10462381dde9
会社にある既存サイトでPHPコードの修正処理をしています。 ひとつのIDのもとにいくつの階層が存在するのかを調べようとしたら、「Fatal error: Maximum function nesting level of '100' reached, aborting!」とエラーが出てしまいました。 エラー内容について調べてみたら、PHPでは、ループカウントが100以上の再帰呼び出しはできないとのこと。調べるIDは103個くらいなので、あと3個融通が利かないのか!と思ってしまいます。 php.iniの設定変更などでどうにかなるものでしょうか?詳しい方、どうぞよろしくお願いします。
Fatal error: Maximum function nesting level of '100' reached, aborting! =======================================================================
teratail.com
2020.05
[ { "text": "PHPにおいて再帰的なループ処理を行う場合、ループカウントが100回を超えてしまうとエラーが発生します。\n \n\n \n通常処理の見直しが必要となりますが、このループカウントが100回とあと少しという場合には、Xdebugの設定を変更することでカウント数を変えることが可能です。\n \n\n \nXdebugが入っていれば「xdebug.max\\_nesting\\_level=150」とすることで、150までネストの最大値を増やすことができますよ。\n \n\n \nもし、Xdebugが入っていなければpeclコマンドを利用してインストールして下さい。\n \nxdebugは個人的には便利なモジュールだと思いますよ。試してみてください。 \n", "name": "", "is_accepted": true } ]
9fc5110ac6cc96d4c0ed36666a83c8e2
``` <html> <body> <table> <?php foreach ((array)$records as $row) { <tr><td><?=$row['name']?></td> <td><?=$row['sex']?></td> <td><?=$row['birthday']?></td> </tr> } ?> </table> </body> </html> ``` ``` <html> <body> <table> <?php foreach ((array)$records as $row): ?> <tr> <td><?=$row['name']?></td> <td><?=$row['sex']?></td> <td><?=$row['birthday']?></td> </tr> <?php endforeach; ?> </table> </body> </html> ``` viewコードのforeachの部分です。下の場合は動作し、上のコードだと動かないのですが、どこがおかしいのでしょうか。 
foreach文について ============
teratail.com
2021.25
[ { "text": "インデントくらい揃えてね。 \n\n\n\n```\n<html>\n <body>\n <table>\n <?php foreach ((array) $records as $row) { ?>\n <tr><td><?= $row['name'] ?></td>\n <td><?= $row['sex'] ?></td>\n <td><?= $row['birthday'] ?></td>\n </tr>\n <?php } ?>\n </table>\n </body>\n</html>\n```\n", "name": "", "is_accepted": true }, { "text": "これでもいいかも \n\n\n\n```\n<?PHP\n$records=[\n [\"name\"=>11,\"sex\"=>12,\"birthday\"=>13],\n [\"name\"=>21,\"sex\"=>22,\"birthday\"=>23],\n [\"name\"=>31,\"sex\"=>32,\"birthday\"=>33],\n ];\n?>\n<html>\n<body>\n<table>\n<?php\nforeach ((array)$records as $row){\n print <<<eof\n<tr>\n<td>{$row['name']}</td>\n<td>{$row['sex']}</td>\n<td>{$row['birthday']}</td>\n</tr>\n\neof;\n}\n?>\n</table>\n</body>\n</html> \n```\n", "name": "", "is_accepted": false }, { "text": "\n```\n<html>\n <body>\n <table>\n <?php foreach ((array)$records as $row) { ?>\n<tr><td><?=$row['name']?></td>\n <td><?=$row['sex']?></td>\n <td><?=$row['birthday']?></td>\n </tr>\n<?php } ?>\n </table>\n </body>\n </html> \n```\n", "name": "", "is_accepted": false }, { "text": "\n```\n <?php <?php echo $row; ?> ?>\n```\n\n \n\nこれはどう見える?\n\n", "name": "", "is_accepted": false } ]
159de390b63eee98acb0e287a1acf308
画像アップロードを含めた「レコードへの複数挿入」を実行すると、「挿入時に画像データがカラムに入らない」というエラーになる問題で困っています。 原因または解決策をご存知の方はいらっしゃいませんか。 私の行った手順は以下です。 (1)同一テーブルカラムの中にある複数のレコードに挿入処理を掛けるFormの記述 (2)form側のname属性の最後に[]をつけ、array型でsubmit (3)Controller側でsubmitされたrequestデータを受け取り、画像データのみヴァリデーションを行う (4)Controller側で受け取った複数レコードのデータをforeachで回し、また各$requestデータの最後に[i]をくっつける (5)AWSとS3を繋げ、画像データはS3のバケットに保存。また画像パスや他のカラムに対するレコード全てをBookテーブルに保存 すると、以下のような結果になりました。 [![イメージ説明](https://teratail-v2.storage.googleapis.com/uploads/contributed_images/5dbf65c83c3187081f48fe4a99dcb7fd.png)](https://teratail-v2.storage.googleapis.com/uploads/contributed_images/5dbf65c83c3187081f48fe4a99dcb7fd.png) 私は【3つのinputにデータを入れ込んでいるため、複数レコードが挿入できる】と思いました。 原因を確かめるため、inputタグを1行のみにし、 >(2)form側のname属性の最後に[]をつけ、array型でsubmit >(4)Controller側で受け取った複数レコードのデータをforeachで回し、また各$requestデータの最後に[i]をくっつける など、array型で渡すことを前提としたコードを全て、1行レコード更新用のコードに書き換えました。すると、こちらではうまく挿入することができました。 なお、私の環境は以下の通りです。 【MacBook Air (13-inch, Early 2015), 8 GB 1600 MHz DDR3,  AWS, Laravel5.8.21】 以前、画像データを含まない複数レコードの挿入は成功しているのですが、画像データを含むとコードが複雑化し、どのようにすればいいのか分からない状態です。 解決策を教えていただけますと幸いです。 ●Controller ``` public function registrateNewBook(Request $request){ $this->validate($request, [ 'photo\_path' => [ // 必須 'required', // アップロードされたファイルであること 'file', // 画像ファイルであること 'image', // MIMEタイプを指定 'mimes:jpeg,png', // 最小縦横20px 最大縦横500px 'dimensions:min\_width=20,min\_height=20,max\_width=500,max\_height=500', ] ]); if ($request->file('photo\_path')->isValid([])) { $path = $request->photo_path->store('photo', 's3'); Storage::disk('s3')->setVisibility($path, 'public'); $url = Storage::disk('s3')->url($path); $i = 0; foreach($request->num as $val){ $book = new Book; $book->category_id = $request->category_id[$i]; $book->title = $request->title[$i]; $book->author = $request->author[$i]; $book->isbn = $request->isbn[$i]; $book->price = $request->price[$i]; $book->publisher = $request->publisher[$i]; $book->status = $request->status[$i]; $book->photo_path = $url[$i]; $book->save(); $i++; } return view('supplier.registration'); } else { return redirect() ->back() ->withInput() ->withErrors(['file' => '画像がアップロードされていないか不正なデータです。']); } } ``` ●view ``` <form action="/registrateNewBook" method="post" enctype="multipart/form-data"> {{ csrf_field() }} @for($i = 0 ; $i < 3; $i ++) <tr> <td><input type="text" name="title[]"></td> <td><input type="text" name="author[]"></td> <td><input type="text" name="publisher[]"></td> <td><input type="text" name="isbn[]"></td> <td><input type="text" name="price[]"></td> <td><input type="file" name="photo\_path[]"></td> <td> <select name="status[]"> <option value="1">新品同様</option> <option value="2">古本</option> <option value="3">汚い</option> <option></option> </select> </td> <td> <select name="category\_id[]"> <option value="1">小説</option> <option value="2">ノンフィクション</option> <option value="3">ビジネス</option> <option value="4">漫画</option> <option value="5">その他</option> </select> </td> </tr> @endfor <tr><td><input type="submit" value="登録"></td></tr> </form> ``` また、以下に成功した「画像アップロードを含めた単一レコード挿入」のコードも記載いたします。 ●Controller ``` public function registrateNewBook(Request $request){ $this->validate($request, [ 'photo\_path' => [ // 必須 'required', // アップロードされたファイルであること 'file', // 画像ファイルであること 'image', // MIMEタイプを指定 'mimes:jpeg,png', // 最小縦横20px 最大縦横500px 'dimensions:min\_width=20,min\_height=20,max\_width=500,max\_height=500', ] ]); if ($request->file('photo\_path')->isValid([])) { $path = $request->photo_path->store('photo', 's3'); Storage::disk('s3')->setVisibility($path, 'public'); $url = Storage::disk('s3')->url($path); $book = new Book; $book->category_id = $request->category_id; $book->title = $request->title; $book->author = $request->author; $book->isbn = $request->isbn; $book->price = $request->price; $book->publisher = $request->publisher; $book->status = $request->status; $book->photo_path = $url; $book->save(); return view('supplier.registration'); } else { return redirect() ->back() ->withInput() ->withErrors(['file' => '画像がアップロードされていないか不正なデータです。']); } } ``` ●View ``` <form action="/registrateNewBook" method="post" enctype="multipart/form-data"> {{ csrf_field() }} <tr> <td><input type="text" name="title"></td> <td><input type="text" name="author"></td> <td><input type="text" name="publisher"></td> <td><input type="text" name="isbn"></td> <td><input type="text" name="price"></td> <td><input type="file" name="photo\_path"></td> <td> <select name="status"> <option value="1">新品同様</option> <option value="2">古本</option> <option value="3">汚い</option> <option></option> </select> </td> <td> <select name="category\_id"> <option value="1">小説</option> <option value="2">ノンフィクション</option> <option value="3">ビジネス</option> <option value="4">漫画</option> <option value="5">その他</option> </select> </td> </tr> <tr><td><input type="submit" value="登録"></td></tr> </form> ```
画像アップロードを含めた「レコードへの複数挿入」の方法 ===========================
teratail.com
2021.25
[ { "text": "バリデーションが単体について書かれているため。 \n\n複数の画像を送った時、photo\\_pathはfileではなく、arrayです。 \n\nphoto\\_path.0 について、バリデーションをする、というようにすれば修正されるはずです。 \n\n0,1とやっていくとキリがないので、photo\\_path.*に書き換えればできると思います\n\n", "name": "", "is_accepted": false } ]
9266a0ed36231fd09e0843feec86b894
お世話になっています。エラーの指示通り、Rails serverを使っても 起動できなくなってしまったので、お助けくださいませ。 OS: Apple Yosemite Ruby: ruby 2.2.2p95 Rails: rails 4.2.6  1. Rails serverをすると、出てくるエラー Could not find climate\_control-0.0.3 in any of the sources Run `bundle install` to install missing gems.  2. Gemfileを書き換えて、bundle install する時のエラー An error occurred while installing libv8 (3.16.14.13), and Bundler cannot continue. Make sure that `gem install libv8 -v '3.16.14.13'` succeeds before bundling. ``` source 'https://rubygems.org' # Bundle edge Rails instead: gem 'rails', github: 'rails/rails' gem 'rails', '4.2.6' # Use sqlite3 as the database for Active Record gem 'pg' # Use SCSS for stylesheets gem 'sass-rails', '~> 5.0' # Use Uglifier as compressor for JavaScript assets gem 'uglifier', '>= 1.3.0' # Use CoffeeScript for .coffee assets and views gem 'coffee-rails', '~> 4.1.0' gem 'execjs' gem 'therubyracer' # gem 'therubyracer', platforms: :ruby gem 'momentjs-rails' # Use jquery as the JavaScript library gem 'jquery-rails' # Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks gem 'turbolinks' # Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder gem 'jbuilder', '~> 2.0' # bundle exec rake doc:rails generates the API under doc/api. gem 'sdoc', '~> 0.4.0', group: :doc gem 'jquery-turbolinks' # Use ActiveModel has\_secure\_password # gem 'bcrypt', '~> 3.1.7' # Use Unicorn as the app server # gem 'unicorn' # Use Capistrano for deployment # gem 'capistrano-rails', group: :development group :development, :test do # Call 'byebug' anywhere in the code to stop execution and get a debugger console gem 'byebug' gem 'better\_errors' gem 'binding\_of\_caller' end group :development do # Access an IRB console on exception pages or by using <%= console %> in views gem 'web-console', '~> 2.0' # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring gem 'spring' end gem "paperclip", "~> 5.0.0.beta1" gem 'seedbank' gem 'pry' gem 'pry-rails' gem 'pry-doc' gem 'pry-byebug' gem 'pry-stack\_explorer' gem 'climate\_control', '~> 0.0.3' ```  3. gem install libv8 -v '3.16.14.13'をターミナルで入力して出てくるエラー ERROR:  Error installing libv8:     ERROR: Failed to build gem native extension. どうぞ宜しくお願いいたします。
Rails serverができません。。 ====================
teratail.com
2019.47
[ { "text": "gem install libv8 に失敗する。 \n\nhttp://qiita.com/s\\_osa/items/6e563304fcdcf86afcfa \n\n\nの手順でどうでしょうか? \n\n", "name": "", "is_accepted": true } ]