ツタンラーメンの忘備録

プログラミングや精神疾患、ラーメンについて書いていきます。たぶん。

各言語の複数戻り値

知っている範囲で関数から複数の戻り値を返したいなーって思ってちょこちょこ調べている。少しまとめておこうと思います
私が一番好きなのはjavascript(言語自体は嫌い)

function my_swap(x, y){
	var r;
	r = {
		after_x:y,
		after_y:x
	};
	return r;
}

a = my_swap(1, 2);
console.log(a.after_x); //2
console.log(a.after_y); //1

一つのオブジェクトを返しているので正確には複数戻り値と言わないのかもわかりませんが。

rubyはそのまま複数返せるらしい。配列として返している扱いらしいです。

def my_swap(x, y)
	return y, x
	#return [y, x]
end

a, b = my_swap(1, 2)
print(a) #2
print(b) #1

pythonrubyと似たようなもんらしい。ただしこっちはタプル型で返ってきているとか

def my_swap(x, y):
    return y, x

a, b = my_swap(1, 2)
print a #2
print b #1

関数で複数の返り値を返す方法 - おっぱいそん!
jsっぽく戻り値を書く方法もちゃんとある。


Processingはない(javaベースなので)
Arduinoない(Cベースなので)
processingとArduinoはそもそもグローバル変数が多くなりがちな言語なので特殊かな。

ちなみにopenframeworksもない?(C++なので)

需要なさそうだけどVBAでどう複数戻り値を得るかというと配列として返せる

Function MySwap(X As Integer, Y As Integer) As Variant
	Dim R(1) as Variant
	R(0) = Y
	R(1) = X
	MySwap = R
End Function

Dim A As Variant
A = MySwap(1, 2)
MsgBox A(0) '2
MsgBox A(1) '1

Cのポインタ的にも返せる(これを返しているというのかは別として)。

関数/メソッドから複数の値を返すには(多値返却) | hydroculのメモ

エクセルの予測変換→勝手にその文章にされる現象を止める方法

「オートコンプリート」という言葉を知らなかったので、探すのに少し手間取りました。
ex2013bom.jugem.jp
単純ですね。

それにしてもExcelは親切過ぎてうーん…。いいんだか悪いんだか。

オートコンプリートという言葉を知らなくてもマクロのバイトを二年程度しているんですよね…。

WindowsでAnacondaを入れるときにつまずいた

windowsではpyenvが使えなさそうで、pythonのバージョン切り替えるのめんどくさいなーと思っていたらAnacondaを見つけます。
さっそく入れようとしました

C:\日本語

にいれようとすると怒られるので、

C:\work

というjavaやらrubyファイルがざったに入っているところにファイルを展開しました。
そしたら見事に散乱しました。ライブラリ?系の外部ファイル?とjavaやらrubyファイルが混在する気持ち悪い状況に。
さっそくアンインストールしまいた。

workが消えた。

たぶん知っている人は当たり前なんでしょうけど、全く知らなかったです。
javaファイルやらは闇に呑まれました。
だいたいHello worldなので復旧方法は探さなかったです。

データサイエンティストを目指す人のpython環境構築 2016 - Qiita
ここを見て早速仮想環境を作ろうとしたのですが

activate py3
conda env list

したのですが、py3がactivateされない。

PowerShellでAnacondaの仮想環境をactivateするメモ - Qiita

答えがありました。つまりコマンドプロンプトでやれば大丈夫ですね。
では~


でも、PowerShellでやりたくて、上記を試しました。
エラーが出ます。そのエラーは
www.atmarkit.co.jp
で解決できます。あんまりやりたくないですけど…。

でも、これやってもdeactivateは失敗しました。
それはまた調べます。

WordPressにJetpackを入れるのに意外と手間取った。

さくらネット上のwordpressを稼働したときに、どうもJetpackとの連携がうまくいかない。

その理由はjetpackとの連携の時のwordpressアカウントをさくらネット上で作ったwordpressアカウントと分けないといけない…らしい。独自ドメインでの設定ではこうなった(独自ドメインでない時はならなかった)

WindowsのopenFrameworksでLeap Motionを使えるようにする

手軽にまとまった記事がないのでここでまとめて記載する。

1. Visual C++で必要な処理
2. oFで必要な処理
の二点にわかれる。

1. VC++に関して
下記記事を参考
www.naturalsoftware.jp

2. oFに関して
下記記事を参照
gndo.blogspot.jp
Macの記事だけど基本的にoFと名前が被っているところをどうにかするだけ。
サンプルコードも

testApp::drawSphere(Vector vector, float radius) {
//を
ofApp::drawSphere(Vector vector, float radius) {
//に変える

だけです。簡単!

ただWindowsにまとまったサイトがなかったのでここを参照してくださいということで。
下記サンプルは実験するには冗長なので、軽く遊びたいだけなら上記サイトを見てください。


でサンプルコードと合わせて球を表示させつつなんかコンソールにむっちゃ表示させるようにした。

//ofApp.h
#pragma once

#include "ofMain.h"
#include "Leap.h"
using namespace Leap;
class ofApp : public ofBaseApp, public Listener{

	public:
		void setup();
		void update();
		void draw();

		void keyPressed(int key);
		void keyReleased(int key);
		void mouseMoved(int x, int y );
		void mouseDragged(int x, int y, int button);
		void mousePressed(int x, int y, int button);
		void mouseReleased(int x, int y, int button);
		void mouseEntered(int x, int y);
		void mouseExited(int x, int y);
		void windowResized(int w, int h);
		void dragEvent(ofDragInfo dragInfo);
		void gotMessage(ofMessage msg);

		// Leap Motionのコントローラー
		Controller leap;
		// カメラ
		ofCamera camera;
		// 球体の描画処理
		void drawSphere(Vector vector, float radius);


		//----- 一過性のイベントだけListnerから取得 ----------------------------//
		//----- フレームの処理はdraw()で行う -----------------------------------//
		void onConnect(const Controller&) {
			cout << __FUNCTION__ << endl;
		}

		void onDisconnect(const Controller&) {
			cout << __FUNCTION__ << endl;
		}

		void onFocusGained(const Controller&) {
			cout << __FUNCTION__ << endl;
		}

		void onFocusLost(const Controller&) {
			cout << __FUNCTION__ << endl;
		}

		void onServiceConnect(const Controller&) {
			cout << __FUNCTION__ << endl;
		}

		void onServiceDisconnect(const Controller&) {
			cout << __FUNCTION__ << endl;
		}
		//------------------------------------------------------------//
};
//ofApp.cpp
#include "ofApp.h"

const std::string fingerNames[] = { "Thumb", "Index", "Middle", "Ring", "Pinky" };
const std::string boneNames[] = { "Metacarpal", "Proximal", "Middle", "Distal" };
const std::string stateNames[] = { "STATE_INVALID", "STATE_START", "STATE_UPDATE", "STATE_END" };

//--------------------------------------------------------------
void ofApp::setup(){
	// カメラの初期位置と方向を指定
	camera.setFov(60);
	camera.setPosition(0, 200, ofGetWidth() / 3);
	camera.lookAt(ofVec3f(0, 200, 0));
	//ofSetFrameRate(1);
}

//--------------------------------------------------------------
void ofApp::update(){
	const Frame frame = leap.frame();
	std::cout << "Frame id: " << frame.id()
		<< ", timestamp: " << frame.timestamp()
		<< ", hands: " << frame.hands().count()
		<< ", extended fingers: " << frame.fingers().extended().count()
		<< ", tools: " << frame.tools().count()
		<< ", gestures: " << frame.gestures().count() << std::endl;

	HandList hands = frame.hands();
	for (HandList::const_iterator hl = hands.begin(); hl != hands.end(); ++hl) {
		// Get the first hand
		const Hand hand = *hl;
		std::string handType = hand.isLeft() ? "Left hand" : "Right hand";
		std::cout << std::string(2, ' ') << handType << ", id: " << hand.id()
			<< ", palm position: " << hand.palmPosition() << std::endl;
		// Get the hand's normal vector and direction
		const Vector normal = hand.palmNormal();
		const Vector direction = hand.direction();

		// Calculate the hand's pitch, roll, and yaw angles
		std::cout << std::string(2, ' ') << "pitch: " << direction.pitch() * RAD_TO_DEG << " degrees, "
			<< "roll: " << normal.roll() * RAD_TO_DEG << " degrees, "
			<< "yaw: " << direction.yaw() * RAD_TO_DEG << " degrees" << std::endl;

		// Get the Arm bone
		Arm arm = hand.arm();
		std::cout << std::string(2, ' ') << "Arm direction: " << arm.direction()
			<< " wrist position: " << arm.wristPosition()
			<< " elbow position: " << arm.elbowPosition() << std::endl;

		// Get fingers
		const FingerList fingers = hand.fingers();
		for (FingerList::const_iterator fl = fingers.begin(); fl != fingers.end(); ++fl) {
			const Finger finger = *fl;
			std::cout << std::string(4, ' ') << fingerNames[finger.type()]
				<< " finger, id: " << finger.id()
				<< ", length: " << finger.length()
				<< "mm, width: " << finger.width() << std::endl;

			// Get finger bones
			for (int b = 0; b < 4; ++b) {
				Bone::Type boneType = static_cast<Bone::Type>(b);
				Bone bone = finger.bone(boneType);
				std::cout << std::string(6, ' ') << boneNames[boneType]
					<< " bone, start: " << bone.prevJoint()
					<< ", end: " << bone.nextJoint()
					<< ", direction: " << bone.direction() << std::endl;
			}
		}
	}

	// Get tools
	const ToolList tools = frame.tools();
	for (ToolList::const_iterator tl = tools.begin(); tl != tools.end(); ++tl) {
		const Tool tool = *tl;
		std::cout << std::string(2, ' ') << "Tool, id: " << tool.id()
			<< ", position: " << tool.tipPosition()
			<< ", direction: " << tool.direction() << std::endl;
	}

	// Get gestures
	const GestureList gestures = frame.gestures();
	for (int g = 0; g < gestures.count(); ++g) {
		Gesture gesture = gestures[g];

		switch (gesture.type()) {
		case Gesture::TYPE_CIRCLE:
		{
			CircleGesture circle = gesture;
			std::string clockwiseness;

			if (circle.pointable().direction().angleTo(circle.normal()) <= PI / 2) {
				clockwiseness = "clockwise";
			}
			else {
				clockwiseness = "counterclockwise";
			}

			// Calculate angle swept since last frame
			float sweptAngle = 0;
			if (circle.state() != Gesture::STATE_START) {
				CircleGesture previousUpdate = CircleGesture(leap.frame(1).gesture(circle.id()));
				sweptAngle = (circle.progress() - previousUpdate.progress()) * 2 * PI;
			}
			std::cout << std::string(2, ' ')
				<< "Circle id: " << gesture.id()
				<< ", state: " << stateNames[gesture.state()]
				<< ", progress: " << circle.progress()
				<< ", radius: " << circle.radius()
				<< ", angle " << sweptAngle * RAD_TO_DEG
				<< ", " << clockwiseness << std::endl;
			break;
		}
		case Gesture::TYPE_SWIPE:
		{
			SwipeGesture swipe = gesture;
			std::cout << std::string(2, ' ')
				<< "Swipe id: " << gesture.id()
				<< ", state: " << stateNames[gesture.state()]
				<< ", direction: " << swipe.direction()
				<< ", speed: " << swipe.speed() << std::endl;
			break;
		}
		case Gesture::TYPE_KEY_TAP:
		{
			KeyTapGesture tap = gesture;
			std::cout << std::string(2, ' ')
				<< "Key Tap id: " << gesture.id()
				<< ", state: " << stateNames[gesture.state()]
				<< ", position: " << tap.position()
				<< ", direction: " << tap.direction() << std::endl;
			break;
		}
		case Gesture::TYPE_SCREEN_TAP:
		{
			ScreenTapGesture screentap = gesture;
			std::cout << std::string(2, ' ')
				<< "Screen Tap id: " << gesture.id()
				<< ", state: " << stateNames[gesture.state()]
				<< ", position: " << screentap.position()
				<< ", direction: " << screentap.direction() << std::endl;
			break;
		}
		default:
			std::cout << std::string(2, ' ') << "Unknown gesture type." << std::endl;
			break;
		}
	}

	if (!frame.hands().isEmpty() || !gestures.isEmpty()) {
		std::cout << std::endl;
	}
}

//--------------------------------------------------------------
void ofApp::draw(){
	camera.begin();
	// 背景を黒に塗りつぶし
	ofBackground(0, 0, 0);
	// フレームを取得
	Frame frame = leap.frame();
	// Handをあるだけ列挙
	for (int i = 0; i<frame.hands().count(); i++) {
		Hand hand = frame.hands()[i];
		// てのひらの位置に球体を描画
		drawSphere(hand.palmPosition(), 20);
		// Hand内のFingerをあるだけ描画
		for (int j = 0; j<hand.fingers().count(); j++) {
			Finger finger = frame.fingers()[j];
			drawSphere(finger.tipPosition(), 8);
			//drawSphere(finger.jointPosition(), 2);
		}
	}
	camera.end();
}

void ofApp::drawSphere(Vector vector, float radius) {
	// 球体の描画処理    
	ofNoFill();
	ofPushMatrix();
	ofPoint point = ofPoint(vector.x, vector.y, vector.z);
	ofTranslate(point);
	ofRotateX(point.x);
	ofRotateY(point.y);
	ofRotateZ(point.z);
	ofSetColor(0xCC, 0, 0, 255);
	ofSphere(radius);
	ofPopMatrix();
}

コメントもそのまま残っていて草はえますね。
これを描くとコンソールにむっちゃ言葉が出てきて追いきれません。位置とかを送ってそうですね(雑な理解)

btn.addEventListenerが使えなかった(nullが返ってきた)

初心者にありがち?なミスなんだけど、

//a.js
const btn = document.getElementById('btn');
btn.addEventListener( 'click' , function() {
    socket.emit('btn', true);
} );

//もしくは

document.querySelector('#btn').onclick = function () {
  socket.emit('btn', true);
}

とするとnullが返ってくる。

htmlはざっくり

<script type="text/javascript" src="a.js"></script>
<body>
    <input type="button" id="btn" value="ループ開始" class="select" />
</body>

こんなん

理由は下記がわかりやすい

teratail.com
簡単に言うと呼び出しが早すぎて順番が逆転する状態らしい。

私流に描くと

window.onload = function(){
  const btn = document.getElementById('btn');
  btn.addEventListener( 'click' , function() {
      socket.emit('btn', true);
  } );
};

やらかしてしまった…。こんなんに時間を取られたのか…。

ちなみに

<script type="text/javascript" src="a.js"></script>

<script type="text/javascript" scr="a.js"></script>

と描くミスをたまにやる。初心者はやることが違いますね(笑)
scr