Thursday, November 12, 2015

Code: Miscellaneous

1.[Python]查找特定后缀名称文件并返回完整路径;
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
#Reference
#https://stackoverflow.com/questions/3964681/find-all-files-in-directory-with-extension-txt-with-python/3964691#3964691
def GetFileListExt(SouDir, FlagStr):
    import glob, os
    FileList=[]
    os.chdir(SouDir)
    filter_str='*'+FlagStr
    #print filter_str
    for filepath in glob.glob(filter_str):
        FileList.append(os.path.join(SouDir, filepath))
    return FileList
2.[Arcpy]若参数是Optional,在不确定情况下可用"#"表示;
3.[Arcpy]获取shapefile文件的全部属性名称;
1
2
3
4
5
6
# Reference
# http://gis.stackexchange.com/questions/140653/in-arcpy-how-to-call-specific-columns-of-attribute-table
fieldlist=arcpy.ListFields(filepath)
    print filepath
    for field in fieldlist:
        print field.name
1
2
3
% Reference
% http://blog.sciencenet.cn/blog-1148346-842075.html
geotiffwrite('m2.tif', image, geo, 'GeoKeyDirectoryTag', info.GeoTIFFTags.GeoKeyDirectoryTag);
7.[IDL]file_search函数使用方法总结:1, 2;
1
set(gcf,'outerposition',get(0,'screensize'));
10.[Matlab]输出图片的强大Toolbox,用法说明参考在线文档:export_fig;以如下代码保存图片,避免意外:
1
export_fig('exportfig_painters.png', '-png', '-painters', '-r300');
当图片包含中文字符时请参考此段代码:
1
export_fig([name,'.png'], '-png', '-r400','-q300');
11.[Matlab]栅格数据线性斜率参考代码;
12.[Matlab]若干.mat文件中的变量逐一以变量名另存为.xlsx文件:mat2xls.m;
13.[Python]获取目录下的包含一定字符的文件路径:(不能肯定指向后缀名.extension)
 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
# -*- coding: utf-8 -*-  
#~ #----------------------------------------------------------------------  
#~module:wlab  
#~Filename:wgetfilelist.py  
#~Function :  
#~def IsSubString(SubStrList,Str)  
#~def GetFileList(FindPath,FlagStr=[]):  
#~功能:读取指定目录下特定类型的文件名列表  
#~Data: 2013-08-08,星期四  
#~Author:吴徐平  
#~Email:wxp07@qq.com  
#~http://blog.csdn.net/rumswell/article/details/9818001
#~ #----------------------------------------------------------------------  
#~ #----------------------------------------------------------------------  
def IsSubString(SubStrList,Str):  
    ''''' 
    #判断字符串Str是否包含序列SubStrList中的每一个子字符串 
    #>>>SubStrList=['F','EMS','txt'] 
    #>>>Str='F06925EMS91.txt' 
    #>>>IsSubString(SubStrList,Str)#return True (or False) 
    '''  
    flag=True  
    for substr in SubStrList:  
        if not(substr in Str):  
            flag=False  
  
    return flag  
#~ #----------------------------------------------------------------------  
def GetFileList(FindPath,FlagStr=[]):  
    ''''' 
    #获取目录中指定的文件名 
    #>>>FlagStr=['F','EMS','txt'] #要求文件名称中包含这些字符 
    #>>>FileList=GetFileList(FindPath,FlagStr) # 
    '''  
    import os  
    FileList=[]  
    FileNames=os.listdir(FindPath)  
    if (len(FileNames)>0):  
       for fn in FileNames:  
           if (len(FlagStr)>0):  
               #返回指定类型的文件名  
               if (IsSubString(FlagStr,fn)):  
                   fullfilename=os.path.join(FindPath,fn)  
                   FileList.append(fullfilename)  
           else:  
               #默认直接返回所有文件名  
               fullfilename=os.path.join(FindPath,fn)  
               FileList.append(fullfilename)  
  
    #对文件名排序  
    if (len(FileList)>0):  
        FileList.sort()  
  
    return FileList  
15.[Software]ANUSPLIN V4.36;
17.[Python]Access Xls data by row:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#~#------------------------------------------------------------------
def GetXlsRows(xlspath, indexes, records, offset):
    import xlrd
    workbook=xlrd.open_workbook(xlspath)
    # loop for every single sheet
    import math
    for sheetno in indexes:
        #print sheetno
        try:
            worksheet=workbook.sheet_by_index(sheetno)
            records=GetRecords(worksheet, offset, records)
        except:
            continue
    return records
#~#------------------------------------------------------------------
def GetRecords(worksheet, offset, records):
    for i, row in enumerate(range(worksheet.nrows)):
        if i <offset:
            continue
        r=[]    
        for j, col in enumerate(range(worksheet.ncols)):
            r.append(worksheet.cell_value(i, j))
        records.append(r)
    return records
  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
% Created by LI Xu
% Version 1.0
% November 23, 2015

% Description:
% Check out the current Matlab lincense Info

% If you have any question about this code,
% please do not hesitate to contact me via E-mail: 
% jeremy456@163.com

% Blog:
% http://blog.sciencenet.cn/u/lixujeremy
% http://lixuworld.blogspot.com/

% Reference
% http://stackoverflow.com/questions/2060382/how-would-one-check-for-installed-matlab-toolboxes-in-a-script-function

clear;
clc;

% Display toolbox version info
ver
disp('**************************************************');
disp('Display a list of licenses currently being used.');
license('inuse')
disp('**************************************************');
disp('Check out a license for all the available toolboxes.');
featureStr = {'Aerospace_Blockset'; ...
              'Aerospace_Toolbox'; ...
              'Bioinformatics_Toolbox'; ...
              'Communication_Blocks'; ...
              'Communication_Toolbox'; ...
              'Compiler'; ...
              'Control_Toolbox'; ...
              'Curve_Fitting_Toolbox'; ...
              'Data_Acq_Toolbox'; ...
              'Database_Toolbox'; ...
              'Datafeed_Toolbox'; ...
              'Dial_and_Gauge_Blocks'; ...
              'Distrib_Computing_Toolbox'; ...
              'Econometrics_Toolbox'; ...
              'EDA_Simulator_Link_DS'; ...
              'Embedded_Target_c166'; ...
              'Embedded_Target_c2000'; ...
              'Embedded_Target_c6000'; ...
              'Embedded_Target_MPC555'; ...
              'Excel_Link'; ...
              'Filter_Design_HDL_Coder'; ...
              'Filter_Design_Toolbox'; ...
              'Fin_Derivatives_Toolbox'; ...
              'Financial_Toolbox'; ...
              'Fixed_Income_Toolbox'; ...
              'Fixed_Point_Toolbox'; ...
              'Fixed-Point_Blocks'; ...
              'Fuzzy_Toolbox'; ...
              'GADS_Toolbox'; ...
              'IDE_Link_MU'; ...
              'Identification_Toolbox'; ...
              'Image_Acquisition_Toolbox'; ...
              'Image_Toolbox'; ...
              'Instr_Control_Toolbox'; ...
              'Link_for_Incisive'; ...
              'Link_for_ModelSim'; ...
              'Link_for_Tasking'; ...
              'Link_for_VisualDSP'; ...
              'MAP_Toolbox'; ...
              'MATLAB'; ...
              'MATLAB_Builder_for_dot_Net'; ...
              'MATLAB_Builder_for_Java'; ...
              'MATLAB_Distrib_Comp_Engine'; ...
              'MATLAB_Excel_Builder'; ...
              'MATLAB_Link_for_CCS'; ...
              'MATLAB_Report_Gen'; ...
              'MBC_Toolbox'; ...
              'MPC_Toolbox'; ...
              'NCD_Toolbox'; ...
              'Neural_Network_Toolbox'; ...
              'OPC_Toolbox'; ...
              'Optimization_Toolbox'; ...
              'PDE_Toolbox'; ...
              'Power_System_Blocks'; ...
              'Real-Time_Win_Target'; ...
              'Real-Time_Workshop'; ...
              'RF_Blockset'; ...
              'RF_Toolbox'; ...
              'Robust_Toolbox'; ...
              'RTW_Embedded_Coder'; ...
              'Signal_Blocks'; ...
              'Signal_Toolbox'; ...
              'SimBiology'; ...
              'SimDriveline'; ...
              'SimElectronics'; ...
              'SimEvents'; ...
              'SimHydraulics'; ...
              'SimMechanics'; ...
              'Simscape'; ...
              'SIMULINK'; ...
              'Simulink_Control_Design'; ...
              'Simulink_Design_Verifier'; ...
              'Simulink_HDL_Coder'; ...
              'Simulink_Param_Estimation'; ...
              'SIMULINK_Report_Gen'; ...
              'SL_Verification_Validation'; ...
              'Spline_Toolbox'; ...
              'Stateflow'; ...
              'Stateflow_Coder'; ...
              'Statistics_Toolbox'; ...
              'Symbolic_Toolbox'; ...
              'SystemTest'; ...
              'Video_and_Image_Blockset'; ...
              'Virtual_Reality_Toolbox'; ...
              'Wavelet_Toolbox'; ...
              'XPC_Embedded_Option'; ...
              'XPC_Target'};
index = cellfun(@(f) license('test',f),featureStr);
availableFeatures = featureStr(logical(index));
index = cellfun(@(f) license('checkout',f),availableFeatures);
checkedOutFeatures = availableFeatures(logical(index))
fprintf('Total: %d.\n', length(checkedOutFeatures));
disp('**************************************************');
19.[python]文件名称包含特定序列字符:
1
2
3
4
5
6
7
8
def GetFileSubStr(SouDir, flagstr):
    import os, glob
    allfiles=os.listdir(SouDir)
    filepath=[]
    for file in allfiles:
        if flagstr in file:
            filepath=os.path.join(SouDir, file)
            return filepath
20.[Matlab] Change language for Matlab desktop
21.[Matlab]函数Text指定中文字体须以其英文名称为准,如黑体是SimHei,此时才为有效:
1
input=['\fontname{Arial}(', char(96+ii), ') \fontname{SimHei}', names{ii}];
  • 黑体:SimHei
  • 宋体:SimSun
  • 新宋体:NSimSun
  • 仿宋:FangSong
  • 楷体:KaiTi
  • 仿宋_GB2312:FangSong_GB2312
  • 楷体_GB2312:KaiTi_GB2312
  • 微软雅黑体:Microsoft YaHei
23.[Matlab]Plot添加字符
 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
% Created by LI Xu
% Version 1.0
% November 27, 2015

% Description:
% Insert Text on the plot figure

% If you have any question about this code,
% please do not hesitate to contact me via E-mail: 
% jeremy456@163.com

% Blog:
% http://blog.sciencenet.cn/u/lixujeremy
% http://lixuworld.blogspot.com/

% Example
% instr={str1, str2, str3};
% instratts.font='Arial';
% instratts.xsclae=0.2;
% instratts.yscale=0.3;
% instratts.fontsize=12;
% instratts.interval=0.1;
% PlotAddText(gca, instr, instratts);

function PlotAddText(handle, instr, instratts)
    % Get xlim ylim
    xlim=get(handle, 'xlim');
    ylim=get(handle, 'ylim');
    
    fontsize=instratts.fontsize;
    if fontsize<1
        fontsize=(ylim(2)-ylim(1))*fontsize;
    end
    
    % Loop
    for ii=1:length(instr)
        strVal=instr{ii};
        x=(xlim(2)-xlim(1))*instratts.xscale+xlim(1);
        y=(ylim(2)-ylim(1))*instratts.yscale+ylim(1);
        y=y-(ylim(2)-ylim(1))*instratts.interval*(ii-1);
        text(x, y, strVal, 'fontname', instratts.font, ...
            'fontsize', fontsize);
    end
end

 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
% Created by LI Xu
% Version 1.0
% November 27, 2015

% Description:
% Insert Text on the plot figure

% If you have any question about this code,
% please do not hesitate to contact me via E-mail: 
% jeremy456@163.com

% Blog:
% http://blog.sciencenet.cn/u/lixujeremy
% http://lixuworld.blogspot.com/

% Modification
% Add color property
% Version 1.1
% May 11, 2015

% Example
% instr={str1, str2, str3};
% instratts.font='Arial';
% instratts.xscale=0.2;
% instratts.yscale=0.3;
% instratts.fontsize=12;
% instratts.interval=0.1;
% instratts.color=[0, 0, 0];
% PlotAddText(gca, instr, instratts);

function PlotAddText(handle, instr, instratts)
    % Get xlim ylim
    xlim=get(handle, 'xlim');
    ylim=get(handle, 'ylim');
    
    fontsize=instratts.fontsize;
    if fontsize<1
        fontsize=(ylim(2)-ylim(1))*fontsize;
    end
    
    % Loop
    for ii=1:length(instr)
        strVal=instr{ii};
        x=(xlim(2)-xlim(1))*instratts.xscale+xlim(1);
        y=(ylim(2)-ylim(1))*instratts.yscale+ylim(1);
        y=y-(ylim(2)-ylim(1))*instratts.interval*(ii-1);
        text(x, y, strVal, 'fontname', instratts.font, ...
            'fontsize', fontsize, 'color', instratts.color./255);
    end
end
24.[Matlab]插入°C,此时Matlab当前编码类型应是'Windows-1252'
25.[Matlab]Matlab显示点乘(dot product)符号,按照Tex语言
1
2
data = double(py.array.array('d',py.numpy.nditer(x))); %d is for double, see link below on types
data = reshape(data,[4 4])'; %Could incorporate x.shape here ...
28.[Matlab]返回指定目录下特定文件的一定位置的数值(DN)
 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
% Created by LI Xu
% Version 1.0
% January 26, 2016

% Description
% Retrieve the DNs of multiple files

% If you have any question about this code,
% please do not hesitate to contact me via E-mail: 
% jeremy456@163.com

% Blog:
% http://blog.sciencenet.cn/u/lixujeremy
% http://lixuworld.blogspot.com/

function data=RetDNs(SouDir, files, index)
    data=[];
    % Loop
    for ii=1:length(files)
        filename=files(ii).name;
        filepath=fullfile(SouDir, filename);
        file=imread(filepath);
        DN=file(index);
        data=AddData(data, DN);
    end

end
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
function    [ st, msg ] = cmd_rmdir( folderspec )       
%   cmd_rmdir removes a directory and its contents 
%   
%   Removes all directories and files in the specified directory in
%   addition to the directory itself.  Used to remove a directory tree.
%   See also: xtests\generic_utilies_test.m      
    narginchk( 1, 1 )
    dos_cmd = sprintf( 'rmdir /S /Q "%s"', folderspec ); 
    [ st, msg ] = system( dos_cmd );
end
30.[Matlab]过滤像元,小于定值者重设为定值
 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
% Created by LI Xu
% Version 1.0
% Febuary 2, 2016

% Description
% Replace values with new

% If you have any question about this code,
% please do not hesitate to contact me via E-mail: 
% jeremy456@163.com

% Blog:
% http://blog.sciencenet.cn/u/lixujeremy
% http://lixuworld.blogspot.com/

clear;
clc;

% Source Directory
SouDir='./input';
% Destination Directory
DesDir='./output';

% All Files
files=dir(fullfile(SouDir, '*.tif'));
keyval=0;

for ii=1:length(files)
    filename=files(ii).name;
    inpath=fullfile(SouDir, filename);
    [image, geo]=geotiffread(inpath);
    info=geotiffinfo(inpath);
    index=find(image<keyval);
    if ~isempty(index)
        image(index)=keyval;
    end
    
    % Export
    otpath=fullfile(DesDir, filename);
    geotiffwrite(otpath, image, geo, 'GeoKeyDirectoryTag', info.GeoTIFFTags.GeoKeyDirectoryTag);
    disp([num2str(ii), ': ', filename]);

end

disp('*********************************************');
31.[Matlab]修改bar颜色
1
2
3
4
5
6
7
8
9
function ChangeColor(handle, RGBs)
    color=[];
    for ii=1:size(RGBs)
        rgb=RGBs(ii, :);
        color=[color; {rgb./255}];        
    end
    set(handle, {'FaceColor'}, color);

end
32.[Matlab]乘号:‘\times’;减号:‘char(8722)’;
 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
% Created by LI Xu
% Version 1.0
% April 10, 2016

% Description:
% Convert Lat/Long in deg/min/sec format
% to demical degree

% If you have any question about this code,
% please do not hesitate to contact me via E-mail: 
% jeremy456@163.com

% Blog:
% http://blog.sciencenet.cn/u/lixujeremy
% http://lixuworld.blogspot.com/


clear;
clc;

% XLS
xlspath='input.xlsx';
[rawdata, labels, ~]=xlsread(xlspath);
labels(1:2, :)=[];
labels(:, 2:end)=[];

lat=rawdata(:, 1:3);
otlat=lat(:, 1)+lat(:, 2)./60+lat(:, 3)./3600;
long=rawdata(:, 4:end);
otlong=long(:, 1)+long(:, 2)./60+long(:, 3)./3600;

otdata=[otlat, otlong];
otdata=[labels, num2cell(otdata)];

disp('*****************************************');
34.[Matlab]中文显示不正常,可以使用如下代码尝试之.
feature('DefaultCharacterSet', 'UTF8');
35.[Matlab]temll元胞向量,每个元胞含有相同大小的元胞数组,以下可以将子元胞数组打开并规则输出
newcon=vertcat(temll{:});


No comments:

Post a Comment