Category Archives: Source

AndroidでThreadとHandlerでマルチスレッド処理

1.説明
post(Runnable runnable)  スレッドを起動
removeCallbacks(Runnable runnable)  スレッドをキャンセル
postDelayed(Runnable runnable,int time)  スレッドを遅延

2.xml

2.1 welcome.xml
<?xml version=”1.0″ encoding=”utf-8″?>
<RelativeLayout
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
xmlns:android=”http://schemas.android.com/apk/res/android”>

<ImageView
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:id=”@+id/imageView”
android:layout_alignParentLeft=”true”
android:layout_alignParentStart=”true”
android:layout_alignParentTop=”true”
android:layout_alignParentBottom=”true”
android:src=”@drawable/music”
android:layout_alignParentRight=”true”
android:layout_alignParentEnd=”true” />

</RelativeLayout>

2.2 main.xml
<RelativeLayout xmlns:android=”http://schemas.android.com/apk/res/android”
xmlns:tools=”http://schemas.android.com/tools”
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:paddingLeft=”@dimen/activity_horizontal_margin”
android:paddingRight=”@dimen/activity_horizontal_margin”
android:paddingTop=”@dimen/activity_vertical_margin”
android:paddingBottom=”@dimen/activity_vertical_margin”
tools:context=”.MyActivity”>

<TextView
android:text=”@string/hello_world”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content” />

</RelativeLayout>

3.Java

3.1 welcome.java
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.view.Window;
import android.widget.ImageView;

public class welcome extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.welcome);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
Intent mainIntent = new Intent(welcome.this,MyActivity.class);
welcome.this.startActivity(mainIntent);
welcome.this.finish();
}
},3000);
}
}
3.2 MyActivity.java
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class MyActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.my, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}

php言語 http_build_query関数

<?php
$data 
= array(‘foo’=>‘bar’,
‘baz’=>‘boom’,
‘cow’=>‘milk’,
‘php’=>‘hypertext processor’);

echo http_build_query($data) . “\n”;
echo 
http_build_query($data‘&amp;’);

?>

結果:

foo=bar&baz=boom&cow=milk&php=hypertext+processor
foo=bar&amp;baz=boom&amp;cow=milk&amp;php=hypertext+processor

UbuntuへのFTPサーバーのインストール

1.FTPサーバーのインストール
sudo apt-get install vsftpd

2.匿名アクセス
Anonymous_enable=NO
Local_enable=YES
3.サーバーまたはネットワークサービスを再起動
sudo /etc/init.d/xinetd restart
sudo /etc/init.d/vsftpd restart

php言語 addChild()関数

1.説明
class SimpleXMLElement
{
string addChild(name,value,ns)
}
2.xmlファイル
<?xml version=”1.0″ encoding=”ISO-8859-1″?>
<note>
<to>George</to>
<from>John</from>
<heading>Reminder</heading>
<body>Don’t forget the meeting!</body>
</note>

3.phpコード
<?php
$xml = simplexml_load_file(“test.xml”);

$xml->body[0]->addChild(“date”, “214-08-08”);

foreach ($xml->body->children() as $child)
{
echo “Child node: ” . $child;
}
?>

4.結果輸出:
Child node: 2014-08-08

Android 大きい画像を効果的に読み込む

1.画像の関連DimensionとTypeを計算
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(getResources(), R.id.myimage, options);
int imageHeight = options.outHeight;
int imageWidth = options.outWidth;
String imageType = options.outMimeType;

2.メモリへスケールダウンバージョンをロード
public static int calculateInSampleSize(
BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;

if (height > reqHeight || width > reqWidth) {

final int halfHeight = height / 2;
final int halfWidth = width / 2;

// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) > reqHeight
&& (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}

return inSampleSize;
}
3.画像に対してエンコードを行う
public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
int reqWidth, int reqHeight) {

// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(res, resId, options);

// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(res, resId, options);
}

4.サンプルを呼び出す
mImageView.setImageBitmap(
decodeSampledBitmapFromResource(getResources(), R.id.myimage, 100, 100));

php関数filter_input()

説明:
filter_input(input_type, variable, filter, options)

サンプルコード:

php関数urlencode URLのエンコード

サンプルコード:

<?php
$interest = “arts”;
$homepage = “http://www.arkgame.com”;
$query = “homepage=”.urlencode( $homepage );
$query .= “&interest=”.urlencode( $interest );
echo $query;
?>

CentOS x64の中にphpソースコンパイルエラー現象と解決策

1.configure: error: xml2-config not found. Please check your libxml2 installation.

yum install libxml2-devel.x86_64

2.configure: error: Cannot find OpenSSL’s

yum install openssl-devel.x86_64

3.configure: error: Could not find pcre.h in /usr/local

yum install pcre-devel.x86_64

4.configure: error: Could not find pcre.h in /usr/local

"--with-pcre-regex=/usr/include" \

5.configure: error: Could not find libpcre.(a|so) in /usr/include

"--with-pcre-regex=/usr" \

6.configure: error: Please reinstall the libcurl distribution –
easy.h should be in /include/curl/

yum install curl-devel.x86_64

7.configure: error: libjpeg.(a|so) not found.

yum install libjpeg-devel.x86_64

8.configure: error: libpng.(a|so) not found.

yum install libpng-devel.x86_64

9.configure: error: freetype.h not found.

yum install freetype-devel.x86_64

10.configure: error: Please reinstall the iconv library.

"--with-iconv" \

11.configure: error: mcrypt.h not found. Please reinstall libmcrypt.

yum install libmcrypt.x86_64 libmcrypt-devel.x86_64

12.configure: error: Please reinstall libmhash – I cannot find mhash.h

yum install mhash.x86_64 mhash-devel.x86_64

13.Note that the MySQL client library is not bundled anymore!

yum install php-mysql.x86_64 mysql-devel.x86_64

14.configure: error: Please reinstall the BZip2 distribution

yum install bzip2-devel.x86_64

15.configure: error: utf8_mime2text() has new signature, but U8T_CANONICAL is missing. This should not happen. Check config.log for additional information.
DISABLE IMAP
configure: error: Cannot find pspell

yum install aspell-devel.x86_64

16.configure: error: Cannot find libtidy

yum install libtidy.x86_64 libtidy-devel.x86_64

17.error: xslt-config not found. Please reinstall the libxslt >= 1.1.0 distribution

yum install libxslt.x86_64 libxslt-devel.x86_64

18.collect2: ld returned 1 exit status

yum install glibc-utils.x86_64 libtool-ltdl-devel.x86_64

PHPのコンパイルに導くために下記作業を行う
1.開発ツール&ライブラリをアップデートとインストール
yum update
yum group install "Development Tools"
yum group install "Development Libraries"

2.下記スクリプトを実行
#!/bin/sh
"./configure" \
"--prefix=/usr/local/php5" \
"--enable-force-cgi-redirect" \
"--enable-fastcgi" \
"--with-bz2" \
"--with-config-file-path=/usr/local/etc" \
"--with-config-file-scan-dir=/usr/local/etc/php.d" \
"--with-curl=/usr/local/lib" \
"--with-gd" \
"--with-gettext" \
"--with-jpeg-dir=/usr/local/lib" \
"--with-freetype-dir=/usr/local/lib" \
"--with-kerberos" \
"--with-mcrypt" \
"--with-mhash" \
"--with-mime-magic" \
"--with-mysql" \
"--with-mysqli" \
"--with-pcre-regex=/usr" \
"--with-pdo-mysql=shared" \
"--with-pdo-sqlite=shared" \
"--with-pear=/usr/local/lib/php" \
"--with-png-dir=/usr/local/lib" \
"--with-pspell" \
"--with-sqlite=shared" \
"--with-tidy" \
"--with-ttf" \
"--with-xmlrpc" \
"--with-xsl" \
"--with-zlib" \
"--with-zlib-dir=/usr/local/lib" \
"--with-openssl" \
"--with-iconv" \
"--with-libdir=lib64" \
"--enable-bcmath" \
"--enable-calendar" \
"--enable-exif" \
"--enable-ftp" \
"--enable-gd-native-ttf" \
"--enable-libxml" \
"--enable-magic-quotes" \
"--enable-soap" \
"--enable-sockets" \
"--enable-mbstring" \
"--enable-zip" \
"--enable-wddx"
 

zabbix アラートスクリプト

サンプルコード:

ファイル名:alertsend.sh

#!/usr/bin/python
# -*- coding: utf8 -*-
#zabbix remote command
import time,datetime
import re,os
import sys
import zabbix_sendmail
from zabbix_sendmail import SendmailError
import subprocess
import logging
from logging.handlers import RotatingFileHandler
reload(sys)
sys.setdefaultencoding(‘utf-8’)
LOGFILE = “/apps/svr/zabbix_server/scripts/logs/out.log”
MAXLOGSIZE = 100*1024*1024
BACKUPCOUNT = 4
log = logging.getLogger(‘zabbix_exec_command’)
log.setLevel(logging.DEBUG)
formatter = logging.Formatter(‘%(asctime)s – %(levelname)s: %(message)s’)
fh = RotatingFileHandler(LOGFILE,maxBytes=MAXLOGSIZE,backupCount=BACKUPCOUNT)
ch = logging.StreamHandler()
fh.setFormatter(formatter)
ch.setFormatter(formatter)
log.addHandler(fh)
log.addHandler(ch)
def get_2hour_ago():
a = os.popen(“date +%Y%m%d%H -d ‘2 hours ago'”).readlines()[0]
b = a.strip()
return b
def run_command(ip,command):
cmd = “zabbix_get -s ” + ip + ” -k ‘system.run[\”” + command + “\”]'”
return os.popen(cmd).readlines()
mailcontent = “”
if __name__ == “__main__”:
to_list = []
to_mobile = []
if len(sys.argv) != 8:
print “show usage: %s serverip itemid itemname hostname itemkey itemvalue triggerstatus” % (sys.argv[0])
sys.exit(1)
mailcontent = “””
<html>
<body>
<meta http-equiv=”Content-Type” content=”text/html”;charset=utf-8>
<title>ビッグデータモニタリングメール</title>
<style type=”text/css”>
.body { font-size: 14px; color: #333;background-color: #fff;}
.divtd {color:#E28E40;}
</style>
“””
ip,itemid,itemname,hostname = sys.argv[1],sys.argv[2],sys.argv[3],sys.argv[4]
itemkey,itemvalue,triggerstatus = str(sys.argv[5]).replace(” “,””),str(sys.argv[6]).replace(” “,””),sys.argv[7]
log.info(“アラート:IP:%s,監視項目:%s,ホスト名:%s,監視key:%s”%(ip,itemname,hostname,itemkey))
time_start = get_2hour_ago()
mailcontent += “<div class=’divtd’> 監視項目:%s , ホスト名:%s ,IP:%s ,現在値: %s </div><br />” % (itemname,hostname,ip,itemvalue)
mailcontent += “<div class=’divtd’>メモリ:</div> <div class=’.body’>”
for line in run_command(ip,”free -m”):
line=line.strip()
mailcontent += “%s<br />” % line
mailcontent += “<br /></div>”
mailcontent += “<div class=’divtd’>IO情報:</div> <div class=’.body’>”
for line in run_command(ip,”iostat -xn 1 1″):
line=line.strip()
mailcontent += “%s<br />” % line
mailcontent += “<br /></div>”
mailcontent += “<div class=’divtd’>負荷情報:</div> <div class=’.body’>”
for line in run_command(ip,”sar -q 1 3″):
line=line.strip()
mailcontent += “%s<br />” % line
mailcontent += “<br /></div>”
mailcontent += “<div class=’divtd’>CPU情報:</div> <div class=’.body’>”
for line in run_command(ip,”mpstat -P ALL”):
line=line.strip()
mailcontent += “%s<br />” % line
mailcontent += “<br /></div>”
mailcontent += “<div class=’divtd’>システムログ:</div> <div class=’.body’>”
for line in run_command(ip,”/usr/bin/sudo tail -20 /var/log/messages”):
line=line.strip()
mailcontent += “%s<br />” % line
mailcontent += “<br /></div>”
to_list = [“xxxx”]
mailcontent += “<div class=’divtd’>履歴データ:</div> <div class=’.body’>”
mailcontent += “<table style=’border-collapse: collapse; width: 96%;’>”
mailcontent += “””<tr><img src=http://xxxxxx/chart.php?itemid=%s&period=7200&stime=%s width=”871″ height=”305″/>””” % (itemid,time_start)
mailcontent += “</tr> </table>”
mailcontent += “””</html>
</body>”””
print mailcontent
log.debug(“監視メール内容:%s”%mailcontent)
log.info(“受信:%s,受信者リスト:%s”%(to_list,to_mobile))
mail_sub = “Zabbix監視アラーム|現在状態:%s,監視項目:%s,監視ホスト:%s ” % (triggerstatus,itemname,hostname)
log.info(“メールを送信,件名:%s”%mail_sub)
try:
zabbix_sendmail.send_mail_withoutSSL(to_list,mail_sub,mailcontent)
log.info(“アラームメール送信成功”)
except SendmailError,e:
log.error(“アラーム送信失敗,失敗メッセージ:%s”%(str(e)))

2.sendmailの中身下記

#!/usr/bin/python
# -*- coding: utf8 -*-
#to send zabbix alert mail
import smtplib
from email.mime.text import MIMEText
import traceback
import exceptions
import sys
reload(sys)
sys.setdefaultencoding(‘utf-8′)
mail_host = “xxxxx”
mail_user = “xxxx”
mail_pass = “xxxx”
mail_address = “xxx”
mail_postfix=”xxxx”
mail_port=”xxx”
class SendmailError(Exception):
def __init__(self, errorlog):
self.errorlog = errorlog
def __str__(self):
return “メール送信エラー,エラーメッセージ: %s” % (self.errorlog)
def send_mail_withoutSSL(to_list,sub,content):
me = “BI Monitor” + “<“+mail_user+”@”+mail_postfix+”>”
msg = MIMEText(content,’html’,’utf8′)
msg[‘Subject’] = sub
msg[‘From’] = me
msg[‘To’] = “;”.join(to_list)
try:
s = smtplib.SMTP()
s.connect(mail_host)
s.login(mail_user,mail_pass)
s.sendmail(me, to_list, msg.as_string())
s.close()
return True
except Exception, e:
raise SendmailError(str(e))

 

packet to client mac reached max retries removing the client

エラーメッセージ
packet to client mac reached max retries removing the client

説明:

Explanation   This error message indicates that the access point attempts to poll the client a certain number of times, but does not receive a response. Therefore, the client is removed from the association table. This issue is commonly seen when the client and access point are attempting to communicate in a noisy RF environment.

Recommended Action   To resolve this issue, run a carrier busy test on the access point to determine if there is excessive noise in the radio channel spectrum. Attempt to alleviate any unwanted noise.

If there are several access points in the same area, there might be overlapping the channel signals or possibly other wireless device in the area. Change the access point channel to one of the non-overlapping channels using the access point GUI. Under Network Interfaces, select Radio-802.11. There are three non-overlapping channels: 1, 6, and 11.

The maximum data retries setting determines the number of attempts the access point/bridge makes to send a packet before giving up and dropping the packet.The default setting is 32. Beginning in privileged EXEC mode, follow these steps to configure the maximum data retries:

詳細内容についてこちらをご参照してください。