/// <summary>
        /// If a TaskSequence was interrupted, it is possible to continue
        /// from the last loaded trial before the interruption.
        /// </summary>
        /// <returns>Current sequence index after load.</returns>
        public virtual int LoadPartiallyFinishedTaskSequence()
        {
            if (!File.Exists(Path.Combine(MmTaskUserData.DirPath, PartialDataFile)))
            {
                return(0);
            }

            var reader = new StreamReader(Path.Combine(MmTaskUserData.DirPath,
                                                       PartialDataFile),
                                          Encoding.UTF8);

            string line = reader.ReadLine();

            if (line == null)
            {
                MmLogger.LogError("Partial Sequence File Empty");
                return(-1);
            }

            var curSequenceIndex = int.Parse(line.Split(',')[1]);

            reader.Close();

            return(curSequenceIndex);
        }
Пример #2
0
        /// <summary>
        /// Read the area constraints from an .area file.
        /// </summary>
        /// <param name="areafilename"></param>
        /// <param name="intriangles"></param>
        /// <param name="data"></param>
        private double[] ReadAreaFile(string areafilename, int intriangles)
        {
            double[] data = null;

            using (
#if NETFX_CORE
                var reader = new WinRTLegacy.IO.StreamReader(areafilename)
#else
                var reader = new StreamReader(areafilename)
#endif
                )
            {
                string[] line;

                if (!TryReadLine(reader, out line))
                {
                    throw new Exception("Can't read input file (area).");
                }

                if (int.Parse(line[0]) != intriangles)
                {
                    Log.Instance.Warning("Number of area constraints doesn't match number of triangles.",
                                         "ReadAreaFile()");
                    return(null);
                }

                data = new double[intriangles];

                // Read area constraints.
                for (int i = 0; i < intriangles; i++)
                {
                    if (!TryReadLine(reader, out line))
                    {
                        throw new Exception("Can't read input file (area).");
                    }

                    if (line.Length != 2)
                    {
                        throw new Exception("Triangle has no nodes.");
                    }

                    data[i] = double.Parse(line[1], nfi);
                }
            }

            return(data);
        }
Пример #3
0
 private static void loadHighScore()
 {
     try
     {
         if (File.Exists(Application.persistentDataPath + "/score.json"))
         {
             StreamReader sr       = new StreamReader(Application.persistentDataPath + "/score.json");
             string       loadJSON = sr.ReadToEnd();
             sr.Close();
             highScore = UnityEngine.JsonUtility.FromJson <HighScoreData>(loadJSON).highScore;
         }
     }
     catch
     {
         highScore = 0;
         return;
     }
 }
Пример #4
0
 public static bool Load(out Tile[] tiles, out int score)
 {
     try
     {
         loadHighScore();
         tiles = null;
         score = 0;
         if (File.Exists(Application.persistentDataPath + "/save.json"))
         {
             StreamReader sr       = new StreamReader(Application.persistentDataPath + "/save.json");
             string       loadJSON = sr.ReadToEnd();
             sr.Close();
             if (loadJSON == "")
             {
                 File.Delete(Application.persistentDataPath + "/save.json");
                 return(false);
             }
             TilesCollection TS = UnityEngine.JsonUtility.FromJson <TilesCollection>(loadJSON);
             tiles = new Tile[TS.tsd.Length];
             for (int i = 0; i < TS.tsd.Length; i++)
             {
                 tiles[i]          = new Tile();
                 tiles[i].Value    = TS.tsd[i].value;
                 tiles[i].Position = TS.tsd[i].i;
             }
             score = TS.score;
             return(true);
         }
         else
         {
             return(false);
         }
     }
     catch
     {
         score = 0;
         tiles = null;
         return(false);
     }
 }
        /// <summary>
        /// Given a collection of task infos, load
        /// the task sequence from file into the collection.
        /// </summary>
        /// <param name="taskInfos">Collection filled by task sequence from
        /// file. Can be empty if file unloaded.</param>
        public virtual void LoadTaskSequence(ref LinkedList <U> taskInfos)
        {
            var filename = MmTaskUserData.BaseDirectory + "/" + TaskSeqFilename;

            try
            {
                using (var sr = new StreamReader(filename, Encoding.UTF8))
                {
                    // Skip header line
                    var line = sr.ReadLine();

                    if (string.IsNullOrEmpty(line))
                    {
                        return;
                    }

                    taskInfos = new LinkedList <U>();

                    while ((line = sr.ReadLine()) != null)
                    {
                        var t = new U();
                        t.Parse(line);

                        // Only load current user
                        if (t.UserId != MmTaskUserData.UserId)
                        {
                            continue;
                        }

                        taskInfos.AddLast(t);
                    }
                }
            }
            catch (Exception e)
            {
                MmLogger.LogError("The file could not be read:");
                MmLogger.LogError(e.Message);
            }
        }
Пример #6
0
        public static List <CsvRow> ParseCSV_Exp(string pathNameInResource)
        {
            StreamReader mysr = new StreamReader(pathNameInResource);
            string       str  = mysr.ReadToEnd();

            if (str == string.Empty)
            {
                return(null);
            }

            string contents = str;

            byte[]        datas  = System.Text.Encoding.UTF8.GetBytes(contents);
            CsvFileReader reader = new CSVHelper.CsvFileReader(new MemoryStream(datas));
            List <CsvRow> result = new List <CsvRow>();
            CsvRow        row    = new CsvRow();

            while (reader.ReadRow(row))
            {
                result.Add(row);
                row = new CsvRow();
            }
            return(result);
        }
    IEnumerator GetIdentifyWords()
    {
        // using (StreamReader audio = new StreamReader(filePath, Encoding.UTF8))
        using (StreamReader audio = new StreamReader(recordingWav.memoryStream))
        {
            // StreamReader audio = new StreamReader(recordingWav.memoryStream);
            BinaryReader br = new BinaryReader(audio.BaseStream);


            len = (int)audio.BaseStream.Length;

            byte[] buffer = new byte[len];
            br.Read(buffer, 0, buffer.Length);
            speech = Convert.ToBase64String(buffer);

            /*
             *
             * Char[] buffer_char = new Char[len];
             * audio.Read(buffer_char, 0, buffer_char.Length);
             *
             * byte[] buffer_byte = Encoding.ASCII.GetBytes(buffer_char);
             *
             * speech = Convert.ToBase64String(buffer_byte);
             */

            audio.Dispose();
            recordingWav.memoryStream.Dispose();
        }


        #region GetToken
        WWWForm form1 = new WWWForm();
        form1.AddField("grant_type", "client_credentials");
        form1.AddField("client_id", client_id);
        form1.AddField("client_secret", client_secret);

        WWW w1 = new WWW(url_token, form1);
        yield return(w1);

        BaiDuTokenData getToken = new BaiDuTokenData();
        JsonUtility.FromJsonOverwrite(w1.text, getToken);
        token = getToken.access_token;
        #endregion

        if (token == null || speech == null)
        {
            show_text.text = "参数信息不够";
        }
        yield return(0);

        var request = new UnityWebRequest(url_api, "POST");

        UploadData uploadData = new UploadData();
        uploadData.format  = format;
        uploadData.rate    = rate;
        uploadData.channel = channel;
        uploadData.cuid    = cuid;
        uploadData.token   = token;
        uploadData.speech  = speech;
        uploadData.len     = len;
        uploadData.lan     = lan;

        string data = JsonUtility.ToJson(uploadData);

        //JsonData data = new JsonData();

        Byte[] post_byte = Encoding.UTF8.GetBytes(data);


        request.uploadHandler   = (UploadHandler) new UploadHandlerRaw(post_byte);
        request.downloadHandler = (DownloadHandler) new DownloadHandlerBuffer();

        request.SetRequestHeader("Content-Type", "application/json");

        yield return(request.Send());

        try
        {
            AcceptanceIdentification acceptData = new AcceptanceIdentification();

            JsonUtility.FromJsonOverwrite(request.downloadHandler.text, acceptData);

            show_text.text = request.downloadHandler.text;

            show_text.text = acceptData.result[0].ToString();

            MatchTheWords(acceptData.result[0]);
        }
        catch (Exception ex)
        {
            show_text.text = "error :" + ex;
        }
    }
Пример #8
0
        /// <summary>
        /// Read an .edge file.
        /// </summary>
        /// <param name="edgeFile">The file name.</param>
        /// <param name="invertices">The number of input vertices (read from a .node or .poly file).</param>
        /// <returns>A List of edges.</returns>
        public List <Edge> ReadEdgeFile(string edgeFile, int invertices)
        {
            // Read poly file
            List <Edge> data = null;

            startIndex = 0;

            string[] line;

            using (
#if NETFX_CORE
                var reader = new WinRTLegacy.IO.StreamReader(edgeFile)
#else
                var reader = new StreamReader(edgeFile)
#endif
                )
            {
                // Read the edges from a .edge file.

                // Read number of segments and number of boundary markers.
                if (!TryReadLine(reader, out line))
                {
                    throw new Exception("Can't read input file (segments).");
                }

                int inedges = int.Parse(line[0]);

                int edgemarkers = 0;
                if (line.Length > 1)
                {
                    edgemarkers = int.Parse(line[1]);
                }

                if (inedges > 0)
                {
                    data = new List <Edge>(inedges);
                }

                int end1, end2, mark;
                // Read and insert the segments.
                for (int i = 0; i < inedges; i++)
                {
                    if (!TryReadLine(reader, out line))
                    {
                        throw new Exception("Can't read input file (segments).");
                    }

                    if (line.Length < 3)
                    {
                        throw new Exception("Segment has no endpoints.");
                    }

                    // TODO: startIndex ok?
                    end1 = int.Parse(line[1]) - startIndex;
                    end2 = int.Parse(line[2]) - startIndex;
                    mark = 0;

                    if (edgemarkers > 0 && line.Length > 3)
                    {
                        mark = int.Parse(line[3]);
                    }

                    if ((end1 < 0) || (end1 >= invertices))
                    {
                        if (Log.Verbose)
                        {
                            Log.Instance.Warning("Invalid first endpoint of segment.",
                                                 "MeshReader.ReadPolyfile()");
                        }
                    }
                    else if ((end2 < 0) || (end2 >= invertices))
                    {
                        if (Log.Verbose)
                        {
                            Log.Instance.Warning("Invalid second endpoint of segment.",
                                                 "MeshReader.ReadPolyfile()");
                        }
                    }
                    else
                    {
                        data.Add(new Edge(end1, end2, mark));
                    }
                }
            }

            return(data);
        }
Пример #9
0
        /// <summary>
        /// Read the elements from an .ele file.
        /// </summary>
        /// <param name="elefilename"></param>
        /// <param name="data"></param>
        /// <param name="readArea"></param>
        private List <ITriangle> ReadEleFile(string elefilename, bool readArea)
        {
            int intriangles = 0, attributes = 0;

            List <ITriangle> triangles;

            using (
#if NETFX_CORE
                var reader = new WinRTLegacy.IO.StreamReader(elefilename)
#else
                var reader = new StreamReader(elefilename)
#endif
                )
            {
                // Read number of elements and number of attributes.
                string[] line;
                bool     validRegion = false;

                if (!TryReadLine(reader, out line))
                {
                    throw new Exception("Can't read input file (elements).");
                }

                intriangles = int.Parse(line[0]);

                // We irgnore index 1 (number of nodes per triangle)
                attributes = 0;
                if (line.Length > 2)
                {
                    attributes  = int.Parse(line[2]);
                    validRegion = true;
                }

                if (attributes > 1)
                {
                    Log.Instance.Warning("Triangle attributes not supported.", "FileReader.Read");
                }

                triangles = new List <ITriangle>(intriangles);

                InputTriangle tri;

                // Read triangles.
                for (int i = 0; i < intriangles; i++)
                {
                    if (!TryReadLine(reader, out line))
                    {
                        throw new Exception("Can't read input file (elements).");
                    }

                    if (line.Length < 4)
                    {
                        throw new Exception("Triangle has no nodes.");
                    }

                    // TODO: startIndex ok?
                    tri = new InputTriangle(
                        int.Parse(line[1]) - startIndex,
                        int.Parse(line[2]) - startIndex,
                        int.Parse(line[3]) - startIndex);

                    // Read triangle region
                    if (attributes > 0 && validRegion)
                    {
                        int region = 0;
                        validRegion = int.TryParse(line[4], out region);
                        tri.label   = region;
                    }

                    triangles.Add(tri);
                }
            }

            // Read area file
            if (readArea)
            {
                string areafile = Path.ChangeExtension(elefilename, ".area");
                if (File.Exists(areafile))
                {
                    ReadAreaFile(areafile, intriangles);
                }
            }

            return(triangles);
        }
Пример #10
0
        /// <summary>
        /// Read the vertices and segments from a .poly file.
        /// </summary>
        /// <param name="polyfilename"></param>
        /// <param name="readElements">If true, look for an associated .ele file.</param>
        /// <param name="readElements">If true, look for an associated .area file.</param>
        public Polygon ReadPolyFile(string polyfilename, bool readElements, bool readArea)
        {
            // Read poly file
            Polygon data;

            startIndex = 0;

            string[] line;
            int      invertices = 0, attributes = 0, nodemarkers = 0;

            using (
#if NETFX_CORE
                var reader = new WinRTLegacy.IO.StreamReader(polyfilename)
#else
                var reader = new StreamReader(polyfilename)
#endif
                )
            {
                if (!TryReadLine(reader, out line))
                {
                    throw new Exception("Can't read input file.");
                }

                // Read number of vertices, number of dimensions, number of vertex
                // attributes, and number of boundary markers.
                invertices = int.Parse(line[0]);

                if (line.Length > 1)
                {
                    if (int.Parse(line[1]) != 2)
                    {
                        throw new Exception("Triangle only works with two-dimensional meshes.");
                    }
                }

                if (line.Length > 2)
                {
                    attributes = int.Parse(line[2]);
                }

                if (line.Length > 3)
                {
                    nodemarkers = int.Parse(line[3]);
                }

                // Read the vertices.
                if (invertices > 0)
                {
                    data = new Polygon(invertices);

                    for (int i = 0; i < invertices; i++)
                    {
                        if (!TryReadLine(reader, out line))
                        {
                            throw new Exception("Can't read input file (vertices).");
                        }

                        if (line.Length < 3)
                        {
                            throw new Exception("Invalid vertex.");
                        }

                        if (i == 0)
                        {
                            // Set the start index!
                            startIndex = int.Parse(line[0], nfi);
                        }

                        ReadVertex(data.Points, i, line, attributes, nodemarkers);
                    }
                }
                else
                {
                    // If the .poly file claims there are zero vertices, that means that
                    // the vertices should be read from a separate .node file.
                    data = ReadNodeFile(Path.ChangeExtension(polyfilename, ".node"));

                    invertices = data.Points.Count;
                }

                var points = data.Points;

                if (points.Count == 0)
                {
                    throw new Exception("No nodes available.");
                }

                // Read the segments from a .poly file.

                // Read number of segments and number of boundary markers.
                if (!TryReadLine(reader, out line))
                {
                    throw new Exception("Can't read input file (segments).");
                }

                int insegments = int.Parse(line[0]);

                int segmentmarkers = 0;
                if (line.Length > 1)
                {
                    segmentmarkers = int.Parse(line[1]);
                }

                int end1, end2, mark;
                // Read and insert the segments.
                for (int i = 0; i < insegments; i++)
                {
                    if (!TryReadLine(reader, out line))
                    {
                        throw new Exception("Can't read input file (segments).");
                    }

                    if (line.Length < 3)
                    {
                        throw new Exception("Segment has no endpoints.");
                    }

                    // TODO: startIndex ok?
                    end1 = int.Parse(line[1]) - startIndex;
                    end2 = int.Parse(line[2]) - startIndex;
                    mark = 0;

                    if (segmentmarkers > 0 && line.Length > 3)
                    {
                        mark = int.Parse(line[3]);
                    }

                    if ((end1 < 0) || (end1 >= invertices))
                    {
                        if (Log.Verbose)
                        {
                            Log.Instance.Warning("Invalid first endpoint of segment.",
                                                 "MeshReader.ReadPolyfile()");
                        }
                    }
                    else if ((end2 < 0) || (end2 >= invertices))
                    {
                        if (Log.Verbose)
                        {
                            Log.Instance.Warning("Invalid second endpoint of segment.",
                                                 "MeshReader.ReadPolyfile()");
                        }
                    }
                    else
                    {
                        data.Add(new Segment(points[end1], points[end2], mark));
                    }
                }

                // Read holes from a .poly file.

                // Read the holes.
                if (!TryReadLine(reader, out line))
                {
                    throw new Exception("Can't read input file (holes).");
                }

                int holes = int.Parse(line[0]);
                if (holes > 0)
                {
                    for (int i = 0; i < holes; i++)
                    {
                        if (!TryReadLine(reader, out line))
                        {
                            throw new Exception("Can't read input file (holes).");
                        }

                        if (line.Length < 3)
                        {
                            throw new Exception("Invalid hole.");
                        }

                        data.Holes.Add(new Point(double.Parse(line[1], nfi),
                                                 double.Parse(line[2], nfi)));
                    }
                }

                // Read area constraints (optional).
                if (TryReadLine(reader, out line))
                {
                    int id, regions = int.Parse(line[0]);

                    if (regions > 0)
                    {
                        for (int i = 0; i < regions; i++)
                        {
                            if (!TryReadLine(reader, out line))
                            {
                                throw new Exception("Can't read input file (region).");
                            }

                            if (line.Length < 4)
                            {
                                throw new Exception("Invalid region attributes.");
                            }

                            if (!int.TryParse(line[3], out id))
                            {
                                id = i;
                            }

                            double area = 0.0;

                            if (line.Length > 4)
                            {
                                double.TryParse(line[4], NumberStyles.Number, nfi, out area);
                            }

                            // Triangle's .poly file format allows region definitions with
                            // either 4 or 5 parameters, and different interpretations for
                            // them depending on the number of parameters.
                            //
                            // See http://www.cs.cmu.edu/~quake/triangle.poly.html
                            //
                            // The .NET version will interpret the fourth parameter always
                            // as an integer region id and the optional fifth parameter as
                            // an area constraint.

                            data.Regions.Add(new RegionPointer(
                                                 double.Parse(line[1], nfi), // Region x
                                                 double.Parse(line[2], nfi), // Region y
                                                 id, area));
                        }
                    }
                }
            }

            // Read ele file
            if (readElements)
            {
                string elefile = Path.ChangeExtension(polyfilename, ".ele");
                if (File.Exists(elefile))
                {
                    ReadEleFile(elefile, readArea);
                }
            }

            return(data);
        }
Пример #11
0
        /// <summary>
        /// Read the vertices from a file, which may be a .node or .poly file.
        /// </summary>
        /// <param name="nodefilename"></param>
        /// <param name="readElements"></param>
        public Polygon ReadNodeFile(string nodefilename, bool readElements)
        {
            Polygon data;

            startIndex = 0;

            string[] line;
            int      invertices = 0, attributes = 0, nodemarkers = 0;

            using (
#if NETFX_CORE
                var reader = new WinRTLegacy.IO.StreamReader(nodefilename)
#else
                var reader = new StreamReader(nodefilename)
#endif
                )
            {
                if (!TryReadLine(reader, out line))
                {
                    throw new Exception("Can't read input file.");
                }

                // Read number of vertices, number of dimensions, number of vertex
                // attributes, and number of boundary markers.
                invertices = int.Parse(line[0]);

                if (invertices < 3)
                {
                    throw new Exception("Input must have at least three input vertices.");
                }

                if (line.Length > 1)
                {
                    if (int.Parse(line[1]) != 2)
                    {
                        throw new Exception("Triangle only works with two-dimensional meshes.");
                    }
                }

                if (line.Length > 2)
                {
                    attributes = int.Parse(line[2]);
                }

                if (line.Length > 3)
                {
                    nodemarkers = int.Parse(line[3]);
                }

                data = new Polygon(invertices);

                // Read the vertices.
                if (invertices > 0)
                {
                    for (int i = 0; i < invertices; i++)
                    {
                        if (!TryReadLine(reader, out line))
                        {
                            throw new Exception("Can't read input file (vertices).");
                        }

                        if (line.Length < 3)
                        {
                            throw new Exception("Invalid vertex.");
                        }

                        if (i == 0)
                        {
                            startIndex = int.Parse(line[0], nfi);
                        }

                        ReadVertex(data.Points, i, line, attributes, nodemarkers);
                    }
                }
            }

            if (readElements)
            {
                // Read area file
                string elefile = Path.ChangeExtension(nodefilename, ".ele");
                if (File.Exists(elefile))
                {
                    ReadEleFile(elefile, true);
                }
            }

            return(data);
        }
    IEnumerator GetIdentifyWords()
    {
        StreamReader audio = new StreamReader(filePath, Encoding.UTF8);

        //  BinaryReader br = new BinaryReader(audio);

        len = (int)audio.Length;

        Debug.Log(" 文件大小 : " + len);

        byte[] buffer = new byte[len];
        br.Read(buffer, 0, buffer.Length);

        speech = Convert.ToBase64String(buffer);

        // Debug.Log("likai :  " + speech);

        if (recordingWav.speech_Byte != null)
        {
            // speech = Convert.ToBase64String(recordingWav.speech_Byte);
            //  Debug.Log("likai :  " + speech);
        }
        else
        {
            // Debug.Log(" 你所要取的信息为空 ");
        }



        // audio.Close();
        //audio.Dispose();
        // br.Close();
        //br.Dispose();



        #region GetToken
        WWWForm form1 = new WWWForm();
        form1.AddField("grant_type", "client_credentials");
        form1.AddField("client_id", client_id);
        form1.AddField("client_secret", client_secret);

        WWW w1 = new WWW(url_token, form1);
        yield return(w1);

        JsonData jd1 = JsonMapper.ToObject(w1.text);
        token = (string)jd1["access_token"];

        #endregion


        if (token == null || speech == null)
        {
            Debug.Log("参数信息不够");
        }
        yield return(0);

        var request = new UnityWebRequest(url_api, "POST");


        JsonData data = new JsonData();
        data["format"]  = format;
        data["rate"]    = rate;
        data["channel"] = channel;
        data["cuid"]    = cuid;
        data["token"]   = token;
        data["speech"]  = speech;
        data["len"]     = len;
        data["lan"]     = lan;
        Byte[] post_byte = null;//Encoding.Default.GetBytes(data.ToJson());

        request.uploadHandler   = (UploadHandler) new UploadHandlerRaw(post_byte);
        request.downloadHandler = (DownloadHandler) new DownloadHandlerBuffer();

        request.SetRequestHeader("Content-Type", "application/json");

        yield return(request.Send());

        // Debug.Log(request.downloadHandler.text);

        JsonData result = JsonMapper.ToObject(request.downloadHandler.text);

        MatchTheWords(result["result"][0].ToString());

        if (show_text != null)
        {
            show_text.text = result["result"][0].ToString();
        }
    }