首页 文章 精选 留言 我的

精选列表

搜索[笔记软件],共10000篇文章
优秀的个人博客,低调大师

学习笔记-4.1用户管理命令

复习: /etc/passwd: 用户名:密码:UID:GID:注释:家目录:默认shell /etc/group: 组名:密码:GID:以此组为其附加组的用户列表 /etc/shadow: 用户名:密码:最近一次修改密码的时间:最短使用期限,最长使用期限: 警告时间:非活动时间:过期时间 useradd [options] USERNAME useradd -u 1000 user1 -u 指定其UID -g GID(基本组) 指定组一定要存在 -G GID,... (附加组) -c "COMMENT"指定注释信息 -d /path/to/directory指定家目录,默认是home下 -s SHELL useradd -s /sbin/nologin user5 su - user5 -m -k 强制复制bash配置文件到家目录 -M 创建用户,不创建家目录 -r 添加一个系统用户 /etc/login.defs /etc/shells:指定了当前系统可用的安全shell 环境变量:PATH HISTSIZE SHELL userdel: userdel [option] USERNAME 不指定选项,不会删除家目录 -r 删除用户的同时,同时删除用户的家目录 id :查看用户的账号属性信息 -u -g -G -n 上面都可用和-n合用 finger USERNAME(user1)查看用户账号相关信息 修改用户账号属性: usermod -u usermod -u 2002 user2 -g (基本组,事先存在的组) -G 附加组,已有附件组,修改了后原有附件组就没有了 -a -G:追加附件组(-a与-G联合使用) -c 注释 -d -m 为用户指定新的家目录,并移动此前新建的文件到新的家目录 -s shell -l 修改用户名 -L:锁定账号 -U:解锁 chsh:修改用户的默认shell chfn:修改用户的注释信息(fn是finger的缩写) 密码管理: passwd [USERNAME] --stdin -l 锁定账号 -u 解锁 -d 删除用户密码(禁止登录) echo "redhat" | passwd --stdin user3 pwch(passwdcheck)检查用户账号完整性 组管理: 创建组:groupadd groupadd -g GID -r 添加为系统组 groupmod -g GID -n GRPNAME groupdel gpasswd:为组设定密码 newgrp 临时切换基本组 exit退出 练习: 1 创建一个用户mandriva ,其ID号2002,基本组为distro(组ID3003),附加组 为linux: # groupadd -g 3003 distro # groupadd linux # useradd -u 2002 -g distro -G linux mandriva 2 创建一个用户fedora,其全名为Fedora Community,默认shell为tcsh # useradd -c "Fedora Community" -s /bin/tcsh/ fedora 3 修改mandriva的ID号为4004,基本组为linux,附加组为distro和Fedora # usermod -u 4004 -g linux -G distro,fedora mandriva 4 给Fedora加密码,并设定其密码最短使用期限为2天,最长为50天 # passwd -n 2 -x 50 fedora 5 将madriva的默认shell改为/bin/bash # usermod -s /bin/bash mandrira 6 添加系统用户hbase,且不允许其登陆系统 #useradd -r -s /sbin/noglogin hbase change(改变密码过期信息的) -d 最近一次的修改时间 -E 过期时间 -r: 非活动时间 -m 最短使用时间 -M 最长使用时间 -w:警告时间 本文转自飞行萌51CTO博客,原文链接: http://blog.51cto.com/8527508/1939822,如需转载请自行联系原作者

优秀的个人博客,低调大师

Nginx学习笔记(一) Nginx架构

Nginx全程是什么?Nginx ("engine x") 是一个高性能的 HTTP 和反向代理服务器,也是一个 IMAP/POP3/SMTP代理服务器。 daemon守护线程 nginx在启动后,在unix系统中会以daemon的方式在后台运行,后台进程包含一个master进程和多个worker进程。 当然nginx也是支持多线程的方式的,只是我们主流的方式还是多进程的方式,也是nginx的默认方式。 master进程主要用来管理worker进程,包含:接收来自外界的信号,向各worker进程发送信号,监控worker进程的运行状态,当worker进程退出后(异常情况下),会自动重新启动新的worker进程。 worker进程则是处理基本的网络事件。多个worker进程之间是对等的,他们同等竞争来自客户端的请求,各进程互相之间是独立的。一个请求,只可能在一个worker进程中处理,一个worker进程,不可能处理其它进程的请求。 worker进程的个数是可以设置的,一般我们会设置与机器cpu核数一致。更多的worker数,只会导致进程来竞争cpu资源了,从而带来不必要的上下文切换。而且,nginx为了更好的利用多核特性,具有cpu绑定选项,我们可以将某一个进程绑定在某一个核上,这样就不会因为进程的切换带来cache的失效。 惊群现象 每个worker进程都是从master进程fork过来。在master进程里面,先建立好需要listen的socket之后,然后再fork出多个worker进程,这样每个worker进程都可以去accept这个socket(当然不是同一个socket,只是每个进程的这个socket会监控在同一个ip地址与端口,这个在网络协议里面是允许的)。一般来说,当一个连接进来后,所有在accept在这个socket上面的进程,都会收到通知,而只有一个进程可以accept这个连接,其它的则accept失败。 相对于线程,采用进程的优点 进程之间不共享资源,不需要加锁,所以省掉了锁带来的开销。 采用独立的进程,可以让互相之间不会影响,一个进程退出后,其它进程还在工作,服务不会中断,master进程则很快重新启动新的worker进程。 编程上更加容易。 多线程的问题 而多线程在多并发情况下,线程的内存占用大,线程上下文切换造成CPU大量的开销。想想apache的常用工作方式(apache也有异步非阻塞版本,但因其与自带某些模块冲突,所以不常用),每个请求会独占一个工作线程,当并发数上到几千时,就同时有几千的线程在处理请求了。这对操作系统来说,是个不小的挑战,线程带来的内存占用非常大,线程的上下文切换带来的cpu开销很大,自然性能就上不去了,而这些开销完全是没有意义的。 异步非阻塞 异步的概念和同步相对的,也就是不是事件之间不是同时发生的。 非阻塞的概念是和阻塞对应的,阻塞是事件按顺序执行,每一事件都要等待上一事件的完成,而非阻塞是如果事件没有准备好,这个事件可以直接返回,过一段时间再进行处理询问,这期间可以做其他事情。但是,多次询问也会带来额外的开销。 总的来说,Nginx采用异步非阻塞的好处在于: 不需要创建线程,每个请求只占用少量的内存 没有上下文切换,事件处理非常轻量 淘宝tengine团队说测试结果是“24G内存机器上,处理并发请求可达200万”。 本文转自cococo点点博客园博客,原文链接:http://www.cnblogs.com/coder2012/p/3141469.html,如需转载请自行联系原作者

优秀的个人博客,低调大师

openstack学习笔记四 组件框架

组件 nova 对虚拟机管理 cinder 云硬盘 swift 对象存储 容器 glance 镜像 neutron 网络 kestone 验证 所有的组件都得要向keystone进行注册,登记 利用 rebitmq互相通信 环境需要mysql 框架 控制节点 keystone dashboard 计算节点 跑虚拟机的机器 网络节点 为计算节点里的虚拟机提供路由 DHCP 存储节点 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 [root@h1~] #sourcekeystonerc_admin [root@h1~(keystone_admin)] #open open openstack-configopenstack-service opensslopenstack-dbopenstack-status openstackopenstack-keystone-sample-dataopenvt [root@h1~(keystone_admin)] #openstack-status ==Novaservices== openstack-nova-api:active openstack-nova-compute:active openstack-nova-network:inactive(disabledonboot) openstack-nova-scheduler:active openstack-nova-cert:active openstack-nova-conductor:active openstack-nova-console:inactive(disabledonboot) openstack-nova-consoleauth:active openstack-nova-xvpvncproxy:inactive(disabledonboot) ==Glanceservices== openstack-glance-api:active openstack-glance-registry:active ==Keystoneservice== openstack-keystone:inactive(disabledonboot) ==Horizonservice== openstack-dashboard:active ==neutronservices== neutron-server:active neutron-dhcp-agent:active neutron-l3-agent:active neutron-metadata-agent:active neutron-openvswitch-agent:active ==Swiftservices== openstack-swift-proxy:active openstack-swift-account:active openstack-swift-container:active openstack-swift-object:active ==Cinderservices== openstack-cinder-api:active openstack-cinder-scheduler:active openstack-cinder-volume:active openstack-cinder-backup:active ==Ceilometerservices== openstack-ceilometer-api:active openstack-ceilometer-central:active openstack-ceilometer-compute:active openstack-ceilometer-collector:active openstack-ceilometer-alarm-notifier:active openstack-ceilometer-alarm-evaluator:active openstack-ceilometer-notification:active ==Supportservices== mysqld:active(disabledonboot) openvswitch:active dbus:active target:active rabbitmq-server:active memcached:active ==Keystone users == /usr/lib/python2 .7 /site-packages/keystoneclient/shell .py:64:DeprecationWarning:ThekeystoneCLIisdeprecated in favorofpython-openstackclient.ForaPythonlibrary, continue usingpython-keystoneclient. 'python-keystoneclient.' ,DeprecationWarning) /usr/lib/python2 .7 /site-packages/keystoneclient/v2_0/client .py:145:DeprecationWarning:Constructinganinstanceofthekeystoneclient.v2_0.client.Clientclasswithoutasessionisdeprecatedasofthe1.7.0releaseandmayberemoved in the2.0.0release. 'the2.0.0release.' ,DeprecationWarning) /usr/lib/python2 .7 /site-packages/keystoneclient/v2_0/client .py:147:DeprecationWarning:Usingthe 'tenant_name' argumentisdeprecated in version '1.7.0' andwillberemoved in version '2.0.0' ,pleaseusethe 'project_name' argumentinstead super(Client,self).__init__(**kwargs) /usr/lib/python2 .7 /site-packages/debtcollector/renames .py:43:DeprecationWarning:Usingthe 'tenant_id' argumentisdeprecated in version '1.7.0' andwillberemoved in version '2.0.0' ,pleaseusethe 'project_id' argumentinstead return f(*args,**kwargs) /usr/lib/python2 .7 /site-packages/keystoneclient/httpclient .py:376:DeprecationWarning:ConstructinganHTTPClientinstancewithoutusingasessionisdeprecatedasofthe1.7.0releaseandmayberemoved in the2.0.0release. 'the2.0.0release.' ,DeprecationWarning) +----------------------------------+------------+---------+----------------------+ | id |name|enabled|email| +----------------------------------+------------+---------+----------------------+ |1627cc3d61c04f9db9608e9703a01371|admin|True|root@localhost| |04247710cdf34914a7f5b315ab166731|ceilometer|True|ceilometer@localhost| |cb5e12e30a4a4c1dae57255c184b8b30|cinder|True|cinder@localhost| |632fb20205ea4c40988d7d65b2844ff6|glance|True|glance@localhost| |23c4fb48a5a247d68e50c6b74fb6f035|http|True|| |80069f5c8edc454b8038e7f116df4ff5|neutron|True|neutron@localhost| |adbcaaf58d09495988b57be8e82b4e6b|nova|True|nova@localhost| |4f488ff4859e4973afefea6e7872ed83|swift|True|swift@localhost| +----------------------------------+------------+---------+----------------------+ ==Glanceimages== +--------------------------------------+-----------+ |ID|Name| +--------------------------------------+-----------+ |2a0db075-f221-4285-9ff9-38b755a322c1|centos7.2| +--------------------------------------+-----------+ ==Novamanagedservices== +----+------------------+---------------+----------+---------+-------+----------------------------+-----------------+ |Id|Binary|Host|Zone|Status|State|Updated_at|DisabledReason| +----+------------------+---------------+----------+---------+-------+----------------------------+-----------------+ |1|nova-consoleauth|h1.hequan.com|internal|enabled|up|2016-07-05T07:06:34.000000|-| |2|nova-scheduler|h1.hequan.com|internal|enabled|up|2016-07-05T07:06:34.000000|-| |3|nova-conductor|h1.hequan.com|internal|enabled|up|2016-07-05T07:06:34.000000|-| |5|nova-compute|h1.hequan.com|nova|enabled|up|2016-07-05T07:06:34.000000|-| |6|nova-cert|h1.hequan.com|internal|enabled|up|2016-07-05T07:06:34.000000|-| |7|nova-compute|h2.hequan.com|nova|enabled|up|2016-07-05T07:06:34.000000|-| +----+------------------+---------------+----------+---------+-------+----------------------------+-----------------+ ==Novanetworks== +--------------------------------------+---------+------+ |ID|Label|Cidr| +--------------------------------------+---------+------+ |bebbc903-5846-4e8d-9c19-f0248cb6e08d|put-ex|-| |494cbfae-b26d-4e29-859e-35c55f017f19|he_sub2|-| |1f8a8d0c-2e32-4aaa-83d6-3ba52a768292|quan|-| |67d35cd2-3b95-48a7-96b7-6ba1f0eb7d5d|he_sub|-| +--------------------------------------+---------+------+ ==Novainstanceflavors== +----+-----------+-----------+------+-----------+------+-------+-------------+-----------+ |ID|Name|Memory_MB|Disk|Ephemeral|Swap|VCPUs|RXTX_Factor|Is_Public| +----+-----------+-----------+------+-----------+------+-------+-------------+-----------+ |1|m1.tiny|512|1|0||1|1.0|True| |2|m1.small|2048|20|0||1|1.0|True| |3|m1.medium|4096|40|0||2|1.0|True| |4|m1.large|8192|80|0||4|1.0|True| |5|m1.xlarge|16384|160|0||8|1.0|True| +----+-----------+-----------+------+-----------+------+-------+-------------+-----------+ ==Novainstances== +--------------------------------------+------+----------------------------------+--------+------------+-------------+-----------------------------------+ |ID|Name|TenantID|Status|TaskState|PowerState|Networks| +--------------------------------------+------+----------------------------------+--------+------------+-------------+-----------------------------------+ |95311ed2-6091-4ce7-a2be-caab8e2760ce|1|43986fb013804aa0a04ca277e4d0e69c|ACTIVE|-|Running|quan=192.168.10.12,192.168.2.104| +--------------------------------------+------+------ 本文转自 295631788 51CTO博客,原文链接:http://blog.51cto.com/hequan/1795980,如需转载请自行联系原作者

优秀的个人博客,低调大师

Android笔记:定时提醒、闹钟实现

android要实现定时的功能那肯定就要用到闹铃相关的技术, 那么android闹铃实现是基于 AlarmManager 这个类的,首先我们来看一下它的几个主要的方法。 两个核心的方法 : 1 private final IAlarmManagermService; 1 2 3 4 5 6 public void set( int type, long triggerAtMillis,PendingIntentoperation){ try { mService.set(type,triggerAtMillis,operation); } catch (RemoteExceptionex){ } } 和 1 2 3 4 5 6 7 public void setRepeating( int type, long triggerAtMillis, long intervalMillis,PendingIntentoperation){ try { mService.setRepeating(type,triggerAtMillis,intervalMillis,operation); } catch (RemoteExceptionex){ } } 第一个方法主要功能是注册一个比较简单的闹铃,第二个方法是注册一个重复的闹铃,这里重复的意思是指:设置5s, 那么每隔5s会执行一次 。 我们看到这里具体的实现都是基于IAlarmManager的,而IAlarmManager是一个aidl(Android Interface definition language),具体的就不详细介绍了,大家有兴趣的可以自己研究一下。 下面我来看下set(int type, long triggerAtMillis, PendingIntent operation)方法是如何调用的: 1 2 3 4 5 6 7 8 9 10 11 //进行闹铃注册 Intentintent= new Intent(MainActivity. this ,AlarmReceiver. class ); PendingIntentsender=PendingIntent.getBroadcast(MainActivity. this , 0 ,intent, 0 ); //过10s执行这个闹铃 Calendarcalendar=Calendar.getInstance(); calendar.setTimeInMillis(System.currentTimeMillis()); calendar.add(Calendar.SECOND, 10 ); AlarmManagermanager=(AlarmManager)getSystemService(ALARM_SERVICE); manager.set(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),sender); 看一下AlarmReceiver 的源码: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 /** * *@ClassName:AlarmReceiver *@Description:闹铃时间到了会进入这个广播,这个时候可以做一些该做的业务。 *@authorHuHood *@date2013-11-25下午4:44:30 * */ public class AlarmReceiver extends BroadcastReceiver{ @Override public void onReceive(Contextcontext,Intentintent){ Toast.makeText(context, "闹铃响了,可以做点事情了~~" ,Toast.LENGTH_LONG).show(); } } 还有别忘了,AndroidManifest.xml中需要加入: 1 <receiverandroid:name= "com.example.alarmmanagerdemo.AlarmReceiver" android:process= ":remote" > 运行之后,过10s 弹出 "闹铃响了,可以做点事情了~~", 说明成功了。 ok,这个结果肯定不是我们想要的,我们想要的功能是每天定时提醒的功能,那么需要基于 setRepeating(int type, long triggerAtMillis,long intervalMillis, PendingIntent operation) 这个方法来实现,代码如下: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 Intentintent= new Intent(MainActivity. this ,AlarmReceiver. class ); PendingIntentsender=PendingIntent.getBroadcast(MainActivity. this , 0 ,intent, 0 ); long firstTime=SystemClock.elapsedRealtime(); //开机之后到现在的运行时间(包括睡眠时间) long systemTime=System.currentTimeMillis(); Calendarcalendar=Calendar.getInstance(); calendar.setTimeInMillis(System.currentTimeMillis()); //这里时区需要设置一下,不然会有8个小时的时间差 calendar.setTimeZone(TimeZone.getTimeZone( "GMT+8" )); calendar.set(Calendar.MINUTE,mMinute); calendar.set(Calendar.HOUR_OF_DAY,mHour); calendar.set(Calendar.SECOND, 0 ); calendar.set(Calendar.MILLISECOND, 0 ); //选择的定时时间 long selectTime=calendar.getTimeInMillis(); //如果当前时间大于设置的时间,那么就从第二天的设定时间开始 if (systemTime>selectTime){ Toast.makeText(MainActivity. this , "设置的时间小于当前时间" ,Toast.LENGTH_SHORT).show(); calendar.add(Calendar.DAY_OF_MONTH, 1 ); selectTime=calendar.getTimeInMillis(); } //计算现在时间到设定时间的时间差 long time=selectTime-systemTime; firstTime+=time; //进行闹铃注册 AlarmManagermanager=(AlarmManager)getSystemService(ALARM_SERVICE); manager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstTime,DAY,sender); Log.i(TAG, "time====" +time+ ",selectTime=====" +selectTime+ ",systemTime====" +systemTime+ ",firstTime===" +firstTime); Toast.makeText(MainActivity. this , "设置重复闹铃成功!" ,Toast.LENGTH_LONG).show(); 以上的思路大致是这样的,首先根据设置的时间,算出当前时间离设置时间的时间差,加上这个时间差,我们就知道第一次提醒的时间,然后再设定重复的时间间隔,我们这里设置1天就可以了。现在解释一下setRepeating中第一个参数:AlarmManager.RTC,硬件闹钟,不唤醒手机(也可能是其它设备)休眠;当手机休眠时不发射闹钟。AlarmManager.RTC_WAKEUP,硬件闹钟,当闹钟发躰时唤醒手机休眠;AlarmManager.ELAPSED_REALTIME,真实时间流逝闹钟,不唤醒手机休眠;当手机休眠时不发射闹钟。AlarmManager.ELAPSED_REALTIME_WAKEUP,真实时间流逝闹钟,当闹钟发躰时唤醒手机休眠;RTC闹钟和ELAPSED_REALTIME最大的差别就是前者可以通过修改手机时间触发闹钟事件,后者要通过真实时间的流逝,即使在休眠状态,时间也会被计算。以上摘自:http://hualang.iteye.com/blog/1304054还有,我们这里是调用广播的形式来实现的,也可以用service的方式来进行实现,只要把PendingIntent改动一下即可,相关代码:PendingIntent.getService(MainActivity.this, 0,new Intent(MainActivity.this,AlarmService.class), 0);其他的均相同。完整Demo下载:http://download.csdn.net/detail/jakend/6612033 本文转自 glblong 51CTO博客,原文链接:http://blog.51cto.com/glblong/1679698,如需转载请自行联系原作者

优秀的个人博客,低调大师

Android笔记:Intent的Component使用

使用components有两种方式: 1 2 3 ComponentNamecom= new ComponentName(MainActivity. this ,MyActivity. class ); //first ComponentNamecom= new ComponentName( "com.example.testcomponent" , "com.example.testcomponent.MyActivity" ); //second 第二种方式的第二个参数必须写全包名,不然会报错的。 一样的,主Activity中: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 button.setOnClickListener( new Button.OnClickListener() { @Override public void onClick(Viewarg0) { //TODOAuto-generatedmethodstub Intentintent= new Intent(); ComponentNamecom= new ComponentName( "com.example.testcomponent" , "com.example.testcomponent.MyActivity" ); intent.setComponent(com); Strings= "ThisisaTest." ; intent.putExtra( "id" ,s); startActivity(intent); } }); 在目标Ativity中获取数据和上面是一样的,但是,在目标Activity中就可以获取到源目标,知道是从哪儿传递过来的: 1 2 3 4 5 6 7 8 text=(TextView)findViewById(R.id.text); Intentintent=getIntent(); Stringstr=intent.getStringExtra( "id" ); ComponentNamecom=intent.getComponent(); StringpkgName=com.getPackageName(); StringclassName=com.getClassName(); text.setText(str+ "\n" +pkgName+ "\n" +className); 本文转自 glblong 51CTO博客,原文链接:http://blog.51cto.com/glblong/1611832,如需转载请自行联系原作者

优秀的个人博客,低调大师

Android开发学习笔记:浅谈ToggleButton

ToggleButton(开关按钮)是Android系统中比较简单的一个组件,是一个具有选中和未选择状态双状态的按钮,并且需要为不同的状态设置不同的显示文本。 ToggleButton常用的XML属性 属性名称 描述 android:disabledAlpha 设置按钮在禁用时透明度。 android:textOff 未选中时按钮的文本 android:textOn 选中时按钮的文本 下面是具体的例子: 第一个例子是通过Toast显示ToggleButton不同的状态时的信息 MainActivity.java packagecom.android.togglebutton; importandroid.app.Activity; importandroid.os.Bundle; importandroid.view.View; importandroid.view.View.OnClickListener; importandroid.widget.Toast; importandroid.widget.ToggleButton; publicclassMainActivityextendsActivity{ //声明ToggleButton privateToggleButtontogglebutton; @Override publicvoidonCreate(BundlesavedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.main); togglebutton=(ToggleButton)findViewById(R.id.togglebutton); togglebutton.setOnClickListener(newOnClickListener(){ publicvoidonClick(Viewv){ //当按钮第一次被点击时候响应的事件 if(togglebutton.isChecked()){ Toast.makeText(MainActivity.this,"你喜欢球类运动",Toast.LENGTH_SHORT).show(); } //当按钮再次被点击时候响应的事件 else{ Toast.makeText(MainActivity.this,"你不喜欢球类运动",Toast.LENGTH_SHORT).show(); } } }); } } main.xml <?xmlversion="1.0"encoding="utf-8"?> <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> <ToggleButton android:id="@+id/togglebutton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textOn="喜欢" android:textOff="不喜欢" /> </LinearLayout> strings.xml <?xmlversion="1.0"encoding="utf-8"?> <resources> <stringname="hello">你喜不喜欢球类运动?</string> <stringname="app_name">测试ToggleButton</string> </resources> 效果图: 第二个例子通过图片的变化显示ToggleButton不同的状态时的图片 MainActivity.java packagecom.android.togglebutton; importandroid.app.Activity; importandroid.os.Bundle; importandroid.widget.CompoundButton; importandroid.widget.CompoundButton.OnCheckedChangeListener; importandroid.widget.ImageView; importandroid.widget.ToggleButton; publicclassMainActivityextendsActivity{ //声明ImageView,ToggleButton privateImageViewimageView; privateToggleButtontoggleButton; @Override publicvoidonCreate(BundlesavedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.main); //通过findViewById获得ImageView,ToggleButton imageView=(ImageView)findViewById(R.id.imageView); toggleButton=(ToggleButton)findViewById(R.id.toggleButton); toggleButton.setOnCheckedChangeListener(newOnCheckedChangeListener(){ publicvoidonCheckedChanged(CompoundButtonbuttonView,booleanisChecked){ toggleButton.setChecked(isChecked); //使用三目运算符来响应按钮变换的事件 imageView.setImageResource(isChecked?R.drawable.pic_on:R.drawable.pic_off); } }); } } main.xml <?xmlversion="1.0"encoding="utf-8"?> <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <ImageView android:id="@+id/imageView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/pic_off" android:layout_gravity="center_horizontal" /> <ToggleButton android:id="@+id/toggleButton" android:layout_width="130dip" android:layout_height="wrap_content" android:textOn="开灯" android:textOff="关灯" android:layout_gravity="center_horizontal" /> </LinearLayout> 效果图: 本文转自 lingdududu 51CTO博客,原文链接:http://blog.51cto.com/liangruijun/655014

优秀的个人博客,低调大师

Android开发学习笔记:浅谈Toast

一.Toast的简介 Toast是Android中一种提供给用户简短信息的视图,该视图已浮于应用程序之上的形式呈现给用户。因为它并不获得焦点,即使用户正在输入什么也不会受到影响。它的目标是尽可能已不显眼的方式,使用户看到你提供的信息。显示的时间是有限制的,过一段时间后会自动消失,不过Toast本身可以控制显示时间的长短。 二.Toast的常用方法 int getDuration() 返回Toast视图显示持续的时间. int getGravity() 取得提示信息在屏幕上显示的位置. float getHorizontalMargin() 返回横向栏外空白 float getVerticalMargin() 返回纵向栏外空白. View getView() 返回View对象. int getXOffset() 返回相对于参照位置的横向偏移像素量。 int getYOffset() 返回相对于参照位置的纵向偏移像素量 staticToast makeText(Contextcontext, int resId, int duration) 生成一个从资源中取得的包含文本视图的标准Toast对象。 context使用的上下文。通常是你的Application或Activity对象 resId要使用的字符串资源ID,可以是已格式化文本。 duration该信息的存续期间。值为LENGTH_SHORT或LENGTH_LONG staticToast makeText(Contextcontext,CharSequencetext, int duration) 生成一个包含文本视图的标准Toast对象. void setDuration(int duration) 设置Toast视图显示持续的时间,LENGTH_LONG表示持续时间较长,LENGTH_SHORT表示持续时间较短 void setGravity(int gravity, int xOffset, int yOffset) 设置提示信息在屏幕上的显示位置.(自定义Toast的显示位置,例如toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0)可以把Toast定位在左上角。Toast提示的位置xOffset:大于0向右移,小于0向左移) void setMargin(float horizontalMargin, float verticalMargin) 设置视图的栏外空白. horizontalMargin容器的边缘与提示信息的横向空白(与容器宽度的比) verticalMargin容器的边缘与提示信息的纵向空白(与容器高度的比)。 void setText(int resId) 更新之前通过makeText()方法生成的Toast对象的文本内容.resId为Toast指定的新的字符串资源ID。 void setText(CharSequences) 更新之前通过makeText()方法生成的Toast对象的文本内容. s为Toast指定的新的文本 void setView(Viewview) 设置要显示的View.注意这个方法可以显示自定义的toast视图,可以包含图像,文字等等。是比较常用的方法 void show() 按照指定的存续期间显示提示信息 三.Toast的不同显示样式 效果图(有五种不同的Toast显示样式): main.xml <?xmlversion="1.0"encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <Button android:id="@+id/btn_1" android:text="@string/btn1" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <Button android:id="@+id/btn_2" android:text="@string/btn2" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <Button android:id="@+id/btn_3" android:text="@string/btn3" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <Button android:id="@+id/btn_4" android:text="@string/btn4" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <Button android:id="@+id/btn_5" android:text="@string/btn5" android:layout_width="fill_parent" android:layout_height="wrap_content" /> </LinearLayout> toast.xml <?xmlversion="1.0"encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="fill_parent" android:padding="5dp" android:background="#708090" > <ImageView android:id="@+id/img" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="带图片文字的Toast" /> </LinearLayout> strings.xml <?xmlversion="1.0"encoding="utf-8"?> <resources> <stringname="hello">HelloToast!</string> <stringname="app_name">ToastDemo</string> <stringname="btn1">系统默认的Toast</string> <stringname="btn2">自定义位置的Toast</string> <stringname="btn3">带只有图片的Toast</string> <stringname="btn4">有图有文字的Toast</string> <stringname="btn5">自定义布局的Toast</string> </resources> ToastDemoActivity.java packagecom.android.toast.activity; importandroid.app.Activity; importandroid.content.Context; importandroid.os.Bundle; importandroid.view.Gravity; importandroid.view.LayoutInflater; importandroid.view.View; importandroid.view.View.OnClickListener; importandroid.widget.Button; importandroid.widget.ImageView; importandroid.widget.LinearLayout; importandroid.widget.Toast; publicclassToastDemoActivityextendsActivity{ privateButtonbtn_1,btn_2,btn_3,btn_4,btn_5; privateToasttoast=null; @Override protectedvoidonCreate(BundlesavedInstanceState){ //TODOAuto-generatedmethodstub super.onCreate(savedInstanceState); setContentView(R.layout.main); btn_1=(Button)findViewById(R.id.btn_1); btn_2=(Button)findViewById(R.id.btn_2); btn_3=(Button)findViewById(R.id.btn_3); btn_4=(Button)findViewById(R.id.btn_4); btn_5=(Button)findViewById(R.id.btn_5); btn_1.setOnClickListener(newButtonClick()); btn_2.setOnClickListener(newButtonClick()); btn_3.setOnClickListener(newButtonClick()); btn_4.setOnClickListener(newButtonClick()); btn_5.setOnClickListener(newButtonClick()); } classButtonClickimplementsOnClickListener{ @Override publicvoidonClick(Viewv){ //TODOAuto-generatedmethodstub switch(v.getId()){ caseR.id.btn_1: toast.makeText(ToastDemoActivity.this,"默认的Toast显示",Toast.LENGTH_LONG).show(); break; caseR.id.btn_2: //getApplicationContext()得到程序当前的默认Context toast=Toast.makeText(getApplicationContext(),"自定义位置的Toast显示", Toast.LENGTH_LONG); //设置Toast的位置 toast.setGravity(Gravity.CENTER,toast.getXOffset()/2,toast.getYOffset()/2); toast.show(); break; caseR.id.btn_3: toast=Toast.makeText(getApplicationContext(),"只有图片的Toast显示", Toast.LENGTH_LONG); ImageViewimg=newImageView(ToastDemoActivity.this); img.setImageResource(R.drawable.android); toast.setView(img); toast.show(); break; caseR.id.btn_4: toast=Toast.makeText(getApplicationContext(),"有图有字的Toast",Toast.LENGTH_LONG); LinearLayoutlayout=(LinearLayout)toast.getView(); ImageViewimg1=newImageView(getApplicationContext()); img1.setImageResource(R.drawable.android); layout.addView(img1,0); toast.show(); break; caseR.id.btn_5: //将一个xml布局转换成一个view对象 LayoutInflaterinflater=(LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE); Viewview=inflater.inflate(R.layout.toast,null); Toasttoast=newToast(getApplicationContext()); //在view中查找查找ImageView控件 ImageViewimage=(ImageView)view.findViewById(R.id.img); image.setImageResource(R.drawable.android); toast.setView(view); toast.show(); break; default: break; } } } } 本文转自 lingdududu 51CTO博客,原文链接: http://blog.51cto.com/liangruijun/638913

优秀的个人博客,低调大师

Android学习笔记(四)Android 组件

EditText和setOnKeyListener事件实现文本处理 package com.example.test12; import android.os.Bundle; import android.app.Activity; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.EditText; import android.widget.TextView; import android.support.v4.app.NavUtils; public class MainActivity extends Activity { private TextView text; private EditText edit; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); text=(TextView)findViewById(R.id.textView1); edit=(EditText)findViewById(R.id.editText1); edit.setOnKeyListener(editlistener); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_main, menu); return true; } View.OnKeyListener editlistener=new View.OnKeyListener() { public boolean onKey(View v, int keyCode, KeyEvent event) { // TODO Auto-generated method stub text.setText(edit.getText()); return false; } }; } 带背景图片的按钮 使用ImageButton来实现带背景图片的按钮。 OnFocusChangeListener焦点变化监听 ImageButton.setImageResourse()用来指定按钮的背景颜色 package com.example.test13; import android.os.Bundle; import android.app.Activity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.ImageButton; import android.widget.TextView; import android.support.v4.app.NavUtils; public class MainActivity extends Activity { private TextView tv; private ImageButton ibt; private Button bt; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tv=(TextView)findViewById(R.id.textView1); ibt=(ImageButton)findViewById(R.id.imageButton1); bt=(Button)findViewById(R.id.button1); ibt.setOnFocusChangeListener(focusChange); bt.setOnClickListener(clicked); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_main, menu); return true; } View.OnFocusChangeListener focusChange=new View.OnFocusChangeListener() { public void onFocusChange(View v, boolean hasFocus) { // TODO Auto-generated method stub if(hasFocus){ tv.setText("Got Focus!!!"); ibt.setImageResource(R.drawable.image1); } else{ tv.setText("Lost Focus!!!"); ibt.setImageResource(R.drawable.image2); } } }; View.OnClickListener clicked=new View.OnClickListener() { public void onClick(View v) { // TODO Auto-generated method stub if(tv.getText()=="Got Focus!!!"){ tv.setText("Lost Focus!!!"); ibt.setImageResource(R.drawable.image2); } else{ tv.setText("Got Focus!!!"); ibt.setImageResource(R.drawable.image1); } } }; } Toast实现提示条(Toast总结) Toast.makeText()让文字显示与Toast对象中,会显示一段时间后自动消失。 Toast.makeText( MainActivity.this, "这个是Toast.makeText提示", Toast.LENGTH_LONG).show(); CheckBox和RadioButton复选框 通过CheckBox.setOnCheckedChangeLister来监听CheckBox 相框的实现 可以通过ImageButton和ImageView来实现,推荐ImageButton,它可以直接添加点击监听 java.io.File实现文件搜索 在JAVA I/O的API中,提供了java.io.File对象。 package com.example.test14; import java.io.File; import android.os.Bundle; import android.app.Activity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import android.support.v4.app.NavUtils; public class MainActivity extends Activity { private TextView result; private Button bt; private EditText edit; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); result=(TextView)findViewById(R.id.textView2); bt=(Button)findViewById(R.id.button1); edit=(EditText)findViewById(R.id.editText1); bt.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { // TODO Auto-generated method stub String keyword=edit.getText().toString(); if(keyword.equals("")){ Toast.makeText( MainActivity.this, "不能为空!", Toast.LENGTH_LONG).show(); } else{ result.setText(searchFile(keyword)); } } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_main, menu); return true; } private String searchFile(String Keyword){ String searchResult=""; File[] files=new File("/").listFiles(); for(File f:files){ if(f.getName().indexOf(Keyword)>=0) searchResult+=f.getPath()+"\n";// \n换行 } if(searchResult.equals("")) searchResult="找不到文件!!!!"; return searchResult; } } 本文转自cococo点点博客园博客,原文链接:http://www.cnblogs.com/coder2012/archive/2013/05/17/3083991.html,如需转载请自行联系原作者

优秀的个人博客,低调大师

操作主机角色笔记

操作主机角色 1架构主机 架构主机控制整个林的架构的全部更新 手工安装 运行——regsvr32 schmmgmt.dll 运行——mmc——文件——添加或删除管理单元——Active Directory架构 2域命名主机 域命名主机控制林中域的添加或删除,可以防止林中的域名重复. 管理工具——Active Directory域和信任关系 3PDC仿真主机 管理来自客户端的密码更改 最小化密码变化的复制等待时间 管理工具——Active Directory用户和计算机——右击域名——操作主机——PDC 4RID主机 RID主机将相对ID(RID)序列分配给域中每个域控制器 管理工具——Active Directory用户和计算机——右击域名——操作主机——RID 5基础结构主机 基础结构主机负责更新从它所在域中的对象到其他域中对象的引用 转移操作主机角色 转移架构主机 Active Directory架构——更改Active Directory域控制器——更改目录服务器——第2台域控制器 Active Directory架构——操作主机——更改 转移RID、PDC、基础结构主机 Active Directory用户和计算机——更改Active Directory域控制器——更改目录服务器——第2台域控制器 Active Directory用户和计算机——操作主机——RID——更改 Active Directory用户和计算机——操作主机——PDC——更改 Active Directory用户和计算机——操作主机——基础结构主机——更改 转移域命名主机 Active Directory域和信任关系——更改Active Directory域控制器——更改目录服务器——第2台域控制器 Active Directory域和信任关系——操作主机——更改 使用命令行转移操作主机 1cmd 2ntdsutil 3roles 4connection 5connect to server dc02.benet.com(目标域控制器) 6quit 帮助命令help 7transferPDC 8transferRID master 9transfer infrastructure master 基础结构 10transfer domain naming master域命名 11transfer schema master 架构 使用命令行占用操作主机 1cmd 2ntdsutil 3roles 4connection 5connect to server dc02.benet.com(目标域控制器) 6quit 帮助命令help 7seizePDC 8seizeRID master 9seize infrastructure master 基础结构 10seize domain naming master 域命名 11seize schema master 架构 在占用角色时,一定要保证DNS能正确解析域名 授权还原 非授权还原 本文转自 jin626889 51CTO博客,原文链接:http://blog.51cto.com/zuoshou/1291883,如需转载请自行联系原作者

优秀的个人博客,低调大师

Android笔记:热门标签,流式布局

一、测试效果未成功 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 package cn.app.meiya.aa.widget; import android.content.Context; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; import java.util.ArrayList; import java.util.List; /** *类似话题标签的流式布局,测试效果无效 *http://www.apkbus.com/android-239725-1-1.html *Createdbylonshineon15/7/16. */ public class TopicFlowLayout extends ViewGroup{ //存储所有子View private List<List<View>>mAllChildViews= new ArrayList<>(); //每一行的高度 private List<Integer>mLineHeight= new ArrayList<>(); public TopicFlowLayout(Contextcontext){ this (context, null ); //TODOAuto-generatedconstructorstub } public TopicFlowLayout(Contextcontext,AttributeSetattrs){ this (context,attrs, 0 ); //TODOAuto-generatedconstructorstub } public TopicFlowLayout(Contextcontext,AttributeSetattrs, int defStyle){ super (context,attrs,defStyle); //TODOAuto-generatedconstructorstub } @Override protected void onMeasure( int widthMeasureSpec, int heightMeasureSpec){ //TODOAuto-generatedmethodstub //父控件传进来的宽度和高度以及对应的测量模式 int sizeWidth=MeasureSpec.getSize(widthMeasureSpec); int modeWidth=MeasureSpec.getMode(widthMeasureSpec); int sizeHeight=MeasureSpec.getSize(heightMeasureSpec); int modeHeight=MeasureSpec.getMode(heightMeasureSpec); //如果当前ViewGroup的宽高为wrap_content的情况 int width= 0 ; //自己测量的宽度 int height= 0 ; //自己测量的高度 //记录每一行的宽度和高度 int lineWidth= 0 ; int lineHeight= 0 ; //获取子view的个数 int childCount=getChildCount(); for ( int i= 0 ;i<childCount;i++){ Viewchild=getChildAt(i); //测量子View的宽和高 measureChild(child,widthMeasureSpec,heightMeasureSpec); //得到LayoutParams MarginLayoutParamslp=(MarginLayoutParams)getLayoutParams(); //子View占据的宽度 int childWidth=child.getMeasuredWidth()+lp.leftMargin+lp.rightMargin; //子View占据的高度 int childHeight=child.getMeasuredHeight()+lp.topMargin+lp.bottomMargin; //换行时候 if (lineWidth+childWidth>sizeWidth){ //对比得到最大的宽度 width=Math.max(width,lineWidth); //重置lineWidth lineWidth=childWidth; //记录行高 height+=lineHeight; lineHeight=childHeight; } else { //不换行情况 //叠加行宽 lineWidth+=childWidth; //得到最大行高 lineHeight=Math.max(lineHeight,childHeight); } //处理最后一个子View的情况 if (i==childCount- 1 ){ width=Math.max(width,lineWidth); height+=lineHeight; } } //wrap_content setMeasuredDimension(modeWidth==MeasureSpec.EXACTLY?sizeWidth:width, modeHeight==MeasureSpec.EXACTLY?sizeHeight:height); super .onMeasure(widthMeasureSpec,heightMeasureSpec); } @Override protected void onLayout( boolean changed, int l, int t, int r, int b){ //TODOAuto-generatedmethodstub mAllChildViews.clear(); mLineHeight.clear(); //获取当前ViewGroup的宽度 int width=getWidth(); int lineWidth= 0 ; int lineHeight= 0 ; //记录当前行的view List<View>lineViews= new ArrayList<View>(); int childCount=getChildCount(); for ( int i= 0 ;i<childCount;i++){ Viewchild=getChildAt(i); MarginLayoutParamslp=(MarginLayoutParams)child.getLayoutParams(); int childWidth=child.getMeasuredWidth(); int childHeight=child.getMeasuredHeight(); //如果需要换行 if (childWidth+lineWidth+lp.leftMargin+lp.rightMargin>width){ //记录LineHeight mLineHeight.add(lineHeight); //记录当前行的Views mAllChildViews.add(lineViews); //重置行的宽高 lineWidth= 0 ; lineHeight=childHeight+lp.topMargin+lp.bottomMargin; //重置view的集合 lineViews= new ArrayList(); } lineWidth+=childWidth+lp.leftMargin+lp.rightMargin; lineHeight=Math.max(lineHeight,childHeight+lp.topMargin+lp.bottomMargin); lineViews.add(child); } //处理最后一行 mLineHeight.add(lineHeight); mAllChildViews.add(lineViews); //设置子View的位置 int left= 0 ; int top= 0 ; //获取行数 int lineCount=mAllChildViews.size(); for ( int i= 0 ;i<lineCount;i++){ //当前行的views和高度 lineViews=mAllChildViews.get(i); lineHeight=mLineHeight.get(i); for ( int j= 0 ;j<lineViews.size();j++){ Viewchild=lineViews.get(j); //判断是否显示 if (child.getVisibility()==View.GONE){ continue ; } MarginLayoutParamslp=(MarginLayoutParams)child.getLayoutParams(); int cLeft=left+lp.leftMargin; int cTop=top+lp.topMargin; int cRight=cLeft+child.getMeasuredWidth(); int cBottom=cTop+child.getMeasuredHeight(); //进行子View进行布局 child.layout(cLeft,cTop,cRight,cBottom); left+=child.getMeasuredWidth()+lp.leftMargin+lp.rightMargin; } left= 0 ; top+=lineHeight; } } /** *与当前ViewGroup对应的LayoutParams */ @Override public LayoutParamsgenerateLayoutParams(AttributeSetattrs){ //TODOAuto-generatedmethodstub return new MarginLayoutParams(getContext(),attrs); } } 用法: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 <fontcolor= "#362e2b" ><fontstyle= "background-color:rgb(255,255,255)" ><fontface= "Arial" ><fontstyle= "font-size:14px" > package com.czm.flowlayout; import android.app.Activity; import android.graphics.Color; import android.os.Bundle; import android.view.ViewGroup.LayoutParams; import android.view.ViewGroup.MarginLayoutParams; import android.widget.TextView; /** * *@authorcaizhiming *@createdon2015-4-13 */ public class MainActivity extends Activity{ private StringmNames[]={ "welcome" , "android" , "TextView" , "apple" , "jamy" , "kobebryant" , "jordan" , "layout" , "viewgroup" , "margin" , "padding" , "text" , "name" , "type" , "search" , "logcat" }; private XCFlowLayoutmFlowLayout; @Override protected void onCreate(BundlesavedInstanceState){ super .onCreate(savedInstanceState); setContentView(R.layout.activity_main); initChildViews(); } private void initChildViews(){ //TODOAuto-generatedmethodstub mFlowLayout=(XCFlowLayout)findViewById(R.id.flowlayout); MarginLayoutParamslp= new MarginLayoutParams( LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT); lp.leftMargin= 5 ; lp.rightMargin= 5 ; lp.topMargin= 5 ; lp.bottomMargin= 5 ; for ( int i= 0 ;i<mNames.length;i++){ TextViewview= new TextView( this ); view.setText(mNames[i]); view.setTextColor(Color.WHITE); view.setBackgroundDrawable(getResources().getDrawable(R.drawable.textview_bg)); mFlowLayout.addView(view,lp); } } }</font></font></font></font> 二、测试可用 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 package cn.app.meiya.aa.widget; import android.content.Context; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; /** *http://www.bkjia.com/Androidjc/1013458.html *Createdbylonshineon15/7/16. */ public class FlowLayout extends ViewGroup{ private float mVerticalSpacing; //每个item纵向间距 private float mHorizontalSpacing; //每个item横向间距 public FlowLayout(Contextcontext){ super (context); } public FlowLayout(Contextcontext,AttributeSetattrs){ super (context,attrs); } public void setHorizontalSpacing( float pixelSize){ mHorizontalSpacing=pixelSize; } public void setVerticalSpacing( float pixelSize){ mVerticalSpacing=pixelSize; } @Override protected void onMeasure( int widthMeasureSpec, int heightMeasureSpec){ int selfWidth=resolveSize( 0 ,widthMeasureSpec); int paddingLeft=getPaddingLeft(); int paddingTop=getPaddingTop(); int paddingRight=getPaddingRight(); int paddingBottom=getPaddingBottom(); int childLeft=paddingLeft; int childTop=paddingTop; int lineHeight= 0 ; //通过计算每一个子控件的高度,得到自己的高度 for ( int i= 0 ,childCount=getChildCount();i<childCount;++i){ ViewchildView=getChildAt(i); LayoutParamschildLayoutParams=childView.getLayoutParams(); childView.measure( getChildMeasureSpec(widthMeasureSpec,paddingLeft+paddingRight, childLayoutParams.width), getChildMeasureSpec(heightMeasureSpec,paddingTop+paddingBottom, childLayoutParams.height)); int childWidth=childView.getMeasuredWidth(); int childHeight=childView.getMeasuredHeight(); lineHeight=Math.max(childHeight,lineHeight); if (childLeft+childWidth+paddingRight>selfWidth){ childLeft=paddingLeft; childTop+=mVerticalSpacing+lineHeight; lineHeight=childHeight; } else { childLeft+=childWidth+mHorizontalSpacing; } } int wantedHeight=childTop+lineHeight+paddingBottom; setMeasuredDimension(selfWidth,resolveSize(wantedHeight,heightMeasureSpec)); } @Override protected void onLayout( boolean changed, int l, int t, int r, int b){ int myWidth=r-l; int paddingLeft=getPaddingLeft(); int paddingTop=getPaddingTop(); int paddingRight=getPaddingRight(); int childLeft=paddingLeft; int childTop=paddingTop; int lineHeight= 0 ; //根据子控件的宽高,计算子控件应该出现的位置。 for ( int i= 0 ,childCount=getChildCount();i<childCount;++i){ ViewchildView=getChildAt(i); if (childView.getVisibility()==View.GONE){ continue ; } int childWidth=childView.getMeasuredWidth(); int childHeight=childView.getMeasuredHeight(); lineHeight=Math.max(childHeight,lineHeight); if (childLeft+childWidth+paddingRight>myWidth){ childLeft=paddingLeft; childTop+=mVerticalSpacing+lineHeight; lineHeight=childHeight; } childView.layout(childLeft,childTop,childLeft+childWidth,childTop+childHeight); childLeft+=childWidth+mHorizontalSpacing; } } } 本文转自 glblong 51CTO博客,原文链接:http://blog.51cto.com/glblong/1675221,如需转载请自行联系原作者

优秀的个人博客,低调大师

学习笔记-安装ELK5

ELK日志平台是一个完整的日志分析系统,有三个开源工具构建组成,分别是:Elasticsearch、Logstash和Kibana。Elasticsearch用于数据分析和深度搜索;Logstash作用是从其他服务器上传输和转发日志,对其集中管理,进行分析;Kibana则是提供了强大的UI展示,将数据可视化。 安装ELK日志平台 ELK基础环境需要java环境,官网要求5.x版本要大于java8。而且安装方式多样化,支持zip、tar.gz、rpm包、deb包、window环境还有docker环境。根据自己喜好选择吧。 我选择的是yum安装,简单方便,系统要求的话没有辣么严格,官网说yum安装方式不再支持centos5.x系列了,非要用centos5.x就去使用tar.gz包吧,官网有具体方法,不再复述。yum安装方式centos6.x和centos7.x都可以,但是我推荐用centos7.x安装,不知道为啥,感觉centos7.x支持更好,centos6.x装完经常会出问题。 还有一点需要说下就是,ELK各个组件版本要一致,官网要求的! 在一个就是安装顺序,为的是确保每个组件相互调用时都能正常运行: 1、Elasticsearch X-Pack for Elasticsearch Kibana X-Pack for Kibana LogstashBeatsElasticsearch Hadoop 安装Elasticsearch 1、导入Elasticsearch安装包PGP Key 1 2 rpm-- import https: //artifacts .elastic.co /GPG-KEY-elasticsearch 2、创建yum源 1 2 3 4 5 6 7 8 9 10 [root@localhost~] #cat>>/etc/yum.repos.d/elasticsearch.repo<<EOF >[elasticsearch-5.x] >name=Elasticsearchrepository for 5.xpackages >baseurl=https: //artifacts .elastic.co /packages/5 .x /yum >gpgcheck=1 >gpgkey=https: //artifacts .elastic.co /GPG-KEY-elasticsearch >enabled=1 >autorefresh=1 > type =rpm-md >EOF 3、安装、启动Elasticsearch进程并开机启动 1 2 3 4 [wangpeng@localhost~]$ sudo yum install elasticsearch [wangpeng@localhost~]$ sudo /bin/systemctl daemon-reload [wangpeng@localhost~]$ sudo /bin/systemctl enable elasticsearch.service [wangpeng@localhost~]$ sudo systemctlstartelasticsearch.service 4、检查Elasticsearch是否已经启动 查看9200、9300是否已经启动 1 2 3 4 5 6 7 8 9 10 11 12 13 14 [wangpeng@localhost~]$curlhttp: //localhost :9200 { "name" : "F5Mw8Pp" , "cluster_name" : "elasticsearch" , "cluster_uuid" : "zVEeXtPNTaeH-TKah7Buzw" , "version" :{ "number" : "5.4.0" , "build_hash" : "780f8c4" , "build_date" : "2017-04-28T17:43:27.229Z" , "build_snapshot" : false , "lucene_version" : "6.5.0" }, "tagline" : "YouKnow,forSearch" } 5、配置Elasticsearch rpm包配置文件在/etc/elasticsearch下面的elasticsearch.yml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 vim /etc/elasticsearch/elasticsearch .yml cluster.name:elasticsearch- test node.name:node-1 path.data: /var/lib/elasticsearch path.logs: /var/log/elasticsearch network.host:0.0.0.0 [wangpeng@localhost~]$ sudo systemctlrestartelasticsearch.service [wangpeng@localhost~]$curlhttp: //localhost :9200 { "name" : "node-1" , "cluster_name" : "elasticsearch-test" , "cluster_uuid" : "zVEeXtPNTaeH-TKah7Buzw" , "version" :{ "number" : "5.4.0" , "build_hash" : "780f8c4" , "build_date" : "2017-04-28T17:43:27.229Z" , "build_snapshot" : false , "lucene_version" : "6.5.0" }, "tagline" : "YouKnow,forSearch" } 6、将/etc/elasticsearch/配置拷贝到/usr/share/elasticsearch/config下面 1 2 3 4 [wangpeng@localhost~]$ sudo mkdir /usr/share/elasticsearch/config [wangpeng@localhost~]$ sudo ln -sf /etc/elasticsearch/ * /usr/share/elasticsearch/config/ [wangpeng@localhost~]$ sudo chown -Relasticsearch:elasticsearch /usr/share/elasticsearch [wangpeng@localhost~]$ sudo systemctlrestartelasticsearch.service 注意:这一点好多人不会注意,因为你不修复也不会启动失败,但是就是写不进数据进去,这个坑好久才发现,看下日志会报错,但是却能启动,我也是服了!~ 7、装个head插件 这个插件5.X官网不再支持了,插件命令没有了,因为它有自己x-pack插件了,但是我装了x-pack发现着实让人吐血,有安全认证方面的问题,导致elk各种问题出现,目前还没研究明白,时间不充裕。 这个head插件我是直接抄的网上大神制作,略有改动。 7.1、下载并配置nodejs 由于head插件本质上还是一个nodejs的工程,因此需要安装node,使用npm来安装依赖的包。(npm可以理解为maven) 去官网下载nodejs,https://nodejs.org/en/download/ 1 2 3 4 5 6 wgethttps: //nodejs .org /dist/v8 .1.1 /node-v8 .1.1-linux-x64. tar .xz tar xfnode-v8.1.1-linux-x64. tar .xz mv node-v8.1.1-linux-x64 /usr/local/node chown -Relasticsearch:elasticsearch /usr/local/node ln -sf /usr/local/node/bin/node /usr/bin/node ln -sf /usr/local/node/bin/npm /usr/bin/npm 7.2、安装grunt 1 2 npm install -ggrunt-cli ln -sf /usr/local/node/bin/grunt /usr/bin/grunt cd /var/lib/elasticsearch 7.3、下载、安装并配置head 1 2 3 4 5 6 yum-y install git cd /var/lib/elasticsearch gitclonegit: //github .com /mobz/elasticsearch-head .git chown -Relasticsearch:elasticsearchelasticsearch- head / cd elasticsearch- head / npm install 7.4、配置head文件 1 2 3 4 5 6 7 8 9 10 11 12 13 14 [root@elk-node1~] #cd/var/lib/elasticsearch/elasticsearch-head/ vimGruntfile.js connect:{ server:{ options:{ port:9100, hostname : "0.0.0.0" , base: '.' , keepalive: true } } } [root@elk-node1elasticsearch- head ] #cd_site/ [root@elk-node1_site] #vimapp.js 把localhost修改成你es的服务器地址: 1 this.base_uri=this.config.base_uri||this.prefs.get( "app-base_uri" )|| "http://10.10.10.10:9200" ; 7.5、启动head插件 1 gruntserver& 安装Kibana 1、yum安装Kibana 1 [wangpeng@localhost~]$ sudo yum install kibana rpm包配置文件在/etc/kibana下面的kibana.yml /etc/kibana/kibana.yml 2、配置Kibana文件 1 2 3 4 [wangpeng@localhost~]$vim /etc/kibana/kibana .yml server.port:5601 server.host: "0.0.0.0" elasticsearch.url: "http://localhost:9200" 3、启动并设置开机启动 1 2 3 [wangpeng@localhost~]$ sudo systemctl enable kibana.service Created symlink from /etc/systemd/system/multi-user .target.wants /kibana .serviceto /etc/systemd/system/kibana .service [wangpeng@localhost~]$ sudo systemctlstartkibana.service 安装Logstash 1、yum安装Logstash 1 2 3 4 5 [wangpeng@localhost~]$ sudo yum-y install logstash [wangpeng@localhost~]$ sudo systemctlstartlogstash.service [wangpeng@localhost~]$ sudo ln -s /usr/share/logstash/bin/logstash /usr/bin/logstash [wangpeng@localhost~]$ sudo -ulogstashsh-c 'mkdir-pv/usr/share/logstash/config' [wangpeng@localhost~]$ sudo -ulogstashsh-c 'ln-s/etc/logstash/*/usr/share/logstash/config/' 2、测试Logstash是否能正常运行 1 2 3 4 5 6 7 8 9 10 11 12 13 [wangpeng@localhost~]$ sudo logstash-e 'input{stdin{}}output{stdout{}}' helloworld 2017-06-02T07:14:13.130Zlocalhosthelloworld [wangpeng@localhost~]$ sudo logstash-e'input{stdin{}}output{ stdout{codec=>rubydebug}}' helloworld Thestdinpluginisnowwaiting for input: { "@timestamp" =>2017-06-02T07:17:44.053Z, "@version" => "1" , "host" => "localhost" , "message" => "helloworld" } 3、写个测试文件,测试一下es是否能够接受数据 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 [wangpeng@localhost~]$vim /etc/logstash/conf .d /test .conf input{ stdin{} } output{ elasticsearch{ hosts=> "127.0.0.1:9200" index=> "test-messages-%{+YYYY.MM.dd}" } } [wangpeng@localhost~]$logstash-f /etc/logstash/conf .d /test .conf-t SendingLogstash'slogsto /var/log/logstash which isnowconfiguredvialog4j2.properties ConfigurationOK [wangpeng@localhost~]$logstash-f /etc/logstash/conf .d /test .conf SendingLogstash'slogsto /var/log/logstash which isnowconfiguredvialog4j2.properties Thestdinpluginisnowwaiting for input: helloworld thisis test message studylogstash 4、Kibana里添加该索引(测试),只要es里面能产生索引,Kibana就能加在上去 安装调试先到这里。 本文转自 wangpengtai 51CTO博客,原文链接:http://blog.51cto.com/wangpengtai/1939138,如需转载请自行联系原作者

优秀的个人博客,低调大师

学习笔记TF065:TensorFlowOnSpark

Hadoop生态大数据系统分为Yam、 HDFS、MapReduce计算框架。TensorFlow分布式相当于MapReduce计算框架,Kubernetes相当于Yam调度系统。TensorFlowOnSpark,利用远程直接内存访问(Remote Direct Memory Access,RDMA)解决存储功能和调度,实现深度学习和大数据融合。TensorFlowOnSpark(TFoS),雅虎开源项目。https://github.com/yahoo/TensorFlowOnSpark 。支持ApacheSpark集群分布式TensorFlow训练、预测。TensorFlowOnSpark提供桥接程序,每个Spark Executor启动一个对应TensorFlow进程,通过远程进程通信(RPC)交互。 TensorFlowOnSpark架构。TensorFlow训练程序用Spark集群运行,管理Spark集群步骤:预留,在Executor执行每个TensorFlow进程保留一个端口,启动数据消息监听器。启动,在Executor启动TensorFlow主函数。数据获取,TensorFlow Readers和QueueRunners机制直接读取HDFS数据文件,Spark不访问数据;Feeding,SparkRDD 数据发送TensorFlow节点,数据通过feed_dict机制传入TensorFlow计算图。关闭,关闭Executor TensorFlow计算节点、参数服务节点。Spark Driver->Spark Executor->参数服务器->TensorFlow Core->gRPC、RDMA->HDFS数据集。http://yahoohadoop.tumblr.com/post/157196317141/open-sourcing-tensorflowonspark-distributed-deep 。 TensorFlowOnSpark MNIST。https://github.com/yahoo/TensorFlowOnSpark/wiki/GetStarted_standalone 。Standalone模式Spark集群,一台计算机。安装 Spark、Hadoop。部署Java 1.8.0 JDK。下载Spark2.1.0版 http://spark.apache.org/downloads.html 。下载Hadoop2.7.3版 http://hadoop.apache.org/#Download+Hadoop 。0.12.1版本支持较好。修改配置文件,设置环境变量,启动Hadoop:$HADOOP_HOME/sbin/start-all.sh。检出TensorFlowOnSpark源代码: git clone --recurse-submodules https://github.com/yahoo/TensorFlowOnSpark.git cd TensorFlowOnSpark git submodule init git submodule update --force git submodule foreach --recursive git clean -dfx 源代码打包,提交任务使用: cd TensorflowOnSpark/src zip -r ../tfspark.zip * 设置TensorFlowOnSpark根目录环境变量: cd TensorFlowOnSpark export TFoS_HOME=$(pwd) 启动Spark主节点(master): $(SPARK_HOME)/sbin/start-master.sh 配置两个工作节点(worker)实例,master-spark-URL连接主节点: export MASTER=spark://$(hostname):7077 export SPARK_WORKER_INSTANCES=2 export CORES_PER_WORKER=1 export TOTAL_CORES=$(($(CORES_PER_WORKER)*$(SPARK_WORKER_INSTANCES))) $(SPARK_HOME)/sbin/start-slave.sh -c $CORES_PER_WORKER -m 3G $(MASTER) 提交任务,MNIST zip文件转换为HDFS RDD 数据集: $(SPARK_HOME)/bin/spark-submit \ --master $(MASTER) --conf spark.ui.port=4048 --verbose \ $(TFoS_HOME)/examples/mnist/mnist_data_setup.py \ --output examples/mnist/csv \ --format csv 查看处理过的数据集: hadoop fs -ls hdfs://localhost:9000/user/libinggen/examples/mnist/csv 查看保存图片、标记向量: hadoop fs -ls hdfs://localhost:9000/user/libinggen/examples/mnist/csv/train/labels 把训练集、测试集分别保存RDD数据。https://github.com/yahoo/TensorFlowOnSpark/blob/master/examples/mnist/mnist_data_setup.py 。 from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy import tensorflow as tf from array import array from tensorflow.contrib.learn.python.learn.datasets import mnist def toTFExample(image, label): """Serializes an image/label as a TFExample byte string""" example = tf.train.Example( features = tf.train.Features( feature = { 'label': tf.train.Feature(int64_list=tf.train.Int64List(value=label.astype("int64"))), 'image': tf.train.Feature(int64_list=tf.train.Int64List(value=image.astype("int64"))) } ) ) return example.SerializeToString() def fromTFExample(bytestr): """Deserializes a TFExample from a byte string""" example = tf.train.Example() example.ParseFromString(bytestr) return example def toCSV(vec): """Converts a vector/array into a CSV string""" return ','.join([str(i) for i in vec]) def fromCSV(s): """Converts a CSV string to a vector/array""" return [float(x) for x in s.split(',') if len(s) > 0] def writeMNIST(sc, input_images, input_labels, output, format, num_partitions): """Writes MNIST image/label vectors into parallelized files on HDFS""" # load MNIST gzip into memory # MNIST图像、标记向量写入HDFS with open(input_images, 'rb') as f: images = numpy.array(mnist.extract_images(f)) with open(input_labels, 'rb') as f: if format == "csv2": labels = numpy.array(mnist.extract_labels(f, one_hot=False)) else: labels = numpy.array(mnist.extract_labels(f, one_hot=True)) shape = images.shape print("images.shape: {0}".format(shape)) # 60000 x 28 x 28 print("labels.shape: {0}".format(labels.shape)) # 60000 x 10 # create RDDs of vectors imageRDD = sc.parallelize(images.reshape(shape[0], shape[1] * shape[2]), num_partitions) labelRDD = sc.parallelize(labels, num_partitions) output_images = output + "/images" output_labels = output + "/labels" # save RDDs as specific format # RDDs保存特定格式 if format == "pickle": imageRDD.saveAsPickleFile(output_images) labelRDD.saveAsPickleFile(output_labels) elif format == "csv": imageRDD.map(toCSV).saveAsTextFile(output_images) labelRDD.map(toCSV).saveAsTextFile(output_labels) elif format == "csv2": imageRDD.map(toCSV).zip(labelRDD).map(lambda x: str(x[1]) + "|" + x[0]).saveAsTextFile(output) else: # format == "tfr": tfRDD = imageRDD.zip(labelRDD).map(lambda x: (bytearray(toTFExample(x[0], x[1])), None)) # requires: --jars tensorflow-hadoop-1.0-SNAPSHOT.jar tfRDD.saveAsNewAPIHadoopFile(output, "org.tensorflow.hadoop.io.TFRecordFileOutputFormat", keyClass="org.apache.hadoop.io.BytesWritable", valueClass="org.apache.hadoop.io.NullWritable") # Note: this creates TFRecord files w/o requiring a custom Input/Output format # else: # format == "tfr": # def writeTFRecords(index, iter): # output_path = "{0}/part-{1:05d}".format(output, index) # writer = tf.python_io.TFRecordWriter(output_path) # for example in iter: # writer.write(example) # return [output_path] # tfRDD = imageRDD.zip(labelRDD).map(lambda x: toTFExample(x[0], x[1])) # tfRDD.mapPartitionsWithIndex(writeTFRecords).collect() def readMNIST(sc, output, format): """Reads/verifies previously created output""" output_images = output + "/images" output_labels = output + "/labels" imageRDD = None labelRDD = None if format == "pickle": imageRDD = sc.pickleFile(output_images) labelRDD = sc.pickleFile(output_labels) elif format == "csv": imageRDD = sc.textFile(output_images).map(fromCSV) labelRDD = sc.textFile(output_labels).map(fromCSV) else: # format.startswith("tf"): # requires: --jars tensorflow-hadoop-1.0-SNAPSHOT.jar tfRDD = sc.newAPIHadoopFile(output, "org.tensorflow.hadoop.io.TFRecordFileInputFormat", keyClass="org.apache.hadoop.io.BytesWritable", valueClass="org.apache.hadoop.io.NullWritable") imageRDD = tfRDD.map(lambda x: fromTFExample(str(x[0]))) num_images = imageRDD.count() num_labels = labelRDD.count() if labelRDD is not None else num_images samples = imageRDD.take(10) print("num_images: ", num_images) print("num_labels: ", num_labels) print("samples: ", samples) if __name__ == "__main__": import argparse from pyspark.context import SparkContext from pyspark.conf import SparkConf parser = argparse.ArgumentParser() parser.add_argument("-f", "--format", help="output format", choices=["csv","csv2","pickle","tf","tfr"], default="csv") parser.add_argument("-n", "--num-partitions", help="Number of output partitions", type=int, default=10) parser.add_argument("-o", "--output", help="HDFS directory to save examples in parallelized format", default="mnist_data") parser.add_argument("-r", "--read", help="read previously saved examples", action="store_true") parser.add_argument("-v", "--verify", help="verify saved examples after writing", action="store_true") args = parser.parse_args() print("args:",args) sc = SparkContext(conf=SparkConf().setAppName("mnist_parallelize")) if not args.read: # Note: these files are inside the mnist.zip file writeMNIST(sc, "mnist/train-images-idx3-ubyte.gz", "mnist/train-labels-idx1-ubyte.gz", args.output + "/train", args.format, args.num_partitions) writeMNIST(sc, "mnist/t10k-images-idx3-ubyte.gz", "mnist/t10k-labels-idx1-ubyte.gz", args.output + "/test", args.format, args.num_partitions) if args.read or args.verify: readMNIST(sc, args.output + "/train", args.format) 提交训练任务,开始训练,在HDFS生成mnist_model,命令: ${SPARK_HOME}/bin/spark-submit \ --master ${MASTER} \ --py-files ${TFoS_HOME}/examples/mnist/spark/mnist_dist.py \ --conf spark.cores.max=${TOTAL_CORES} \ --conf spark.task.cpus=${CORES_PER_WORKER} \ --conf spark.executorEnv.JAVA_HOME="$JAVA_HOME" \ ${TFoS_HOME}/examples/mnist/spark/mnist_spark.py \ --cluster_size ${SPARK_WORKER_INSTANCES} \ --images examples/mnist/csv/train/images \ --labels examples/mnist/csv/train/labels \ --format csv \ --mode train \ --model mnist_model mnist_dist.py 构建TensorFlow 分布式任务,定义分布式任务主函数,启动TensorFlow主函数map_fun,数据获取方式Feeding。获取TensorFlow集群和服务器实例: cluster, server = TFNode.start_cluster_server(ctx, 1, args.rdma) TFNode调用tfspark.zip TFNode.py文件。 mnist_spark.py文件是训练主程序,TensorFlowOnSpark部署步骤: from __future__ import absolute_import from __future__ import division from __future__ import print_function from pyspark.context import SparkContext from pyspark.conf import SparkConf import argparse import os import numpy import sys import tensorflow as tf import threading import time from datetime import datetime from tensorflowonspark import TFCluster import mnist_dist sc = SparkContext(conf=SparkConf().setAppName("mnist_spark")) executors = sc._conf.get("spark.executor.instances") num_executors = int(executors) if executors is not None else 1 num_ps = 1 parser = argparse.ArgumentParser() parser.add_argument("-b", "--batch_size", help="number of records per batch", type=int, default=100) parser.add_argument("-e", "--epochs", help="number of epochs", type=int, default=1) parser.add_argument("-f", "--format", help="example format: (csv|pickle|tfr)", choices=["csv","pickle","tfr"], default="csv") parser.add_argument("-i", "--images", help="HDFS path to MNIST images in parallelized format") parser.add_argument("-l", "--labels", help="HDFS path to MNIST labels in parallelized format") parser.add_argument("-m", "--model", help="HDFS path to save/load model during train/inference", default="mnist_model") parser.add_argument("-n", "--cluster_size", help="number of nodes in the cluster", type=int, default=num_executors) parser.add_argument("-o", "--output", help="HDFS path to save test/inference output", default="predictions") parser.add_argument("-r", "--readers", help="number of reader/enqueue threads", type=int, default=1) parser.add_argument("-s", "--steps", help="maximum number of steps", type=int, default=1000) parser.add_argument("-tb", "--tensorboard", help="launch tensorboard process", action="store_true") parser.add_argument("-X", "--mode", help="train|inference", default="train") parser.add_argument("-c", "--rdma", help="use rdma connection", default=False) args = parser.parse_args() print("args:",args) print("{0} ===== Start".format(datetime.now().isoformat())) if args.format == "tfr": images = sc.newAPIHadoopFile(args.images, "org.tensorflow.hadoop.io.TFRecordFileInputFormat", keyClass="org.apache.hadoop.io.BytesWritable", valueClass="org.apache.hadoop.io.NullWritable") def toNumpy(bytestr): example = tf.train.Example() example.ParseFromString(bytestr) features = example.features.feature image = numpy.array(features['image'].int64_list.value) label = numpy.array(features['label'].int64_list.value) return (image, label) dataRDD = images.map(lambda x: toNumpy(str(x[0]))) else: if args.format == "csv": images = sc.textFile(args.images).map(lambda ln: [int(x) for x in ln.split(',')]) labels = sc.textFile(args.labels).map(lambda ln: [float(x) for x in ln.split(',')]) else: # args.format == "pickle": images = sc.pickleFile(args.images) labels = sc.pickleFile(args.labels) print("zipping images and labels") dataRDD = images.zip(labels) #1.为在Executor执行每个TensorFlow进程保留一个端口 cluster = TFCluster.run(sc, mnist_dist.map_fun, args, args.cluster_size, num_ps, args.tensorboard, TFCluster.InputMode.SPARK) #2.启动Tensorflow主函数 cluster.start(mnist_dist.map_fun, args) if args.mode == "train": #3.训练 cluster.train(dataRDD, args.epochs) else: #3.预测 labelRDD = cluster.inference(dataRDD) labelRDD.saveAsTextFile(args.output) #4.关闭Executor TensorFlow计算节点、参数服务节点 cluster.shutdown() print("{0} ===== Stop".format(datetime.now().isoformat())) 预测命令: ${SPARK_HOME}/bin/spark-submit \ --master ${MASTER} \ --py-files ${TFoS_HOME}/examples/mnist/spark/mnist_dist.py \ --conf spark.cores.max=${TOTAL_CORES} \ --conf spark.task.cpus=${CORES_PER_WORKER} \ --conf spark.executorEnv.JAVA_HOME="$JAVA_HOME" \ ${TFoS_HOME}/examples/mnist/spark/mnist_spark.py \ --cluster_size ${SPARK_WORKER_INSTANCES} \ --images examples/mnist/csv/test/images \ --labels examples/mnist/csv/test/labels \ --mode inference \ --format csv \ --model mnist_model \ --output predictions 还可以Amazon EC2运行及在Hadoop集群采用YARN模式运行。 参考资料:《TensorFlow技术解析与实战》 欢迎推荐上海机器学习工作机会,我的微信:qingxingfengzi

优秀的个人博客,低调大师

Android学习笔记--Content Provider 1

MicrosoftInternetExplorer402DocumentNotSpecified7.8Normal0 1.ContentProvider基本概念 A:ContentProvider提供为存储和获取数据提供了统一的接口 B:使用ContentProvider可以在不同的应用程序之间共享数据 C:Android为常见的一些数据提供了ContentProvider(包括音频,视频,图片和通讯录等等) 2.Uri A:每一个ContnetProvider都拥有一个公共的URI,这个URI用于表示这个ContnetProvider所提供的数据 B:Android所提供的ContentProvider都存放在android.provider包当中 3.ContnetProvider实现方法 Query Insert Update Delete getType onCreate 4.实现ContentProvider的过程 A:定义一个Content_URI常量 B:定义一个类,继承ContentProvider C:实现query,insertupdate,deletegetType,和onCreate方法; D:在AnroidManifest.xml当中进行声明; 例: //DatabaseHelper所为一个访问SQLite的助手类,提供两个方面的功能 //第一,getReadableDatabase()和getWritableDatabasr()可以获得SQLiteDatabase对象 //第二,提供onCreate和onUpgrade两个回调函数,允许我们在创建和升级数据库时,进行操作 例:publicclassDatabaseHelperextendsSQLiteOpenHelper{ //数据库版本号 PrivatestaticfinalintVERSION=1; //必须的构造函数 PublicDatabaseHelper(Contextcontext,Stringname,CursorFactoryfactory,intversion){ Super(context,name,factory,version); } PublicDatabaseHelper(Contextcontext,Stringname,intversion){ Super(context,name,null,version); } PublicDatabaseHelper(Contextcontext,Stringname){ Super(context,name,null,VERSION); } PublicvoidonCreate(SQLiteDatabasedb){ System.out.println("createadatabase"); //拼出了建表的语句 db..execSQL("createtable"+ FirstMetaData.USER_TABLE_NAME +"("+FirstMetaData.UserTableMetaData._ID +"INTEGERPRIMARYKEYAUTOINCREMENT," +FirstMetaData.UserTableMetaData.USER_NAME +"varchar(20));"; } PublicvoidonUpgrade(SQLiteDatabasedb){ System.out.println("updateadatabase"); } } ContentProviderActivity例: 1.声明控件对象(略) 2.获得控件对象(略) 3.绑定事件(略) 4.创建监听器对象 //insert PublicvoidonClick(Viewv){ ContentValuesvalues=newContentValues(); Values.put( FirstMetaData.UserTableMetaData.USER_NAME,"zhangsan" ); Uriuri=getContentesolver().insert( FirstMetaData.UserTableMetaData.CONTENT_URI,values ); System.out.println("uri---->"+uri.toString()); } //query PublicvoidonClick(Viewv){ Cursorc=getContentResolver().query( FirstMetaData.UserTableMetaData.CONTENT_URI,null,null,null,null ); While(c.moveToNext()){ System.out.println(c.getString(c.getColumnIndex(UserTableMeatData.USER_NAME))); } } 本文转自My_King1 51CTO博客,原文链接:http://blog.51cto.com/apprentice/1360568,如需转载请自行联系原作者

优秀的个人博客,低调大师

MQTT 折腾笔记----协议简读

导言 第一次听说MQTT 这玩意是由于要找个做手机推送的方案,后来发现,JPush这家伙做的实在不错,然后就不折腾了,最近,忽然心血来潮,把MQTT 协议看了一遍,网上的很多中文的资料都是坑爹的,全部都是说MQTT 做推送,我按图索骥全部都是转载翻译自老外2010写的这篇文章实在汗颜...后来,我改用全英文关键字,搜索总算发现了MQTT 的用处.如果,你不愿意看我的长篇大论我建议你去wiki那里看下MQTT 详细介绍 MQTT 解决什么事情? 对于需要要了解一个什么玩意,我们需要这玩意,解决我们什么事情.从WIKI 来看MQTT 协议主要解决的是机器与机器之间数据通信,各位想到什么没?有接触过物联网的话,可能有所了解了,当我们所有机器都能在一个网络上面分配的一个地址的话,由于,设备间的性能差异,低到可能就是一个插座,而你需要这个插座能进行数据通信,例如,控制这个插座的开-闭这类的,就需要一个极其轻量级的协议而MQTT 协议就是为此目的诞生的. 比较有趣的是,MQTT这个协议在1999 年就有了最新的版本是v3.1(2010/12/06),其适用于如下但不限于这几点: 即时传输的轻量级协议 专门设计用于低带宽或者高昂的网络费用 具备三种服务品质层级 MQTT 协议简读 MQTT 协议相对某些协议来说,实在是简短的令人发指,整个协议只用42页就说完了. MQTT v3 到 v3.1 有几点比较重要的变化个人感觉最重要的是从ascii 码转向 utf8的支持,不过我估计没人用过v3 所有我这里不多说了,有兴趣的,请翻阅一下协议文档..... 传输开销的比较 MQTT 最引以为豪的就是最小的2 byte 头部传输开销.我们看下其他流行的协议的message format的设计 XMPP消息体用的是xml |--------------------| | <stream> | |--------------------| | <presence> | | <show/> | | </presence> | |--------------------| | <message to='foo'> | | <body/> | | </message> | |--------------------| | <iq to='bar'> | | <query/> | | </iq> | |--------------------| | ... | |--------------------| | </stream> | |--------------------| HTTP HTTP-message = Request | Response ; HTTP/1.1 messages 还有很多协议,就不一样细说了,就举两个我比较了解的.就目前通用的协议来看很少有比MQTT 还要低的传输开销了.如果,你有了解的希望介绍一下. 消息体的设计简说 bit 7 6 5 4 3 2 1 0 byte 1 Message Type DUP flag QoS level RETAIN byte 2 Remaining Length 第一个byte 用于说明消息体的信息. 第二个byte 用于传输我们需要传输的数据. 更多详情请看协议 msg-format 部分 接下来,结合一个最简例子来对这个消息体进行说明 MQTT 最简例子 为了方便进行MQTT的了解与使用,目前MQTT的资料极其匮乏,也找不到什么给力的例子所以,随着我研究的深度,来慢慢提高这些例子的难度. 准备 服务端: nodejs:MQTT.js 客户端: nodejs:MQTT.js java:Paho 例子地址:https://github.com/youxiachai/mqttlesson/tree/master/LessonOnejava 版本暂未提供,晚些时候写个android的客户端.... 例子设计 为了简单,方便理解,这个例子: 服务器是一个广播模型 对于订阅/发布没有限制使用topic(主要是为了后面的知识做准备) 订阅者获取到一次发布者消息就断开连接 首先服务端启动,接着启动 mqttClientSub 例子流程图: clientA ->(connect) server 启动发布者:mqttClientPub 例子流程图: clientB ->(publish) server ->(pub) clientA 以上就是整个例子的流程 版权声明:原创作品,如需转载,请注明出处。否则将追究法律责任 本文转自 liam2199 博客,原文链接: http://blog.51cto.com/youxilua/1186126 如需转载请自行联系原作者

优秀的个人博客,低调大师

Android笔记:intent方法使用总结

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 //showwebapp: Uriuri=Uri.parse( "http://www.google.com" ); Intentit= new Intent(Intent.ACTION_VIEW,uri); startActivity(it); //showmaps: Uriuri=Uri.parse( "geo:38.899533,-77.036476" ); Intentit= new Intent(Intent.Action_VIEW,uri); startActivity(it); //showways Uriuri=Uri.parse( "http://maps.google.com/maps?f=d&saddr=startLat%20startLng&daddr=endLat%20endLng&hl=en" ); Intentit= new Intent(Intent.ACTION_VIEW,URI); startActivity(it); //calldialprogram Uriuri=Uri.parse( "tel:xxxxxx" ); Intentit= new Intent(Intent.ACTION_DIAL,uri); startActivity(it); Uriuri=Uri.parse( "tel.xxxxxx" ); Intentit= new Intent(Intent.ACTION_CALL,uri); //don'tforgetaddthisconfig:<uses-permissionid="android.permission.CALL_PHONE"/> //sendsms/mms //callsenderprogram Intentit= new Intent(Intent.ACTION_VIEW); it.putExtra( "sms_body" , "TheSMStext" ); it.setType( "vnd.android-dir/mms-sms" ); startActivity(it); //sendsms Uriuri=Uri.parse( "smsto:0800000123" ); Intentit= new Intent(Intent.ACTION_SENDTO,uri); it.putExtra( "sms_body" , "TheSMStext" ); startActivity(it); //sendmms Uriuri=Uri.parse( "content://media/external/images/media/23" ); Intentit= new Intent(Intent.ACTION_SEND); it.putExtra( "sms_body" , "sometext" ); it.putExtra(Intent.EXTRA_STREAM,uri); it.setType( "image/png" ); startActivity(it); //sendemail Uriuri=Uri.parse( "mailto:xxx@abc.com" ); Intentit= new Intent(Intent.ACTION_SENDTO,uri); startActivity(it); Intentit= new Intent(Intent.ACTION_SEND); it.putExtra(Intent.EXTRA_EMAIL, "me@abc.com" ); it.putExtra(Intent.EXTRA_TEXT, "Theemailbodytext" ); it.setType( "text/plain" ); startActivity(Intent.createChooser(it, "ChooseEmailClient" )); Intentit= new Intent(Intent.ACTION_SEND); String[]tos={ "me@abc.com" }; String[]ccs={ "you@abc.com" }; it.putExtra(Intent.EXTRA_EMAIL,tos); it.putExtra(Intent.EXTRA_CC,ccs); it.putExtra(Intent.EXTRA_TEXT, "Theemailbodytext" ); it.putExtra(Intent.EXTRA_SUBJECT, "Theemailsubjecttext" ); it.setType( "message/rfc822" ); startActivity(Intent.createChooser(it, "ChooseEmailClient" )); //addextra Intentit= new Intent(Intent.ACTION_SEND); it.putExtra(Intent.EXTRA_SUBJECT, "Theemailsubjecttext" ); it.putExtra(Intent.EXTRA_STREAM, "file:///sdcard/mysong.mp3" ); sendIntent.setType( "audio/mp3" ); startActivity(Intent.createChooser(it, "ChooseEmailClient" )); //playmedia Intentit= new Intent(Intent.ACTION_VIEW); Uriuri=Uri.parse( "file:///sdcard/song.mp3" ); it.setDataAndType(uri, "audio/mp3" ); startActivity(it); Uriuri=Uri.withAppendedPath(MediaStore.Audio.Media.INTERNAL_CONTENT_URI, "1" ); Intentit= new Intent(Intent.ACTION_VIEW,uri); startActivity(it); //Uninstall Uriuri=Uri.fromParts( "package" ,strPackageName, null ); Intentit= new Intent(Intent.ACTION_DELETE,uri); startActivity(it); //uninstallapk UriuninstallUri=Uri.fromParts( "package" , "xxx" , null ); returnIt= new Intent(Intent.ACTION_DELETE,uninstallUri); //installapk UriinstallUri=Uri.fromParts( "package" , "xxx" , null ); returnIt= new Intent(Intent.ACTION_PACKAGE_ADDED,installUri); //playaudio UriplayUri=Uri.parse( "file:///sdcard/download/everything.mp3" ); returnIt= new Intent(Intent.ACTION_VIEW,playUri); //sendextra Intentit= new Intent(Intent.ACTION_SEND); it.putExtra(Intent.EXTRA_SUBJECT, "Theemailsubjecttext" ); it.putExtra(Intent.EXTRA_STREAM, "file:///sdcard/eoe.mp3" ); sendIntent.setType( "audio/mp3" ); startActivity(Intent.createChooser(it, "ChooseEmailClient" )); //search Uriuri=Uri.parse( "market://search?q=pname:pkg_name" ); Intentit= new Intent(Intent.ACTION_VIEW,uri); startActivity(it); //wherepkg_nameisthefullpackagepathforanapplication //showprogramdetailpage Uriuri=Uri.parse( "market://details?id=app_id" ); Intentit= new Intent(Intent.ACTION_VIEW,uri); startActivity(it); //whereapp_idistheapplicationID,findtheID //byclickingonyourapplicationonMarkethome //page,andnoticetheIDfromtheaddressbar //searchgoogle Intentintent= new Intent(); intent.setAction(Intent.ACTION_WEB_SEARCH); intent.putExtra(SearchManager.QUERY, "searchString" ) startActivity(intent); 本文转自 glblong 51CTO博客,原文链接:http://blog.51cto.com/glblong/1613249,如需转载请自行联系原作者

资源下载

更多资源
腾讯云软件源

腾讯云软件源

为解决软件依赖安装时官方源访问速度慢的问题,腾讯云为一些软件搭建了缓存服务。您可以通过使用腾讯云软件源站来提升依赖包的安装速度。为了方便用户自由搭建服务架构,目前腾讯云软件源站支持公网访问和内网访问。

Nacos

Nacos

Nacos /nɑ:kəʊs/ 是 Dynamic Naming and Configuration Service 的首字母简称,一个易于构建 AI Agent 应用的动态服务发现、配置管理和AI智能体管理平台。Nacos 致力于帮助您发现、配置和管理微服务及AI智能体应用。Nacos 提供了一组简单易用的特性集,帮助您快速实现动态服务发现、服务配置、服务元数据、流量管理。Nacos 帮助您更敏捷和容易地构建、交付和管理微服务平台。

Spring

Spring

Spring框架(Spring Framework)是由Rod Johnson于2002年提出的开源Java企业级应用框架,旨在通过使用JavaBean替代传统EJB实现方式降低企业级编程开发的复杂性。该框架基于简单性、可测试性和松耦合性设计理念,提供核心容器、应用上下文、数据访问集成等模块,支持整合Hibernate、Struts等第三方框架,其适用范围不仅限于服务器端开发,绝大多数Java应用均可从中受益。

Rocky Linux

Rocky Linux

Rocky Linux(中文名:洛基)是由Gregory Kurtzer于2020年12月发起的企业级Linux发行版,作为CentOS稳定版停止维护后与RHEL(Red Hat Enterprise Linux)完全兼容的开源替代方案,由社区拥有并管理,支持x86_64、aarch64等架构。其通过重新编译RHEL源代码提供长期稳定性,采用模块化包装和SELinux安全架构,默认包含GNOME桌面环境及XFS文件系统,支持十年生命周期更新。

用户登录
用户注册