windows上自动设置java环境变量的脚本

@echo off

:: TODO:设置java环境变量
:: Author: Gwt
color 02
::设置java的安装路径,可方便切换不同的版本
set input=
set /p "input=请输入java的jdk路径(或回车默认路径为C:\Program Files\Java\jdk1.7.0_71):"
if defined input (echo jdk已设置) else (set input=C:\Program Files\Java\jdk1.7.0_71)
echo jdk路径为%input%
set javaPath=%input%

::如果有的话,先删除JAVA_HOME
wmic ENVIRONMENT where "name='JAVA_HOME'" delete

::如果有的话,先删除ClASS_PATH 
wmic ENVIRONMENT where "name='CLASS_PATH'" delete

::创建JAVA_HOME
wmic ENVIRONMENT create name="JAVA_HOME",username="<system>",VariableValue="%javaPath%"

::创建CLASS_PATH
wmic ENVIRONMENT create name="CLASS_PATH",username="<system>",VariableValue=".;%%JAVA_HOME%%\lib\tools.jar;%

%JAVA_HOME%%\lib\dt.jar;"

::在环境变量path中,剔除掉变量java_home中的字符,回显剩下的字符串
call set xx=%Path%;%JAVA_HOME%\jre\bin;%JAVA_HOME%\bin

::echo %xx%

::将返回显的字符重新赋值到path中
wmic ENVIRONMENT where "name='Path' and username='<system>'" set VariableValue="%xx%"

pause

解释下命令

   @echo off 是关闭回显的,不会显示命令信息 on打开会显示命令信息

  color 02是设置输出文本颜色的,这里是控制命令台输出绿颜色

  set /p "input=请输入命令信息" 是用来接收控制台输入的文本信息的

  if else 是用来做判断 if defined input 是用来判断用户是否输入信息,回车的话,则表示未定义input的值

  echo "输出信息" 是用来显示信息的

  set javaPath=%input% 是用来吧变量input的值赋值给javaPath变量的

  wmic 是提供了批处理的命令,可以方便的操作环境变量值

  删除某一环境变量 就使用 wmic ENVIRONMENT where "name='JAVA_HOME'" delete命令

  创建某一环境变量 使用 wmic ENVIRONMENT create name="JAVA_HOME",username="<system>",VariableValue="%javaPath%"命令

      修改某一环境变量 使用 wmic ENVIRONMENT where "name='Path' and username='<system>'" set VariableValue="value"

注意事项:

  1、在上述批处理脚本命令中,要严格注意空格和大小写等的输入,不然执行不成功的

  2、要以管理员方式运行命令,不然提示拒绝执行命令的提示

解决MacOS下readlink: illegal option -- f

Mac下的readlink没有-f参数,诸如screenfetch又会去调用readlink -f,于是每次都会出现:

readlink: illegal option -- f
usage: readlink [-n] [file ...]

很是烦人,解决方案如下:
1.安装coreutils:

brew install coreutils

2.设置环境变量,编辑~/.bash_profile,添加:

export PATH="/usr/local/opt/coreutils/libexec/gnubin:$PATH"

3.创建别名,使用greadlink替代readlink,同样是编辑~/.bash_profile,添加:

alias readlink=greadlink

C# JSON工具类

using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Linq;
using System.Web.Script.Serialization;
using System.Collections;

namespace WindowsFormsTestApp1
{
    public class JsonConverter
    {

        /// <summary>
        /// 自定义查询对象转换动态类
        /// add yuangang by 2015-05-19
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static dynamic JsonClass(object obj)
        {
            return ConvertJson(Serialize(obj, true));
        }

        /// <summary>
        /// object动态类转换json包
        /// add yuangang by 2015-05-19
        /// </summary>
        /// <param name="obj">对象</param>
        /// <param name="DateConvert">时间戳是否转换成日期类型</param>
        /// <returns></returns>
        public static string Serialize(object obj, bool DateConvert = false)
        {
            JavaScriptSerializer jss = new JavaScriptSerializer();
            var str = jss.Serialize(obj);
            if (DateConvert)
            {
                str = System.Text.RegularExpressions.Regex.Replace(str, @"\\/Date\((\d+)\)\\/", match =>
                {
                    DateTime dt = new DateTime(1970, 1, 1);
                    dt = dt.AddMilliseconds(long.Parse(match.Groups[1].Value));
                    dt = dt.ToLocalTime();
                    return dt.ToString("yyyy-MM-dd HH:mm:ss");
                });
            }
            return str;
        }

        /// <summary>
        /// json转换object动态类
        /// add yuangang by 2015-05-19
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>
        public static dynamic ConvertJson(string json)
        {
            JavaScriptSerializer jss = new JavaScriptSerializer();
            jss.RegisterConverters(new JavaScriptConverter[] { new DynamicJsonConverter() });
            dynamic dy = jss.Deserialize(json, typeof(object)) as dynamic;
            return dy;
        }

        /// <summary>  
        /// DataReader转换为Json  
        /// </summary>  
        /// <param name="dataReader">DataReader对象</param>  
        /// <returns>Json字符串</returns>  
        public static string ToJson(IDataReader dataReader)
        {
            try
            {
                StringBuilder jsonString = new StringBuilder();
                jsonString.Append("[");

                while (dataReader.Read())
                {
                    jsonString.Append("{");
                    for (int i = 0; i < dataReader.FieldCount; i++)
                    {
                        Type type = dataReader.GetFieldType(i);
                        string strKey = dataReader.GetName(i);
                        string strValue = dataReader[i].ToString();
                        jsonString.Append("\"" + strKey + "\":");
                        strValue = StringFormat(strValue, type);
                        if (i < dataReader.FieldCount - 1)
                        {
                            jsonString.Append(strValue + ",");
                        }
                        else
                        {
                            jsonString.Append(strValue);
                        }
                    }
                    jsonString.Append("},");
                }
                if (!dataReader.IsClosed)
                {
                    dataReader.Close();
                }
                jsonString.Remove(jsonString.Length - 1, 1);
                jsonString.Append("]");
                if (jsonString.Length == 1)
                {
                    return "[]";
                }
                return jsonString.ToString();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>  
        /// DataSet转换为Json  
        /// add yuangang by 2015-05-19
        /// </summary>  
        /// <param name="dataSet">DataSet对象</param>  
        /// <returns>Json字符串</returns>  
        public static string ToJson(DataSet dataSet)
        {
            string jsonString = "{";
            foreach (DataTable table in dataSet.Tables)
            {
                jsonString += "\"" + table.TableName + "\":" + ToJson(table) + ",";
            }
            jsonString = jsonString.TrimEnd(',');
            return jsonString + "}";
        }
        /// <summary> 
        /// DataTable转成Json  
        /// add yuangang by 2015-05-19
        /// </summary> 
        /// <param name="jsonName"></param> 
        /// <param name="dt"></param> 
        /// <returns></returns> 
        public static string ToJson(DataTable dt, string jsonName)
        {
            StringBuilder Json = new StringBuilder();
            if (string.IsNullOrEmpty(jsonName))
                jsonName = dt.TableName;
            Json.Append("{\"" + jsonName + "\":[");
            if (dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    Json.Append("{");
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        Type type = dt.Rows[i][j].GetType();
                        Json.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":" + StringFormat(dt.Rows[i][j] is DBNull ? string.Empty : dt.Rows[i][j].ToString(), type));
                        if (j < dt.Columns.Count - 1)
                        {
                            Json.Append(",");
                        }
                    }
                    Json.Append("}");
                    if (i < dt.Rows.Count - 1)
                    {
                        Json.Append(",");
                    }
                }
            }
            Json.Append("]}");
            return Json.ToString();
        }
        /// <summary>  
        /// Datatable转换为Json  
        /// add yuangang by 2015-05-19
        /// </summary>  
        /// <param name="table">Datatable对象</param>  
        /// <returns>Json字符串</returns>  
        public static string ToJson(DataTable dt)
        {
            StringBuilder jsonString = new StringBuilder();
            jsonString.Append("[");
            DataRowCollection drc = dt.Rows;
            for (int i = 0; i < drc.Count; i++)
            {
                jsonString.Append("{");
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    string strKey = dt.Columns[j].ColumnName;
                    string strValue = drc[i][j].ToString();
                    Type type = dt.Columns[j].DataType;
                    jsonString.Append("\"" + strKey + "\":");
                    strValue = StringFormat(strValue, type);
                    if (j < dt.Columns.Count - 1)
                    {
                        jsonString.Append(strValue + ",");
                    }
                    else
                    {
                        jsonString.Append(strValue);
                    }
                }
                jsonString.Append("},");
            }
            jsonString.Remove(jsonString.Length - 1, 1);
            jsonString.Append("]");
            if (jsonString.Length == 1)
            {
                return "[]";
            }
            return jsonString.ToString();
        }
        /// <summary> 
        /// 格式化字符型、日期型、布尔型 
        /// add yuangang by 2015-05-19
        /// </summary> 
        /// <param name="str"></param> 
        /// <param name="type"></param> 
        /// <returns></returns> 
        private static string StringFormat(string str, Type type)
        {
            if (type != typeof(string) && string.IsNullOrEmpty(str))
            {
                str = "\"" + str + "\"";
            }
            else if (type == typeof(string))
            {
                str = String2Json(str);
                str = "\"" + str + "\"";
            }
            else if (type == typeof(DateTime))
            {
                str = "\"" + str + "\"";
            }
            else if (type == typeof(bool))
            {
                str = str.ToLower();
            }
            else if (type == typeof(byte[]))
            {
                str = "\"" + str + "\"";
            }
            else if (type == typeof(Guid))
            {
                str = "\"" + str + "\"";
            }
            return str;
        }
        /// <summary> 
        /// 过滤特殊字符 
        /// add yuangang by 2015-05-19
        /// </summary> 
        /// <param name="s"></param> 
        /// <returns></returns> 
        public static string String2Json(String s)
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < s.Length; i++)
            {
                char c = s.ToCharArray()[i];
                switch (c)
                {
                    case '\"':
                        sb.Append("\\\""); break;
                    case '\\':
                        sb.Append("\\\\"); break;
                    case '/':
                        sb.Append("\\/"); break;
                    case '\b':
                        sb.Append("\\b"); break;
                    case '\f':
                        sb.Append("\\f"); break;
                    case '\n':
                        sb.Append("\\n"); break;
                    case '\r':
                        sb.Append("\\r"); break;
                    case '\t':
                        sb.Append("\\t"); break;
                    case '\v':
                        sb.Append("\\v"); break;
                    case '\0':
                        sb.Append("\\0"); break;
                    default:
                        sb.Append(c); break;
                }
            }
            return sb.ToString();
        }

        public static string GetDataGridJsonByDataSet(DataSet ds, string totalProperty, string root)
        {
            return GetDataGridJsonByDataTable(ds.Tables[0], totalProperty, root);
        }
        public static string GetDataGridJsonByDataTable(DataTable dt, string totalProperty, string root)
        {
            StringBuilder jsonBuilder = new StringBuilder();
            jsonBuilder.Append("({\"" + totalProperty + "\":\"" + dt.Rows.Count + "\",");
            jsonBuilder.Append("\"");
            jsonBuilder.Append(root);
            jsonBuilder.Append("\":[");
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                jsonBuilder.Append("{");
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    jsonBuilder.Append("\"");
                    jsonBuilder.Append(dt.Columns[j].ColumnName);
                    jsonBuilder.Append("\":\"");
                    jsonBuilder.Append(dt.Rows[i][j].ToString());
                    jsonBuilder.Append("\",");
                }
                jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
                jsonBuilder.Append("},");
            }
            jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
            jsonBuilder.Append("]");
            jsonBuilder.Append("})");
            return jsonBuilder.ToString();
        }

        public static string GetTreeJsonByDataSet(DataSet ds)
        {
            return GetTreeJsonByDataTable(ds.Tables[0]);
        }
        public static string GetTreeJsonByDataTable(DataTable dataTable)
        {
            DataTable dt = FormatDataTableForTree(dataTable);
            StringBuilder jsonBuilder = new StringBuilder();
            jsonBuilder.Append("[");
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                jsonBuilder.Append("{");
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    jsonBuilder.Append("\'");

                    if (dt.Columns[j].ColumnName == "leaf")
                    {
                        string leafValue = dt.Rows[i][j].ToString();

                        if (!string.IsNullOrEmpty(leafValue))
                        {
                            jsonBuilder.Append(dt.Columns[j].ColumnName);
                            jsonBuilder.Append("\':\'");
                            jsonBuilder.Append(dt.Rows[i][j].ToString());
                            jsonBuilder.Append("\',");
                        }
                        else
                        {
                            jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
                        }
                    }
                    else if (dt.Columns[j].ColumnName == "customUrl")
                    {
                        jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
                        jsonBuilder.Append(dt.Columns[j].ColumnName);
                        jsonBuilder.Append(":\'");
                        jsonBuilder.Append(dt.Rows[i][j].ToString());
                        jsonBuilder.Append("\',");
                    }
                    else
                    {
                        jsonBuilder.Append(dt.Columns[j].ColumnName);
                        jsonBuilder.Append("\':\'");
                        jsonBuilder.Append(dt.Rows[i][j].ToString());
                        jsonBuilder.Append("\',");
                    }

                }
                jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
                jsonBuilder.Append("},");
            }
            jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
            jsonBuilder.Append("]");
            return jsonBuilder.ToString();
        }
        private static DataTable FormatDataTableForTree(DataTable dt)
        {
            DataTable dtTree = new DataTable();
            dtTree.Columns.Add("id", typeof(string));
            dtTree.Columns.Add("text", typeof(string));
            dtTree.Columns.Add("leaf", typeof(string));
            dtTree.Columns.Add("cls", typeof(string));
            dtTree.Columns.Add("customUrl", typeof(string));
            dtTree.AcceptChanges();

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                DataRow drTree = dtTree.NewRow();
                drTree["id"] = dt.Rows[i]["id"].ToString();
                drTree["text"] = dt.Rows[i]["text"].ToString();
                if (dt.Rows[i]["leaf"].ToString() == "Y")
                {
                    drTree["leaf"] = "true";
                    drTree["cls"] = "file";
                }
                else
                {
                    drTree["cls"] = "folder";
                }
                drTree["customUrl"] = dt.Rows[i]["customUrl"].ToString();
                dtTree.Rows.Add(drTree);
            }
            return dtTree;
        }

    }
    /// <summary>
    /// 动态JSON解析
    /// add yuangang by 2015-05-19
    /// </summary>
    public class DynamicJsonObject : System.Dynamic.DynamicObject
    {
        private IDictionary<string, object> Dictionary { get; set; }

        public DynamicJsonObject(IDictionary<string, object> dictionary)
        {
            this.Dictionary = dictionary;
        }

        public override bool TryGetMember(System.Dynamic.GetMemberBinder binder, out object result)
        {
            result = this.Dictionary[binder.Name];

            if (result is IDictionary<string, object>)
            {
                result = new DynamicJsonObject(result as IDictionary<string, object>);
            }
            else if (result is ArrayList && (result as ArrayList) is IDictionary<string, object>)
            {
                result = new List<DynamicJsonObject>((result as ArrayList).ToArray().Select(x => new DynamicJsonObject(x as IDictionary<string, object>)));
            }
            else if (result is ArrayList)
            {
                result = new List<object>((result as ArrayList).ToArray());
            }

            return this.Dictionary.ContainsKey(binder.Name);
        }
    }
    /// <summary>
    /// 动态JSON转换
    /// add yuangang by 2015-05-19
    /// </summary>
    public class DynamicJsonConverter : JavaScriptConverter
    {
        public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
        {
            if (dictionary == null)
                throw new ArgumentNullException("dictionary");

            if (type == typeof(object))
            {
                return new DynamicJsonObject(dictionary);
            }

            return null;
        }

        public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
        {
            throw new NotImplementedException();
        }

        public override IEnumerable<Type> SupportedTypes
        {
            get { return new System.Collections.ObjectModel.ReadOnlyCollection<Type>(new List<Type>(new Type[] { typeof(object) })); }
        }
    }
}


C# 获取所有用户进程信息

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Diagnostics;
using System.Management;
using System.Collections;
using System.Net;

namespace WindowsFormsTestApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Console.Write("窗体加载");
        }

        private static string GetProcessUserName(int processId)
        {
            string name = "";
           
            SelectQuery query = new SelectQuery("select * from Win32_Process where processID=" + processId);
            ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);

            try
            {
                foreach (ManagementObject disk in searcher.Get())
                {
                    ManagementBaseObject inPar = null;
                    ManagementBaseObject outPar = null;

                    inPar = disk.GetMethodParameters("GetOwner");

                    outPar = disk.InvokeMethod("GetOwner", inPar, null);

                    name = outPar["User"].ToString();
                    break;
                }
            }
            catch
            {
                name = "SYSTEM";
            }

            return name;
        }


        private void button1_Click(object sender, EventArgs e)
        {
            string str = "";
            textBox1.Clear();
            Process[] processes;
            processes = Process.GetProcesses();
            //Grab some basic information for each process.
            Process process;
            List<IDictionary> infoList = new List<IDictionary>();
            Dictionary<string, Object> result = new Dictionary<string, Object>();
            for (int i = 0; i < processes.Length - 1; i++)
            {
                process = processes[i];
                textBox1.AppendText(Convert.ToString(process.Id) + " : " + process.ProcessName + " : " + GetProcessUserName(process.Id) + "\r\n");
                Dictionary<string, string> dic = new Dictionary<string, string>();
                dic.Add("pid", Convert.ToString(process.Id));
                dic.Add("name", process.ProcessName);
                dic.Add("userName", GetProcessUserName(process.Id));
                infoList.Add(dic);
            }
            result.Add("list", infoList);
            IPHostEntry myHost = new IPHostEntry();
            myHost = Dns.GetHostByName(Dns.GetHostName());
            result.Add("hostName", myHost.HostName.ToString());
            string myip = "";
            for (int i = 0; i < myHost.AddressList.Length; i++)
            {
                if(myip.Length == 0)
                {
                    myip = myip + myHost.AddressList[i].ToString();
                }
                else
                {
                    myip = myip + ";" + myHost.AddressList[i].ToString();
                }
               
            }
            result.Add("ipaddr", myip);
            MessageBox.Show("检测已完成,总计读取到"+ infoList.Count+ "个进程" + JsonConverter.Serialize(result));
        }
    }
}

解决Python 3.6使用pip时Unable to locate finder for pip._vendor.distlib的问题

最近在笔记本上安装了Python 3.6 x86-64位版本,习惯性的创建了一个virtualenv,然后使用pip安装第三库的时候发生以下错误:

Collecting virtualenv
  Downloading virtualenv-15.0.3-py2.py3-none-any.whl (3.5MB)
    100% |████████████████████████████████| 3.5MB 256kB/s
Installing collected packages: virtualenv
Exception:
Traceback (most recent call last):
  File "c:\users\corey shaw\appdata\local\programs\python\python36\lib\site-packages\pip\basecommand.py", line 215, in main
    status = self.run(options, args)
  File "c:\users\corey shaw\appdata\local\programs\python\python36\lib\site-packages\pip\commands\install.py", line 317, in run
    prefix=options.prefix_path,
  File "c:\users\corey shaw\appdata\local\programs\python\python36\lib\site-packages\pip\req\req_set.py", line 742, in install
    **kwargs
  File "c:\users\corey shaw\appdata\local\programs\python\python36\lib\site-packages\pip\req\req_install.py", line 831, in install
    self.move_wheel_files(self.source_dir, root=root, prefix=prefix)
  File "c:\users\corey shaw\appdata\local\programs\python\python36\lib\site-packages\pip\req\req_install.py", line 1032, in move_wheel_files
    isolated=self.isolated,
  File "c:\users\corey shaw\appdata\local\programs\python\python36\lib\site-packages\pip\wheel.py", line 493, in move_wheel_files
    maker.make_multiple(['%s = %s' % kv for kv in console.items()])
  File "c:\users\corey shaw\appdata\local\programs\python\python36\lib\site-packages\pip\_vendor\distlib\scripts.py", line 383, in make_multiple
    filenames.extend(self.make(specification, options))
  File "c:\users\corey shaw\appdata\local\programs\python\python36\lib\site-packages\pip\_vendor\distlib\scripts.py", line 372, in make
    self._make_script(entry, filenames, options=options)
  File "c:\users\corey shaw\appdata\local\programs\python\python36\lib\site-packages\pip\_vendor\distlib\scripts.py", line 276, in _make_script
    self._write_script(scriptnames, shebang, script, filenames, ext)
  File "c:\users\corey shaw\appdata\local\programs\python\python36\lib\site-packages\pip\_vendor\distlib\scripts.py", line 212, in _write_script
    launcher = self._get_launcher('t')
  File "c:\users\corey shaw\appdata\local\programs\python\python36\lib\site-packages\pip\_vendor\distlib\scripts.py", line 351, in _get_launcher
    result = finder(distlib_package).find(name).bytes
  File "c:\users\corey shaw\appdata\local\programs\python\python36\lib\site-packages\pip\_vendor\distlib\resources.py", line 324, in finder
    raise DistlibException('Unable to locate finder for %r' % package)
pip._vendor.distlib.DistlibException: Unable to locate finder for 'pip._vendor.distlib'

解决方案如下:
1.激活对应的virtualenv,然后执行:

python -m pip uninstall pip setuptools

2.下载

https://bootstrap.pypa.io/get-pip.py

3.同样在virtualenv激活状态下,执行python get-pip.py,这里要注意路径的问题,很可能路径没配置,导致了把原有python进行了pip卸载重装的动作