MacOS使用Prolog命令行工具

1、看一下SWI-Prolog的安装说明,发现命令行工具在下面的路径

/Applications/SWI-Prolog.app/Contents/MacOS

2、修改PATH变量,添加SWI-Prolog命令行工具在下面的路径

#查看命令行工具
cd /Applications/SWI-Prolog.app/Contents/MacOS
ls

#查看PATH变量
echo "$PATH"

#修改PATH变量
vi $HOME/.bash_profile
#增加一行
export PATH=${PATH}:/Applications/SWI-Prolog.app/Contents/MacOS

3、重启命令行

#查看PATH变量
echo "$PATH"

#测试一下
swipl hello.pl 

MongoDB查询使用Codec的简单示例(java)

1、数据准备

db.person.insert({"name":"neo","age":"26","sex":"male"})
db.person.insert({"name":"joe","age":"28","sex":"male"})

2、使用Codec

class Person  
{
       public ObjectId _id;
       public double Age;  
       public String Name;  
       public String Sex;  
       
       public Person(ObjectId _id, String Name, double Age, String Sex)
       {
    	   this._id=_id;
    	   this.Name=Name;
    	   this.Age=Age;
    	   this.Sex=Sex;
       }
}

class PersonCodec implements Codec<Person> 
{
    private final CodecRegistry codecRegistry;

    public PersonCodec(final CodecRegistry codecRegistry) {
        this.codecRegistry = codecRegistry;
    }
    
    @Override
    public void encode(BsonWriter writer, Person t, EncoderContext ec) {
    	 writer.writeStartDocument();
         writer.writeName("_id");
         writer.writeObjectId(t._id);
         writer.writeName("name");
         writer.writeString(t.Name);
         writer.writeName("age");
         writer.writeDouble(t.Age);
         writer.writeName("sex");
         writer.writeString(t.Sex);
         writer.writeEndDocument();
    }

    @Override
    public Class<Person> getEncoderClass() {
        return Person.class;
    }

    @Override
    public Person decode(BsonReader reader, DecoderContext dc) 
    {
        reader.readStartDocument();
        reader.readName();
        ObjectId _id = reader.readObjectId();
        reader.readName();
        String name = reader.readString();
        reader.readName();
        double age = reader.readDouble();
        reader.readName();
        String sex =reader.readString();
        reader.readEndDocument();
        return new Person(_id,name,age,sex);
    }
}

class PersonCodecProvider implements CodecProvider 
{
    @Override
    public <T> Codec<T> get(Class<T> type, CodecRegistry cr) 
    {
        if (type == Person.class) 
        {
            return (Codec<T>) new PersonCodec(cr);
        }
        return null;
    }
}

public class CodecTest 
{
	private static void testCodec()
	{
		String[] hosts = {"127.0.0.1"};
		int port = 27017;
		String user = null;
		String password = null;
		String database = "test";
		CodecRegistry codecRegistry = CodecRegistries.fromRegistries(
	            CodecRegistries.fromProviders(new PersonCodecProvider()),
	            MongoClient.getDefaultCodecRegistry());  
		
		MongoClient mongoClient = getConnection(hosts,port,user,password,database,codecRegistry);
		MongoDatabase db = mongoClient.getDatabase("test");
		MongoCollection<Person> collection = db.getCollection("person",Person.class);
		FindIterable<Person> iterable = collection.find();
		MongoCursor<Person> cursor = iterable.iterator();
		while (cursor.hasNext())
		{
        		Person p  = cursor.next();
        		System.out.println("personName: " + p.Name);
		}
	}
	
	private static MongoClient getConnection(String[] hosts, int port, String user, String password, String database, CodecRegistry codecRegistry)
	{
	        MongoClientOptions mongoClientOptions = new MongoClientOptions.Builder()
	        .connectionsPerHost(100)
	        .threadsAllowedToBlockForConnectionMultiplier(5)
	        .maxWaitTime(1000 * 60 * 2)
	        .connectTimeout(1000 * 10)
	        .socketTimeout(0)
	        .socketKeepAlive(false)
	        .readPreference(ReadPreference.primary())
	        .writeConcern(WriteConcern.ACKNOWLEDGED)
	        .codecRegistry(codecRegistry)
	        .build();
		
		List<ServerAddress> mongoAddresses = new ArrayList<ServerAddress>();
		for (String host : hosts) {
		    mongoAddresses.add(new ServerAddress(host, port));
		}
		
		List<MongoCredential> mongoCredentials = null;
		if (user != null && !user.isEmpty() && password != null && !password.isEmpty()) {
		    mongoCredentials = new ArrayList<MongoCredential>();
		    mongoCredentials.add(MongoCredential.createMongoCRCredential(user, database, password.toCharArray()));
		}
		
		if(mongoCredentials==null)
		{
			return new MongoClient(mongoAddresses, mongoClientOptions);
		}
		else
		{
			return new MongoClient(mongoAddresses, mongoCredentials, mongoClientOptions);
		}
	}
}

MongoDB的MapReduce简单示例(java)

1、数据准备

db.sell.insert({"price":8.0,"amount":500.0,"status":"a"})
db.sell.insert({"price":8.0,"amount":450.0,"status":"a"})
db.sell.insert({"price":8.0,"amount":400.0,"status":"a"})
db.sell.insert({"price":9.0,"amount":350.0,"status":"a"})
db.sell.insert({"price":9.0,"amount":300.0,"status":"a"})
db.sell.insert({"price":9.0,"amount":250.0,"status":"a"})
db.sell.insert({"price":9.0,"amount":200.0,"status":"a"})
db.sell.insert({"price":10.0,"amount":150.0,"status":"d"})
db.sell.insert({"price":10.0,"amount":100.0,"status":"d"})
db.sell.insert({"price":10.0,"amount":50.0,"status":"d"})
db.sell.insert({"price":10.0,"amount":0.0,"status":"d"})

2、MapReduce

	private static void testMapReduce3x()
	{
		MongoClient mongoClient = new MongoClient("localhost", 27017);
		MongoDatabase db = mongoClient.getDatabase("test");
		MongoCollection collection = db.getCollection("sell");

		String map = "function(){emit(this.price,this.amount);}";
		String reduce = "function(key, values){return Array.sum(values)}";

		MapReduceIterable out = collection.mapReduce(map, reduce);
		MongoCursor cursor = out.iterator();
		while (cursor.hasNext()) 
		{
			System.out.println(cursor.next());
		}
	}
	
	private static void testMapReduce2x()
	{
		MongoClient mongoClient = new MongoClient("localhost", 27017);
		MongoDatabase db = mongoClient.getDatabase("test");
		BasicDBObject query=new BasicDBObject("status","a");
		DBCollection dbcollection = mongoClient.getDB("test").getCollection("sell");
		
		String map = "function(){emit(this.price,this.amount);}";
		String reduce = "function(key, values){return Array.sum(values)}";
		
		MapReduceCommand cmd = new MapReduceCommand(dbcollection, map, reduce,
		    "outputCollection", MapReduceCommand.OutputType.INLINE, query);
		
		MapReduceOutput out2 = dbcollection.mapReduce(cmd);
		for (DBObject o : out2.results()) 
		{
		   System.out.println(o.toString());
		}
	}

MongoDB入门之增删改查(Java)

测试代码,请重构

	//枚举数据库
	private static void listDB()
	{
		MongoClient mongoClient = new MongoClient("localhost", 27017);
	    for (String dbName : mongoClient.listDatabaseNames())
	    {
	    	System.out.println("dbName: " + dbName);
	    }
	}
	
	//枚举collection
	private static void listCollection()
	{
		MongoClient mongoClient = new MongoClient("localhost", 27017);
		MongoDatabase db = mongoClient.getDatabase("test");
	    for (String collectionName : db.listCollectionNames())
	    {
	    	System.out.println("collectionName: " + collectionName);
	    }
	}

	//查询全部数据
	private static void testQueryAll()
	{
		MongoClient mongoClient = new MongoClient("localhost", 27017);
		MongoDatabase db = mongoClient.getDatabase("test");
		MongoCollection collection = db.getCollection("person");
		BasicDBObject query = new BasicDBObject();
		FindIterable iterable = collection.find(query);
		MongoCursor cursor = iterable.iterator();
		while (cursor.hasNext()) 
		{
		   org.bson.Document person = (org.bson.Document)cursor.next();
		   System.out.println(person.get("name"));
		   System.out.println(person.toString());
		}
		cursor.close();
	}

	//按条件查询数据
	private static void testQuery()
	{
		MongoClient mongoClient = new MongoClient("localhost", 27017);
		MongoDatabase db = mongoClient.getDatabase("test");
		MongoCollection collection = db.getCollection("person");
		
		BasicDBObject query = new BasicDBObject("name","Joe");
		FindIterable iterable = collection.find(query);
		MongoCursor cursor = iterable.iterator();
		while (cursor.hasNext()) 
		{
		   org.bson.Document person = (org.bson.Document)cursor.next();
		   System.out.println(person.get("name"));
		   System.out.println(person.toString());
		}
		cursor.close();
	}

	//插入
	private static void testInsert() 
	{
		MongoClient mongoClient = new MongoClient("localhost", 27017);
		MongoDatabase db = mongoClient.getDatabase("test");
		MongoCollection collection = db.getCollection("person");
		
		Document doc = new Document();
		doc.put("name", "tuzi");
		doc.put("age", 27);
		doc.put("sex", "Female");
		collection.insertOne(doc);
	}

	//删除
	private static void testDelete() {
		MongoClient mongoClient = new MongoClient("localhost", 27017);
		MongoDatabase db = mongoClient.getDatabase("test");
		MongoCollection collection = db.getCollection("person");
		BasicDBObject query = new BasicDBObject("name", "tuziki");
		collection.deleteMany(query);
	}

	//更新
	private static void testUpdate() {
		MongoClient mongoClient = new MongoClient("localhost", 27017);
		MongoDatabase db = mongoClient.getDatabase("test");
		MongoCollection collection = db.getCollection("person");
		
		BasicDBObject query = new BasicDBObject("name", "tuzi");
		
		BasicDBObject newDocument = new BasicDBObject();
		newDocument.put("name", "tuziki");
		
		BasicDBObject updateObj = new BasicDBObject();
		updateObj.put("$set", newDocument);
		
		collection.updateMany(query, updateObj);
	}

AndroidStudio配置NDK环境

1、新建工程,在工程根目录找到local.properties文件

sdk.dir=C\:/Languages/Android/android-sdk-windows
ndk.dir=C\:/Languages/Android/android-ndk-r10

2、在app\build.gradle文件中的defaultConfig段内增加

       ndk {
            moduleName "yourModuleName"
       }

2、在工程的app\src\main目录下,新增jni文件夹,将你的ndk工程拷进去

3、在app\src\main\java目录下,将你的java文件拷贝进去

4、如果你的ndk工程用到了其他so文件,在app目录下,新建jniLibs文件夹,将so文件拷贝进去

jniLibs\armeabi\xxx.so
jniLibs\armeabi-v7a\xxx.so
....

5、自定义文件夹路径。编辑app\build.gradle文件下的android段

    //自定义引用库路径
    sourceSets.main {
        jniLibs.srcDir 'src/main/cpplibs'
    }

    //自定义源码路径
    sourceSets.main {
        jni.srcDirs 'src/main/cpp'
    }

6、现在就可以用啦

7、另一种方式就是,先把so文件用命令行生成好,然后,android项目中直接引用so文件就好了

PS:
如果你的ndk项目只有一个c文件,用早期的AndroidStudio编译会报错:

make.exe: *** No rule to make target
......

Execution failed for task ':XXXXXX:compileXXXXXXDebugNdk'.
.......

这样的话,在你的c文件目录下,随便建立一个空的c文件,重新编译就好了,好挫。

Android配置NDK环境

准备工作
1、下载NDK
2、直接运行,会解压到当前文件夹
3、剪切到你喜欢的文件夹

第一个项目
1、写一个调用JNI的Java类

package com.neohope.android.jni;

public class JniFunc {
    private native int  addNative(int a, int b);

    static {
        System.loadLibrary("jnifunc");
    }

    public int add(int a, int b)
    {
        return addNative(a,b);
    }
}

2、用你喜欢的方式,编译为class文件

3、用jdk的javah工具生成头文件

#在class文件的顶层路径,比如这个例子,就在com这个文件夹相同目录下
javah com.neohope.android.jni.JniFunc

会输出文件“com_neohope_android_jni_JniFunc.h”:

/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class com_neohope_android_jni_JniFunc */

#ifndef _Included_com_neohope_android_jni_JniFunc
#define _Included_com_neohope_android_jni_JniFunc
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     com_neohope_android_jni_JniFunc
 * Method:    addNative
 * Signature: (II)I
 */
JNIEXPORT jint JNICALL Java_com_neohope_android_jni_JniFunc_addNative
  (JNIEnv *, jobject, jint, jint);

#ifdef __cplusplus
}
#endif
#endif

4、编写“com_neohope_android_jni_JniFunc.c”

#include <jni.h>
#include "com_neohope_android_jni_JniFunc.h"

JNIEXPORT jint JNICALL Java_com_neohope_android_jni_JniFunc_addNative
  (JNIEnv *evn, jobject obj, jint a, jint b)
{
    return a+b;
}

5、编写Android.mk及Application.mk

APP_ABI := all
LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)

LOCAL_MODULE    := jnifunc
LOCAL_SRC_FILES := com_neohope_android_jni_JniFunc.c \

LOCAL_C_INCLUDES += com_neohope_android_jni_JniFunc.h

include $(BUILD_SHARED_LIBRARY)

6、编译

SET NDK_HOME="C:\Languages\Android\android-ndk-r10d"

SET PATH=%NDK_HOME%;%PATH%

CMD

REM ndk-build

Andoid百度地图显示方向

    private BaiduMap mBaiduMap = null;
    private MapView mMapView = null;
    private LocationClient mLocClient = null;
    private MyLocationConfiguration.LocationMode mCurrentMode;
    private Boolean isFirstLoc = true;
    private BitmapDescriptor mCurrentMarker=null;

    private float[] accelerometerValues=new float[3];
    private float[] magneticFieldValues=new float[3];
    private float[] values=new float[3];
    private float[] rotate=new float[9];
    private float[] degree=new float[3];

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SDKInitializer.initialize(getApplicationContext());
        setContentView(R.layout.activity_main);

        SensorManager sm = (SensorManager) getApplicationContext().getSystemService(Context.SENSOR_SERVICE);
        SensorEventListener sensorEventListener = new SensorEventListener() {
            @Override
            public void onSensorChanged(SensorEvent event) {
                if(event.sensor.getType()==Sensor.TYPE_ACCELEROMETER){
                    accelerometerValues=event.values;
                }
                if(event.sensor.getType()==Sensor.TYPE_MAGNETIC_FIELD){
                    magneticFieldValues=event.values;
                }
                else
                {
                    return;
                }

                SensorManager.getRotationMatrix(rotate, null, accelerometerValues, magneticFieldValues);
                SensorManager.getOrientation(rotate, values);

                //rotate
                degree[0] = values[0]/3.1415926f*180;
                //up down
                degree[1] = values[1]/3.1415926f*180;
                //left right
                degree[2] = values[2]/3.1415926f*180;
            }

            @Override
            public void onAccuracyChanged(Sensor sensor, int accuracy) {
            }
        };

        sm.registerListener(sensorEventListener,sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),SensorManager.SENSOR_DELAY_NORMAL);
        sm.registerListener(sensorEventListener,sm.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD),SensorManager.SENSOR_DELAY_NORMAL);

        // init baiduMap
        mMapView = (MapView) findViewById(R.id.dbmapView);
        mBaiduMap = mMapView.getMap();

        // set parameters
        mCurrentMode = MyLocationConfiguration.LocationMode.FOLLOWING;
        mCurrentMarker=null;
        mBaiduMap.setMyLocationConfigeration(new MyLocationConfiguration(mCurrentMode, true, mCurrentMarker));

        // allow loaction
        mBaiduMap.setMyLocationEnabled(true);
        mLocClient = new LocationClient(this);
        mLocClient.registerLocationListener(new MyLocationListenner());
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true);
        option.setCoorType("bd09ll");
        option.setScanSpan(1000);
        mLocClient.setLocOption(option);
        mLocClient.start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mMapView.onDestroy();
    }

    public class MyLocationListenner implements BDLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            if (location == null || mMapView == null)
                return;

            MyLocationData locData = new MyLocationData.Builder()
                    .accuracy(location.getRadius())
                    .direction(degree[0])
                    .latitude(location.getLatitude())
                    .longitude(location.getLongitude()).build();
            mBaiduMap.setMyLocationData(locData);

            if (isFirstLoc) {
                isFirstLoc = false;
                LatLng ll = new LatLng(location.getLatitude(),
                        location.getLongitude());
                MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(ll);
                mBaiduMap.animateMapStatus(u);
            }
        }
    }

Apple In House 发布详解(七牛升级服务器搭建)

大家都懂的,很多云存储比如Dropbox国内根本访问不了,某度的规则又不适合做这个功能。

那就用七牛吧。

1、到七牛注册账号
http://www.qiniu.com/

2、上传身份证,进行认证
谁让你想省钱呢

3、认证通过后,新建一个空间,设置开通HTTPS,设置自己的域名
假设你的访问地址为https://dn-xxxxxx.qbox.me/

4、将html文件及plist中文件的绝对路径全部修改为https://dn-xxxxxx.qbox.me/xxxxxx

5、上传文件,将plist的mime type修改为text/xml

6、搞定

还是花钱买的证书好用啊。

Apple In House 发布详解(HTTPS证书生成)

1、如果是在Windows下面,用openssl就可以搞定了
1.1首先生成pem格式的CA证书,并导出为crt格式

set OPENSSL_CONF=%OPENSSL_HOME%\bin\openssl.cfg
openssl genrsa 1024 > NMyCA1024.key
openssl req -new -x509 -nodes -key NMyCA1024.key -days 1095 -subj "/C=CN/ST=ShangHai/L=ShangHai/O=NEOHOPE/OU=Development/CN=NMyCA1024" > NMyCA1024.pem

1.2将CA证书导出为der格式

openssl x509 -outform der -in NMyCA1024.pem -out NMyCA1024.der

1.3生成网站私钥及证书签名请求

set OPENSSL_CONF=%OPENSSL_HOME%\bin\openssl.cfg
openssl genrsa 1024 > server.key
openssl req -new -key server.key -subj "/C=CN/ST=ShangHai/L=ShangHai/O=NEOHOPE/OU=Development/CN=192.168.130.50" > server.csr

1.4用CA证书处理证书签名请求,生成CA授权的证书

openssl x509 -req -in server.csr -CA NMyCA1024.pem -CAkey NMyCA1024.key -CAcreateserial -days 365 > serversigned.crt

1.5将NMyCA1024.der、server.key、serversigned.crt拷给证书使用者

1.6一定要保管好NMyCA1024.key及NMyCA1024.pem,不要弄丢,更不要拷给别人

2、如果是在MAC下面,有一个工具就能搞定EasyCert

./EasyCert -cn NMyCA -h 192.168.130.50

但同样的,要保护好CA的私钥。

Apple In House 发布详解(内网升级服务器搭建)

要内网升级的话,需要搭建内网升级HTTPS服务器。

以APACHE为例:

1、下载支持SSL的APACHE服务程序,如果你已经有APACHE服务,可以查找mod_ssl.so,如果没有请重新下载

2、打开HTTPS支持,httpd.conf文件中,去掉下面两行的注释

LoadModule ssl_module modules/mod_ssl.so
Include conf/extra/httpd-ssl.conf

修改httpd-ssl.conf中证书信息

SSLCertificateFile "C:/ProgramerTools/WebServer/Apache2.2/conf/server.crt"
SSLCertificateKeyFile "C:/ProgramerTools/WebServer/Apache2.2/conf/server.key"

3、将httpd.conf及httpd-ssl.conf路径信息调整为正确路径

4、此时HTTP与HTTPS都可以访问APACHE服务了

5、构建升级网站

5.1、准备资源文件
57×57图标,512×512图标,in house发布签名的ipa文件,CA根证书

5.2、准备plist文件

<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"
"http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
   <!-- array of downloads. -->
   <key>items</key>
   <array>
       <dict>
           <!-- an array of assets to download -->
           <key>assets</key>
           <array>
               <!-- software-package: the ipa to install. -->
               <dict>
                   <!-- required.  the asset kind. -->
                   <key>kind</key>
                   <string>software-package</string>
                   <!-- required.  the URL of the file to download. -->
                   <key>url</key>
                   <string>https://192.168.130.50/XXXXX.ipa</string>
               </dict>
               <!-- display-image: the 57*57 icon to display during download. -->
               <dict>
                   <key>kind</key>
                   <string>display-image</string>
                   <key>url</key>
                   <string>https://192.168.130.50/XXXXX_57.png</string>
               </dict>
               <!-- full-size-image: the large 512x512 icon used by iTunes. -->
               <dict>
                   <key>kind</key>
                   <string>full-size-image</string>
                   <key>url</key>
                   <string>https://192.168.130.50/XXXXX_512.png</string>
               </dict>
           </array>
           <key>metadata</key>
           <dict>
               <!-- required -->
               <key>bundle-identifier</key>
               <string>程序的app id</string>
               <!-- optional (software only) -->
               <key>bundle-version</key>
               <string>程序的版本</string>
               <!-- required.  the download kind. -->
               <key>kind</key>
               <string>software</string>
               <!-- optional. displayed during download; -->
               <!-- typically company name -->
               <key>subtitle</key>
               <string>厂商名称</string>
               <!-- required.  the title to display during the download. -->
               <key>title</key>
               <string>软件名称</string>
           </dict>
       </dict>
   </array>
</dict>
</plist>

5.3、准备.htaccess文件,与plist文件放在一起

AddType text/xml .plist
AddType application/octet-stream .ipa

修改httpd.conf文件,让.htaccess文件生效

#升级文件所在的目录
AllowOverride FileInfo

5.4、准备网页

<html>
	<body>
		<a href="https://192.168.130.46/myCA.cer">Install CA Cert</a>
		</br>
                 <a href="itms-services://?action=download-manifest&amp;url=https://192.168.130.50/XXXXX.plist">Install My App over the air </a>
	</body>
</html>

6、使用
6.1、HTTPS访问网页,下载CA证书,并添加到IOS的信任列表
6.2、点击安装App,然后就开始自动安装啦

7、自动升级
请Google或github一下iVersion