text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Collections.Generic;
using System.CommandLine;
using System.IO;
using System.Linq;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace R2RDump
{
    public class DumpOptions
    {
        public bool Raw;
        public bool Normalize;
        public bool Naked;
        public bool Header;
        public bool Disasm;
        public bool Unwind;
        public bool GC;
        public bool SectionContents;
        public bool EntryPoints;
    }

    public abstract class Dumper
    {
        protected readonly R2RReader _r2r;
        protected readonly TextWriter _writer;
        protected readonly Disassembler _disassembler;
        protected readonly DumpOptions _options;

        public Dumper(R2RReader r2r, TextWriter writer, Disassembler disassembler, DumpOptions options)
        {
            _r2r = r2r;
            _writer = writer;
            _disassembler = disassembler;
            _options = options;
        }

        public IEnumerable<R2RSection> NormalizedSections()
        {
            IEnumerable<R2RSection> sections = _r2r.R2RHeader.Sections.Values;
            if (_options.Normalize)
            {
                sections = sections.OrderBy((s) => s.Type);
            }
            return sections;
        }

        public IEnumerable<R2RMethod> NormalizedMethods()
        {
            IEnumerable<R2RMethod> methods = _r2r.R2RMethods;
            if (_options.Normalize)
            {
                methods = methods.OrderBy((m) => m.SignatureString);
            }
            return methods;
        }

        /// <summary>
        /// Run right before printing output
        /// </summary>
        abstract internal void Begin();

        /// <summary>
        /// Run right after printing output
        /// </summary>
        abstract internal void End();
        abstract internal void WriteDivider(string title);
        abstract internal void WriteSubDivider();
        abstract internal void SkipLine();
        abstract internal void DumpHeader(bool dumpSections);
        abstract internal void DumpSection(R2RSection section, XmlNode parentNode = null);
        abstract internal void DumpEntryPoints();
        abstract internal void DumpAllMethods();
        abstract internal void DumpMethod(R2RMethod method, XmlNode parentNode = null);
        abstract internal void DumpRuntimeFunction(RuntimeFunction rtf, XmlNode parentNode = null);
        abstract internal void DumpDisasm(RuntimeFunction rtf, int imageOffset, XmlNode parentNode = null);
        abstract internal void DumpBytes(int rva, uint size, XmlNode parentNode = null, string name = "Raw", bool convertToOffset = true);
        abstract internal void DumpSectionContents(R2RSection section, XmlNode parentNode = null);
        abstract internal XmlNode DumpQueryCount(string q, string title, int count);
    }

    class R2RDump
    {
        // Options set by user specifying what to dump
        private bool _help;
        private IReadOnlyList<string> _inputFilenames = Array.Empty<string>();
        private string _outputFilename = null;
        private DumpOptions _options = new DumpOptions();
        private IReadOnlyList<string> _queries = Array.Empty<string>();
        private IReadOnlyList<string> _keywords = Array.Empty<string>();
        private IReadOnlyList<int> _runtimeFunctions = Array.Empty<int>();
        private IReadOnlyList<string> _sections = Array.Empty<string>();
        private bool _diff;
        private bool _xml;
        private TextWriter _writer;
        private Dictionary<R2RSection.SectionType, bool> _selectedSections = new Dictionary<R2RSection.SectionType, bool>();
        private Dumper _dumper;
        private bool _ignoreSensitive;

        private R2RDump()
        {
        }

        /// <summary>
        /// Parse commandline options
        /// </summary>
        private ArgumentSyntax ParseCommandLine(string[] args)
        {
            bool verbose = false;
            ArgumentSyntax argSyntax = ArgumentSyntax.Parse(args, syntax =>
            {
                syntax.ApplicationName = "R2RDump";
                syntax.HandleHelp = false;
                syntax.HandleErrors = true;

                syntax.DefineOption("h|help", ref _help, "Help message for R2RDump");
                syntax.DefineOptionList("i|in", ref _inputFilenames, "Input file(s) to dump. Expects them to by ReadyToRun images");
                syntax.DefineOption("o|out", ref _outputFilename, "Output file path. Dumps everything to the specified file except help message and exception messages");
                syntax.DefineOption("x|xml", ref _xml, "Output in XML format");
                syntax.DefineOption("raw", ref _options.Raw, "Dump the raw bytes of each section or runtime function");
                syntax.DefineOption("header", ref _options.Header, "Dump R2R header");
                syntax.DefineOption("d|disasm", ref _options.Disasm, "Show disassembly of methods or runtime functions");
                syntax.DefineOption("naked", ref _options.Naked, "Naked dump suppresses most compilation details like placement addresses");
                syntax.DefineOptionList("q|query", ref _queries, "Query method by exact name, signature, row id or token");
                syntax.DefineOptionList("k|keyword", ref _keywords, "Search method by keyword");
                syntax.DefineOptionList("r|runtimefunction", ref _runtimeFunctions, ArgStringToInt, "Get one runtime function by id or relative virtual address");
                syntax.DefineOptionList("s|section", ref _sections, "Get section by keyword");
                syntax.DefineOption("unwind", ref _options.Unwind, "Dump unwindInfo");
                syntax.DefineOption("gc", ref _options.GC, "Dump gcInfo and slot table");
                syntax.DefineOption("sc", ref _options.SectionContents, "Dump section contents");
                syntax.DefineOption("e|entrypoints", ref _options.EntryPoints, "Dump list of method / instance entrypoints in the R2R file");
                syntax.DefineOption("n|normalize", ref _options.Normalize, "Normalize dump by sorting the various tables and methods (default = unsorted i.e. file order)");
                syntax.DefineOption("v|verbose", ref verbose, "Dump disassembly, unwindInfo, gcInfo and section contents");
                syntax.DefineOption("diff", ref _diff, "Compare two R2R images");
                syntax.DefineOption("ignoreSensitive", ref _ignoreSensitive, "Ignores sensitive properties in xml dump to avoid failing tests");
            });

            if (verbose)
            {
                _options.Disasm = true;
                _options.Unwind = true;
                _options.GC = true;
                _options.SectionContents = true;
                _options.EntryPoints = true;
            }

            return argSyntax;
        }

        private int ArgStringToInt(string arg)
        {
            int n;
            if (!ArgStringToInt(arg, out n))
            {
                throw new ArgumentException("Can't parse argument to int");
            }
            return n;
        }

        /// <summary>
        /// Converts string passed as cmd line args into int, works for hexidecimal with 0x as prefix
        /// </summary>
        /// <param name="arg">The argument string to convert</param>
        /// <param name="n">The integer representation</param>
        private bool ArgStringToInt(string arg, out int n)
        {
			arg = arg.Trim();
            if (arg.StartsWith("0x", StringComparison.OrdinalIgnoreCase))
            {
                return int.TryParse(arg.Substring(2), System.Globalization.NumberStyles.HexNumber, null, out n);
            }
            return int.TryParse(arg, out n);
        }

        /// <summary>
        /// Outputs a warning message
        /// </summary>
        /// <param name="warning">The warning message to output</param>
        public static void WriteWarning(string warning)
        {
            Console.WriteLine($"Warning: {warning}");
        }

        // <summary>
        /// For each query in the list of queries, dump all methods matching the query by name, signature or id
        /// </summary>
        /// <param name="r2r">Contains all the extracted info about the ReadyToRun image</param>
        /// <param name="title">The title to print, "R2R Methods by Query" or "R2R Methods by Keyword"</param>
        /// <param name="queries">The keywords/ids to search for</param>
        /// <param name="exact">Specifies whether to look for methods with names/signatures/ids matching the method exactly or partially</param>
        private void QueryMethod(R2RReader r2r, string title, IReadOnlyList<string> queries, bool exact)
        {
            if (queries.Count > 0)
            {
                _dumper.WriteDivider(title);
            }
            foreach (string q in queries)
            {
                IList<R2RMethod> res = FindMethod(r2r, q, exact);
                XmlNode queryNode = _dumper.DumpQueryCount(q, "Methods", res.Count);
                foreach (R2RMethod method in res)
                {
                    _dumper.DumpMethod(method, queryNode);
                }
            }
        }

        // <summary>
        /// For each query in the list of queries, dump all sections by the name or value of the ReadyToRunSectionType enum
        /// </summary>
        /// <param name="r2r">Contains all the extracted info about the ReadyToRun image</param>
        /// <param name="queries">The names/values to search for</param>
        private void QuerySection(R2RReader r2r, IReadOnlyList<string> queries)
        {
            if (queries.Count > 0)
            {
                _dumper.WriteDivider("R2R Section");
            }
            foreach (string q in queries)
            {
                IList<R2RSection> res = FindSection(r2r, q);
                XmlNode queryNode = _dumper.DumpQueryCount(q, "Sections", res.Count);
                foreach (R2RSection section in res)
                {
                    _dumper.DumpSection(section, queryNode);
                }
            }
        }

        // <summary>
        /// For each query in the list of queries, dump a runtime function by id.
        /// The method containing the runtime function gets outputted, along with the single runtime function that was searched
        /// </summary>
        /// <param name="r2r">Contains all the extracted info about the ReadyToRun image</param>
        /// <param name="queries">The ids to search for</param>
        private void QueryRuntimeFunction(R2RReader r2r, IReadOnlyList<int> queries)
        {
            if (queries.Count > 0)
            {
                _dumper.WriteDivider("Runtime Functions");
            }
            foreach (int q in queries)
            {
                RuntimeFunction rtf = FindRuntimeFunction(r2r, q);

                if (rtf == null)
                {
                    WriteWarning("Unable to find by id " + q);
                    continue;
                }
                XmlNode queryNode = _dumper.DumpQueryCount(q.ToString(), "Runtime Function", 1);
                _dumper.DumpRuntimeFunction(rtf, queryNode);
            }
        }

        /// <summary>
        /// Outputs specified headers, sections, methods or runtime functions for one ReadyToRun image
        /// </summary>
        /// <param name="r2r">The structure containing the info of the ReadyToRun image</param>
        public void Dump(R2RReader r2r)
        {
            _dumper.Begin();

            if (_queries.Count == 0 && _keywords.Count == 0 && _runtimeFunctions.Count == 0 && _sections.Count == 0) //dump all sections and methods if no queries specified
            {
                if (_options.Header || !_options.EntryPoints)
                {
                    _dumper.WriteDivider("R2R Header");
                    _dumper.DumpHeader(true);
                }

                if (_options.EntryPoints)
                {
                    _dumper.DumpEntryPoints();
                }

                if (!_options.Header && !_options.EntryPoints)
                {
                    _dumper.DumpAllMethods();
                }
            }
            else //dump queried sections, methods and runtimeFunctions
            {
                if (_options.Header)
                {
                    _dumper.DumpHeader(false);
                }

                QuerySection(r2r, _sections);
                QueryRuntimeFunction(r2r, _runtimeFunctions);
                QueryMethod(r2r, "R2R Methods by Query", _queries, true);
                QueryMethod(r2r, "R2R Methods by Keyword", _keywords, false);
            }

            _dumper.End();
        }

        /// <summary>
        /// Returns true if the name, signature or id of <param>method</param> matches <param>query</param>
        /// </summary>
        /// <param name="exact">Specifies exact or partial match</param>
        /// <remarks>Case-insensitive and ignores whitespace</remarks>
        private bool Match(R2RMethod method, string query, bool exact)
        {
            int id;
            bool isNum = ArgStringToInt(query, out id);
            bool idMatch = isNum && (method.Rid == id || MetadataTokens.GetRowNumber(method.R2RReader.MetadataReader, method.MethodHandle) == id);

            bool sigMatch = false;
            if (exact)
            {
                sigMatch = method.Name.Equals(query, StringComparison.OrdinalIgnoreCase);
                if (!sigMatch)
                {
                    string sig = method.SignatureString.Replace(" ", "");
                    string q = query.Replace(" ", "");
                    int iMatch = sig.IndexOf(q, StringComparison.OrdinalIgnoreCase);
                    sigMatch = (iMatch == 0 || (iMatch > 0 && iMatch == (sig.Length - q.Length) && sig[iMatch - 1] == '.'));
                }
            }
            else
            {
                string sig = method.Signature.ReturnType + method.SignatureString.Replace(" ", "");
                sigMatch = (sig.IndexOf(query.Replace(" ", ""), StringComparison.OrdinalIgnoreCase) >= 0);
            }

            return idMatch || sigMatch;
        }

        /// <summary>
        /// Returns true if the name or value of the ReadyToRunSectionType of <param>section</param> matches <param>query</param>
        /// </summary>
        /// <remarks>Case-insensitive</remarks>
        private bool Match(R2RSection section, string query)
        {
            int queryInt;
            bool isNum = ArgStringToInt(query, out queryInt);
            string typeName = Enum.GetName(typeof(R2RSection.SectionType), section.Type);

            return (isNum && (int)section.Type == queryInt) || typeName.IndexOf(query, StringComparison.OrdinalIgnoreCase) >= 0;
        }

        /// <summary>
        /// Finds all R2RMethods by name/signature/id matching <param>query</param>
        /// </summary>
        /// <param name="r2r">Contains all extracted info about the ReadyToRun image</param>
        /// <param name="query">The name/signature/id to search for</param>
        /// <param name="exact">Specifies exact or partial match</param>
        /// <out name="res">List of all matching methods</out>
        /// <remarks>Case-insensitive and ignores whitespace</remarks>
        public IList<R2RMethod> FindMethod(R2RReader r2r, string query, bool exact)
        {
            List<R2RMethod> res = new List<R2RMethod>();
            foreach (R2RMethod method in r2r.R2RMethods)
            {
                if (Match(method, query, exact))
                {
                    res.Add(method);
                }
            }
            return res;
        }

        /// <summary>
        /// Finds all R2RSections by name or value of the ReadyToRunSectionType matching <param>query</param>
        /// </summary>
        /// <param name="r2r">Contains all extracted info about the ReadyToRun image</param>
        /// <param name="query">The name or value to search for</param>
        /// <out name="res">List of all matching sections</out>
        /// <remarks>Case-insensitive</remarks>
        public IList<R2RSection> FindSection(R2RReader r2r, string query)
        {
            List<R2RSection> res = new List<R2RSection>();
            foreach (R2RSection section in r2r.R2RHeader.Sections.Values)
            {
                if (Match(section, query))
                {
                    res.Add(section);
                }
            }
            return res;
        }

        /// <summary>
        /// Returns the runtime function with id matching <param>rtfQuery</param>
        /// </summary>
        /// <param name="r2r">Contains all extracted info about the ReadyToRun image</param>
        /// <param name="rtfQuery">The name or value to search for</param>
        public RuntimeFunction FindRuntimeFunction(R2RReader r2r, int rtfQuery)
        {
            foreach (R2RMethod m in r2r.R2RMethods)
            {
                foreach (RuntimeFunction rtf in m.RuntimeFunctions)
                {
                    if (rtf.Id == rtfQuery || (rtf.StartAddress >= rtfQuery && rtf.StartAddress + rtf.Size < rtfQuery))
                    {
                        return rtf;
                    }
                }
            }
            return null;
        }

        private int Run(string[] args)
        {
            ArgumentSyntax syntax = ParseCommandLine(args);

            // open output stream
            if (_outputFilename != null)
            {
                _writer = File.CreateText(_outputFilename);
            }
            else
            {
                _writer = Console.Out;
            }

            if (_help)
            {
                _writer.WriteLine(syntax.GetHelpText());
                return 0;
            }

            Disassembler disassembler = null;

            try
            {
                if (_inputFilenames.Count == 0)
                    throw new ArgumentException("Input filename must be specified (--in <file>)");

                if (_diff && _inputFilenames.Count < 2)
                    throw new ArgumentException("Need at least 2 input files in diff mode");

                if (_options.Naked && _options.Raw)
                {
                    throw new ArgumentException("The option '--naked' is incompatible with '--raw'");
                }

                R2RReader previousReader = null;

                foreach (string filename in _inputFilenames)
                {
                    // parse the ReadyToRun image
                    R2RReader r2r = new R2RReader(filename);

                    if (_options.Disasm)
                    {
                        if (r2r.InputArchitectureSupported() && r2r.DisassemblerArchitectureSupported())
                        {
                            disassembler = new Disassembler(r2r, _options);
                        }
                        else
                        {
                            throw new ArgumentException($"The architecture of input file {filename} ({r2r.Machine.ToString()}) or the architecture of the disassembler tools ({System.Runtime.InteropServices.RuntimeInformation.ProcessArchitecture.ToString()}) is not supported.");
                        }
                    }

                    if (_xml)
                    {
                        _dumper = new XmlDumper(_ignoreSensitive, r2r, _writer, disassembler, _options);
                    }
                    else
                    {
                        _dumper = new TextDumper(r2r, _writer, disassembler, _options);
                    }

                    if (!_diff)
                    {
                        // output the ReadyToRun info
                        Dump(r2r);
                    }
                    else if (previousReader != null)
                    {
                        new R2RDiff(previousReader, r2r, _writer).Run();
                    }

                    previousReader = r2r;
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Error: " + e.ToString());
                if (e is ArgumentException)
                {
                    Console.WriteLine();
                    Console.WriteLine(syntax.GetHelpText());
                }
                if (_xml)
                {
                    XmlDocument document = new XmlDocument();
                    XmlNode node = document.CreateNode("element", "Error", "");
                    node.InnerText = e.Message;
                    document.AppendChild(node);
                    if (_writer != null)
                    {
                        document.Save(_writer);
                    }
                }
                return 1;
            }
            finally
            {
                if (disassembler != null)
                {
                    disassembler.Dispose();
                }
                // close output stream
                _writer.Close();
            }

            return 0;
        }

        public static int Main(string[] args)
        {
            try
            {
                return new R2RDump().Run(args);
            }
            catch (Exception e)
            {
                Console.WriteLine("Error: " + e.ToString());
                return 1;
            }
        }
    }
}


text:
import React from 'react';
import Table from '../Table';
import { mount } from 'enzyme';

describe('FormWizard', () => {
  describe('Renders as expected', () => {
    const wrapper = mount(<Table withBorder></Table>);

    it('renders class as expected', () => {
      expect(wrapper.exists('.wfp--table')).toBe(true);
    });

    it('renders class on withBorder prop', () => {
      expect(wrapper.exists('.wfp--table--with-border')).toBe(true);
    });

    it('renders prop as expected', () => {
      expect(wrapper.props().withBorder).toBe(true);
    });
  });
});

redpajama_set_name: RedPajamaGithub


text:
package pact

import (
	"fmt"
	"net/http"
	"testing"

	"github.com/SEEK-Jobs/pact-go/provider"
)

func Test_ProviderService_CanReigsterInteraction_WithValidData(t *testing.T) {
	ps := newMockProviderService(&BuilderConfig{})

	header := make(http.Header)
	header.Add("content-type", "payload/nuclear")
	request := provider.NewJSONRequest("POST", "/luke", "action=attack", header)
	request.SetBody(`{ "simulation": false, "target": "Death Star" }`)

	response := provider.NewJSONResponse(200, nil)

	if err := ps.Given("Force is strong with Luke Skywalker").
		UponReceiving("Destroy death star").
		With(*request).
		WillRespondWith(*response); err != nil {
		t.Error(err)
	}
}

func Test_ProviderService_CannotReigsterInteraction_WithInvalidData(t *testing.T) {
	ps := newMockProviderService(&BuilderConfig{})

	request := provider.NewJSONRequest("POST", "/luke", "action=attack", nil)
	response := provider.NewJSONResponse(200, nil)

	if err := ps.Given("Force is strong with Luke Skywalker").
		With(*request).
		WillRespondWith(*response); err == nil {
		t.Error("Should not be able to register interaction with empty description")
	}
}

func Test_ProviderService_CannotReigster_DuplicateInteraction(t *testing.T) {
	ps := newMockProviderService(&BuilderConfig{})

	request := provider.NewJSONRequest("POST", "/luke", "action=attack", nil)
	response := provider.NewJSONResponse(200, nil)

	if err := ps.Given("Force is strong with Luke Skywalker").
		UponReceiving("Destroy death star").
		With(*request).
		WillRespondWith(*response); err != nil {
		t.Error(err)
	}

	if err := ps.Given("Force is strong with Luke Skywalker").
		UponReceiving("Destroy death star").
		With(*request).
		WillRespondWith(*response); err == nil {
		t.Error("Should not allow to register duplicate interaction")
	}

}

func Test_ProviderService_CanReigsterDuplicateInteraction_InDifferentScope(t *testing.T) {
	ps := newMockProviderService(&BuilderConfig{})

	request := provider.NewJSONRequest("POST", "/luke", "action=attack", nil)
	response := provider.NewJSONResponse(200, nil)

	if err := ps.Given("Force is strong with Luke Skywalker").
		UponReceiving("Destroy death star").
		With(*request).
		WillRespondWith(*response); err != nil {
		t.Error(err)
	}

	ps.ClearInteractions()

	if err := ps.Given("Force is strong with Luke Skywalker").
		UponReceiving("Destroy death star").
		With(*request).
		WillRespondWith(*response); err != nil {
		t.Error(err)
	}

}

func Test_ProviderService_CanResetTransientState_AfterRegistration(t *testing.T) {
	ps := newMockProviderService(&BuilderConfig{})

	header := make(http.Header)
	header.Add("content-type", "payload/nuclear")
	request := provider.NewJSONRequest("POST", "/luke", "action=attack", header)
	request.SetBody(`{ "simulation": false, "target": "Death Star" }`)

	response := provider.NewJSONResponse(200, nil)

	if err := ps.Given("Force is strong with Luke Skywalker").
		UponReceiving("Destroy death star").
		With(*request).
		WillRespondWith(*response); err != nil {
		t.Error(err)
	}

	if ps.state != "" || ps.description != "" || ps.providerRequest != nil || ps.providerResponse != nil {
		t.Error("Provider services transient state is not cleared after interaction registration")
	}
}

func Test_ProviderService_CanClearInteractions(t *testing.T) {
	ps := newMockProviderService(&BuilderConfig{})

	request := provider.NewJSONRequest("POST", "/luke", "action=attack", nil)
	response := provider.NewJSONResponse(200, nil)

	if err := ps.Given("Force is strong with Luke Skywalker").
		UponReceiving("Destroy death star").
		With(*request).
		WillRespondWith(*response); err != nil {
		t.Error(err)
	}

	ps.ClearInteractions()

	if !ps.service.IsTestScopeClear() {
		t.Error("Interactions have not been cleared")
	}
	if ps.state != "" || ps.description != "" || ps.providerRequest != nil || ps.providerResponse != nil {
		t.Error("Provider services transient state is not cleared after interaction registration")
	}
}

func Test_ProviderService_CanVerifyInteractions(t *testing.T) {
	ps := newMockProviderService(&BuilderConfig{})

	request := provider.NewJSONRequest("POST", "/luke", "action=attack", nil)
	response := provider.NewJSONResponse(200, nil)

	if err := ps.Given("Force is strong with Luke Skywalker").
		UponReceiving("Destroy death star").
		With(*request).
		WillRespondWith(*response); err != nil {
		t.Error(err)
	}

	url := ps.start()
	defer ps.stop()

	client := &http.Client{}
	if req, err := http.NewRequest(request.Method, fmt.Sprintf("%s%s?%s", url, request.Path, request.Query), nil); err != nil {
		t.Error(err)
		t.FailNow()
	} else if _, err := client.Do(req); err != nil {
		t.Error(err)
		t.FailNow()
	} else if err := ps.VerifyInteractions(); err != nil {
		t.Error(err)
		t.FailNow()
	}
}


text:
package com.example.kb.clearsky.model.api_specific;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class City {

    @SerializedName("id")
    @Expose
    private Integer id;

    @SerializedName("name")
    @Expose
    private String name;

    @SerializedName("coord")
    @Expose
    private Coordinates coordinates;

    @SerializedName("country")
    @Expose
    private String country;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Coordinates getCoordinates() {
        return coordinates;
    }

    public void setCoordinates(Coordinates coordinates) {
        this.coordinates = coordinates;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace LocalTravelInfo.Model
{
    public class JobStatusResult
    {
        public Job Job { get; set; }
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>statsmodels.genmod.families.family.Binomial.starting_mu — statsmodels 0.8.0 documentation</title>

    <link rel="stylesheet" href="../_static/nature.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />

    <link rel="shortcut icon" href="../_static/statsmodels_hybi_favico.ico"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="prev" title="statsmodels.genmod.families.family.Binomial.resid_dev" href="statsmodels.genmod.families.family.Binomial.resid_dev.html" />
<link rel="stylesheet" href="../_static/examples.css" type="text/css" />
<link rel="stylesheet" href="../_static/facebox.css" type="text/css" />

Navigation

          index

          modules |

          previous |

Install
  |

Support
  |

Bugs
  |

Develop
  |

Examples
  |

FAQ
  |

Generalized Linear Models |

statsmodels.genmod.families.family.Binomial |

statsmodels.genmod.families.family.Binomial.starting_mu¶

Binomial.starting_mu(y)[source]¶

The starting values for the IRLS algorithm for the Binomial family.
A good choice for the binomial family is

Previous topic

statsmodels.genmod.families.family.Binomial.resid_dev

This Page

Show Source

Quick search

    <form class="search" action="../search.html" method="get">

<input type="text" name="q" />

<input type="submit" value="Go" />

      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

        © Copyright 2009-2017, Josef Perktold, Skipper Seabold, Jonathan Taylor, statsmodels-developers.
      Created using Sphinx 1.5.3.


text:
package org.apache.wss4j.policy.model;

import org.apache.neethi.Assertion;
import org.apache.neethi.Policy;
import org.apache.wss4j.policy.SPConstants;
import org.w3c.dom.Element;

import javax.xml.namespace.QName;
import java.util.*;

public class KerberosToken extends AbstractToken {

    public enum ApReqTokenType {
        WssKerberosV5ApReqToken11,
        WssGssKerberosV5ApReqToken11;

        private static final Map<String, ApReqTokenType> LOOKUP = new HashMap<>();

        static {
            for (ApReqTokenType u : EnumSet.allOf(ApReqTokenType.class)) {
                LOOKUP.put(u.name(), u);
            }
        }

        public static ApReqTokenType lookUp(String name) {
            return LOOKUP.get(name);
        }
    }

    private boolean requireKeyIdentifierReference;

    private ApReqTokenType apReqTokenType;

    public KerberosToken(SPConstants.SPVersion version, SPConstants.IncludeTokenType includeTokenType,
                         Element issuer, String issuerName, Element claims, Policy nestedPolicy) {
        super(version, includeTokenType, issuer, issuerName, claims, nestedPolicy);

        parseNestedPolicy(nestedPolicy, this);
    }

    @Override
    public QName getName() {
        return getVersion().getSPConstants().getKerberosToken();
    }

    @Override
    protected AbstractSecurityAssertion cloneAssertion(Policy nestedPolicy) {
        return new KerberosToken(getVersion(), getIncludeTokenType(), getIssuer(),
                                 getIssuerName(), getClaims(), nestedPolicy);
    }

    protected void parseNestedPolicy(Policy nestedPolicy, KerberosToken kerberosToken) {
        Iterator<List<Assertion>> alternatives = nestedPolicy.getAlternatives();
        //we just process the first alternative
        //this means that if we have a compact policy only the first alternative is visible
        //in contrary to a normalized policy where just one alternative exists
        if (alternatives.hasNext()) {
            List<Assertion> assertions = alternatives.next();
            for (int i = 0; i < assertions.size(); i++) {
                Assertion assertion = assertions.get(i);
                String assertionName = assertion.getName().getLocalPart();
                String assertionNamespace = assertion.getName().getNamespaceURI();
                DerivedKeys derivedKeys = DerivedKeys.lookUp(assertionName);
                if (derivedKeys != null) {
                    if (kerberosToken.getDerivedKeys() != null) {
                        throw new IllegalArgumentException(SPConstants.ERR_INVALID_POLICY);
                    }
                    kerberosToken.setDerivedKeys(derivedKeys);
                    continue;
                }
                QName requireKeyIdentifierRef =
                    getVersion().getSPConstants().getRequireKeyIdentifierReference();
                if (requireKeyIdentifierRef.getLocalPart().equals(assertionName)
                    && requireKeyIdentifierRef.getNamespaceURI().equals(assertionNamespace)) {
                    if (kerberosToken.isRequireKeyIdentifierReference()) {
                        throw new IllegalArgumentException(SPConstants.ERR_INVALID_POLICY);
                    }
                    kerberosToken.setRequireKeyIdentifierReference(true);
                    continue;
                }
                ApReqTokenType apReqTokenType = ApReqTokenType.lookUp(assertionName);
                if (apReqTokenType != null) {
                    if (kerberosToken.getApReqTokenType() != null) {
                        throw new IllegalArgumentException(SPConstants.ERR_INVALID_POLICY);
                    }
                    kerberosToken.setApReqTokenType(apReqTokenType);
                    continue;
                }
            }
        }
    }

    public boolean isRequireKeyIdentifierReference() {
        return requireKeyIdentifierReference;
    }

    protected void setRequireKeyIdentifierReference(boolean requireKeyIdentifierReference) {
        this.requireKeyIdentifierReference = requireKeyIdentifierReference;
    }

    public ApReqTokenType getApReqTokenType() {
        return apReqTokenType;
    }

    protected void setApReqTokenType(ApReqTokenType apReqTokenType) {
        this.apReqTokenType = apReqTokenType;
    }
}


text:
package com.mydomain.smartcrop;

import static org.junit.Assert.assertEquals;
import ij.ImagePlus;

import java.awt.Rectangle;
import java.awt.image.BufferedImage;

import org.junit.Before;
import org.junit.Test;

import com.mydomain.smartcrop.procedure.RegularProcedure;
import com.mydomain.smartcrop.utils.IOImage;

public class BorderIdentifierTest {

    private BorderIdentifier borderId;
    private ImagePlus image;

    @Before
    public void setUp() throws Exception {
        String path = "test/resources/1.png";
        BufferedImage imageB = IOImage.getImage(path);
        image = new ImagePlus("", imageB);
        borderId = new BorderIdentifier(new RegularProcedure());
    }

    @Test
    public void testExecute() {
        Rectangle rec = borderId.execute(image);
        assertEquals(rec.x, 33);
        assertEquals(rec.y, 34);
        assertEquals(rec.height, 274);
        assertEquals(rec.width, 195);
    }

}


text:
package org.faudroids.doublestacks.ui;

public enum BlockColor {

	BLUE,
	YELLOW,
	RED

}


text:
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';

import { Board, BoardCategory } from '../models/index';
import { BaseService } from "./base.service";

@Injectable()
export class BoardCategoryService extends BaseService {
    constructor(private http: Http) {
        super();
    }

    //getAll() {
    //    return this.http.get('/api/v1/boards', this.jwt()).map((response: Response) => response.json());
    //}

    //getById(id: number) {
    //    return this.http.get('/api/users/' + id, this.jwt()).map((response: Response) => response.json());
    //}

    create(board: Board, boardCategory: BoardCategory) {
        var requestObj = {
            boardId: board.boardId,
            name: boardCategory.name
        };

        return this.http.post('/api/v1/boardCategories', JSON.stringify(requestObj), this.jwt()).map((response: Response) => response.json());
    }

    //update(user: User) {
    //    return this.http.put('/api/users/' + user.id, user, this.jwt()).map((response: Response) => response.json());
    //}

    //delete(id: number) {
    //    return this.http.delete('/api/users/' + id, this.jwt()).map((response: Response) => response.json());
    //}
}


text:
/* Scheduler includes. */
#include "FreeRTOS.h"
#include "task.h"

/* Demo includes. */
#include "IntQueueTimer.h"
#include "IntQueue.h"

/* Hardware includes. */
#include "lpc11xx.h"

/* The two timer frequencies. */
#define tmrTIMER_2_FREQUENCY	( 2000UL )
#define tmrTIMER_3_FREQUENCY	( 2001UL )

/* The priorities for the two timers.  Note that a priority of 0 is the highest
possible on Cortex-M devices. */
#define tmrMAX_PRIORITY				( 0UL )
#define trmSECOND_HIGHEST_PRIORITY ( tmrMAX_PRIORITY + 1 )

void vInitialiseTimerForIntQueueTest( void )
{
	/* Enable AHB clock for GPIO and 16-bit timers. */
	LPC_SYSCON->SYSAHBCLKCTRL |= ( 7 << 6 );

	/* Interrupt and reset on MR0 match. */
	LPC_TMR16B0->MCR = 0x03;
	LPC_TMR16B1->MCR = 0x03;

	/* Configure the frequency of the interrupt generated by MR0 matches. */
	LPC_TMR16B0->MR0 = SystemCoreClock / tmrTIMER_2_FREQUENCY;
	LPC_TMR16B1->MR0 = SystemCoreClock / tmrTIMER_3_FREQUENCY;

	/* Don't generate interrupts until the scheduler has been started.
	Interrupts will be automatically enabled when the first task starts
	running. */
	taskDISABLE_INTERRUPTS();

	/* Set the timer interrupts to be above the kernel.  The interrupts are
	assigned different priorities so they nest with each other. */
	NVIC_SetPriority( TIMER_16_0_IRQn, trmSECOND_HIGHEST_PRIORITY );
	NVIC_SetPriority( TIMER_16_1_IRQn, tmrMAX_PRIORITY );

	/* Enable the timer interrupts. */
	NVIC_EnableIRQ( TIMER_16_0_IRQn );
	NVIC_EnableIRQ( TIMER_16_1_IRQn );

	/* Start the timers. */
	LPC_TMR16B0->TCR = 0x01;
	LPC_TMR16B1->TCR = 0x01;
}
/*-----------------------------------------------------------*/

void TIMER16_0_IRQHandler(void)
{
	/* Clear the interrupt. */
	LPC_TMR16B0->IR = LPC_TMR16B0->IR;

	/* Call the  standard demo int queue timer function for this first timer. */
	portEND_SWITCHING_ISR( xFirstTimerHandler() );
}
/*-----------------------------------------------------------*/

void TIMER16_1_IRQHandler(void)
{
	/* Clear the interrupt. */
	LPC_TMR16B1->IR = LPC_TMR16B1->IR;

	/* Call the standard demo int queue timer function for this second timer. */
	portEND_SWITCHING_ISR( xSecondTimerHandler() );
}
/*-----------------------------------------------------------*/


text:
package main

import (
	"fmt"
	"github.com/docopt/docopt-go"
	"github.com/fatih/color"
	"github.com/wjdp/htmltest/htmltest"
	"github.com/wjdp/htmltest/output"
	"gopkg.in/yaml.v2"
	"io/ioutil"
	"os"
	"path"
	"strconv"
	"strings"
	"time"
)

const cmdSeparator string = "========================================================================"

var (
	version  string
	fileMode bool
)

func main() {
	usage := `htmltest - Test generated HTML for problems
           https://github.com/wjdp/htmltest

Usage:
  htmltest [options] [<path>]
  htmltest -v --version
  htmltest -h --help

Options:
  <path>                       Path to directory or file to test, if omitted we
                               attempt to read from .htmltest.yml.
  -c FILE, --conf FILE         Custom path to config file.
  -h, --help                   Show this text.
  -l LEVEL, --log-level LEVEL  Logging level, 0-3: debug, info, warning, error.
  -s, --skip-external          Skip external link checks, may shorten execution
                               time considerably.
  -v, --version                Show version and build time.
`
	versionText := "htmltest " + version
	arguments, _ := docopt.Parse(usage, nil, true, versionText, false)

	// fmt.Println(arguments)

	var options map[string]interface{}

	// Check for NO_COLOR environment variable and turn off colourization if
	// it is set.
	// See https://no-color.org/
	color.NoColor = os.Getenv("NO_COLOR") != ""

	if arguments["--conf"] != nil {
		// Config file specified
		options = parseConfFile(arguments, arguments["--conf"].(string), true)
	} else if arguments["<path>"] != nil {
		// Path specified
		options = parseCLIArgs(arguments)
	} else {
		// Other
		options = parseConfFile(arguments, ".htmltest.yml", false)
	}

	// Pass version into options
	options["Version"] = strings.TrimLeft(version, "v")

	exitCode := run(options)
	os.Exit(exitCode)
}

type optsMap map[string]interface{}

func parseConfFile(arguments map[string]interface{}, path string, explicit bool) optsMap {
	yamlFile, err := ioutil.ReadFile(path)

	if os.IsNotExist(err) {
		if explicit {
			output.AbortWith("Cannot access config file '" + path +
				"', no such file.")
		} else {
			output.AbortWith(`No path provided & the default config .htmltest.yml does not exist.
See htmltest -h for usage.`)
		}
	}
	output.CheckErrorGeneric(err)

	var optsConf optsMap
	err = yaml.Unmarshal(yamlFile, &optsConf)
	output.CheckErrorGeneric(err)

	// Override or append config options with any specified in CLI args
	augmentWithCLIArgs(optsConf, arguments)

	return optsConf
}

// Wrapper for augmentWithCLIArgs when you don't already have an options map.
func parseCLIArgs(arguments map[string]interface{}) optsMap {
	options := optsMap{}
	augmentWithCLIArgs(options, arguments)
	return options
}

// Override or append to the options map with CLI args.
func augmentWithCLIArgs(options optsMap, arguments map[string]interface{}) {
	// Deal with cli arguments

	// We've been given a path, check it exists and decide if it's a single
	// file or a directory of files to check.
	if arguments["<path>"] != nil {
		// Open <path>
		f, err := os.Open(path.Clean(arguments["<path>"].(string)))
		if os.IsNotExist(err) {
			output.AbortWith("Cannot access '" + arguments["<path>"].(string) +
				"', no such file or directory.")
		}
		output.CheckErrorGeneric(err)
		defer f.Close()

		// Get FileInfo, (scan for details)
		fi, err := f.Stat()
		output.CheckErrorPanic(err)

		if fi.IsDir() {
			// We have a directory
			options["DirectoryPath"] = path.Clean(arguments["<path>"].(string))
			fileMode = false
		} else {
			// We have a file
			options["DirectoryPath"] = path.Dir(arguments["<path>"].(string))
			options["FilePath"] = path.Base(arguments["<path>"].(string))
			fileMode = true
		}

	}

	if arguments["--log-level"] != nil {
		if ll, err := strconv.Atoi(arguments["--log-level"].(string)); err == nil && ll >= 0 {
			options["LogLevel"] = ll
		} else {
			output.AbortWith("--log-level must be a positive integer")
		}
	}

	if arguments["--skip-external"].(bool) {
		output.Warn("Skipping the checking of external links.")
		options["CheckExternal"] = false
	}

}

func run(options optsMap) int {
	timeStart := time.Now()

	fmt.Println("htmltest started at", timeStart.Format("03:04:05"), "on", options["DirectoryPath"])
	fmt.Println(cmdSeparator)

	// Run htmltest
	hT, err := htmltest.Test(options)

	if err != nil {
		// Couldn't even run, dump error and exit
		output.AbortWith(err)
	}

	timeEnd := time.Now()
	numErrors := hT.CountErrors()

	if numErrors == 0 {
		color.Set(color.FgHiGreen)
		fmt.Println("✔✔✔ passed in", timeEnd.Sub(timeStart))
		if !fileMode {
			fmt.Println("tested", hT.CountDocuments(), "documents")
		}
		color.Unset()
		return 0
	}

	color.Set(color.FgHiRed)
	fmt.Println(cmdSeparator)
	fmt.Println("✘✘✘ failed in", timeEnd.Sub(timeStart))
	if fileMode {
		fmt.Println(numErrors, "errors")
	} else {
		fmt.Println(numErrors, "errors in", hT.CountDocuments(), "documents")
	}
	color.Unset()
	return 1

}


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ElectricCurrent.cs" company="Hukano">
// Copyright (c) Hukano. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Sundew.Quantities.Serialization.Poco;

using Sundew.Quantities.Core;

/// <summary>
/// Represents <see cref="Sundew.Quantities.ElectricCurrent"/> as a serializable type.
/// </summary>
public class ElectricCurrent : SerializableQuantity<Quantities.ElectricCurrent>
{
    /// <summary>
    /// Initializes a new instance of the <see cref="ElectricCurrent"/> class.
    /// </summary>
    public ElectricCurrent()
    {
    }

    /// <summary>
    /// Initializes a new instance of the <see cref="ElectricCurrent" /> class.
    /// </summary>
    /// <param name="quantity">The quantity.</param>
    public ElectricCurrent(IQuantity quantity)
        : base(quantity)
    {
    }

    /// <summary>
    /// Converts the serializable electric current to a quantity electric current.
    /// </summary>
    /// <returns>A <see cref="Sundew.Quantities.ElectricCurrent"/>.</returns>
    public override Quantities.ElectricCurrent ToQuantity()
    {
        return new Quantities.ElectricCurrent(this.Value, this.GetUnit());
    }
}


text:
/*
 * Copyright (c) 2009 The Khronos Group Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this
 * software and /or associated documentation files (the "Materials "), to deal in the
 * Materials without restriction, including without limitation the rights to use, copy,
 * modify, merge, publish, distribute, sublicense, and/or sell copies of the Materials,
 * and to permit persons to whom the Materials are furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be included
 * in all copies or substantial portions of the Materials.
 *
 * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE MATERIALS OR THE USE OR OTHER DEALINGS IN THE
 * MATERIALS.
 */

#define LOG_NDEBUG 0
#define LOG_TAG "slesTestPlayUri"

#include <utils/Log.h>
#include <getopt.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/time.h>
#include <gtest/gtest.h>
#include <SLES/OpenSLES.h>

#define MAX_NUMBER_INTERFACES 3
#define MAX_NUMBER_OUTPUT_DEVICES 6

//The expected playback duration
const int MP3_DURATION = 71030; //71 secs

//-----------------------------------------------------------------
/* Checks for error. If any errors exit the application! */
void CheckErr( SLresult res )
{
    if ( res != SL_RESULT_SUCCESS )  {
        fprintf(stderr, "%u SL failure, exiting\n", res);
        //Fail the test case
        ASSERT_TRUE(false);
    }
}

//-----------------------------------------------------------------
/* PrefetchStatusItf callback for an audio player */
void PrefetchEventCallback( SLPrefetchStatusItf caller,  void *pContext, SLuint32 event)
{
    SLpermille level = 0;
    (*caller)->GetFillLevel(caller, &level);
    SLuint32 status;
    fprintf(stdout, "\t\tPrefetchEventCallback: received event %u\n", event);
    (*caller)->GetPrefetchStatus(caller, &status);
    if ((event & (SL_PREFETCHEVENT_STATUSCHANGE|SL_PREFETCHEVENT_FILLLEVELCHANGE))
            && (level == 0) && (status == SL_PREFETCHSTATUS_UNDERFLOW)) {
        fprintf(stderr, "\t\tPrefetchEventCallback: Error while prefetching data, exiting\n");
        ASSERT_TRUE(false);
    }
    if (event & SL_PREFETCHEVENT_FILLLEVELCHANGE) {
        fprintf(stdout, "\t\tPrefetchEventCallback: Buffer fill level is = %d\n", level);
    }
    if (event & SL_PREFETCHEVENT_STATUSCHANGE) {
        fprintf(stdout, "\t\tPrefetchEventCallback: Prefetch Status is = %u\n", status);
    }

}

//-----------------------------------------------------------------

/* Play some music from a URI  */
void TestPlayUri( SLObjectItf sl, const char* path)
{
    SLEngineItf                EngineItf;

    SLint32                    numOutputs = 0;
    SLuint32                   deviceID = 0;

    SLresult                   res;

    SLDataSource               audioSource;
    SLDataLocator_URI          uri;
    SLDataFormat_MIME          mime;

    SLDataSink                 audioSink;
    SLDataLocator_OutputMix    locator_outputmix;

    SLObjectItf                player;
    SLPlayItf                  playItf;
    SLVolumeItf                volItf;
    SLPrefetchStatusItf        prefetchItf;

    SLObjectItf                OutputMix;

    SLboolean required[MAX_NUMBER_INTERFACES];
    SLInterfaceID iidArray[MAX_NUMBER_INTERFACES];

    /* Get the SL Engine Interface which is implicit */
    res = (*sl)->GetInterface(sl, SL_IID_ENGINE, (void*)&EngineItf);
    CheckErr(res);

    /* Initialize arrays required[] and iidArray[] */
    for (int i=0 ; i < MAX_NUMBER_INTERFACES ; i++) {
        required[i] = SL_BOOLEAN_FALSE;
        iidArray[i] = SL_IID_NULL;
    }

    // Set arrays required[] and iidArray[] for VOLUME and PREFETCHSTATUS interface
    required[0] = SL_BOOLEAN_TRUE;
    iidArray[0] = SL_IID_VOLUME;
    required[1] = SL_BOOLEAN_TRUE;
    iidArray[1] = SL_IID_PREFETCHSTATUS;
    // Create Output Mix object to be used by player
    res = (*EngineItf)->CreateOutputMix(EngineItf, &OutputMix, 0,
            iidArray, required); CheckErr(res);

    // Realizing the Output Mix object in synchronous mode.
    res = (*OutputMix)->Realize(OutputMix, SL_BOOLEAN_FALSE);
    CheckErr(res);

    /* Setup the data source structure for the URI */
    uri.locatorType = SL_DATALOCATOR_URI;
    uri.URI         =  (SLchar*) path;
    mime.formatType    = SL_DATAFORMAT_MIME;
    mime.mimeType      = (SLchar*)NULL;
    mime.containerType = SL_CONTAINERTYPE_UNSPECIFIED;

    audioSource.pFormat      = (void *)&mime;
    audioSource.pLocator     = (void *)&uri;

    /* Setup the data sink structure */
    locator_outputmix.locatorType   = SL_DATALOCATOR_OUTPUTMIX;
    locator_outputmix.outputMix    = OutputMix;
    audioSink.pLocator           = (void *)&locator_outputmix;
    audioSink.pFormat            = NULL;

    /* Create the audio player */
    res = (*EngineItf)->CreateAudioPlayer(EngineItf, &player,
            &audioSource, &audioSink, 2, iidArray, required); CheckErr(res);

    /* Realizing the player in synchronous mode. */
    res = (*player)->Realize(player, SL_BOOLEAN_FALSE); CheckErr(res);

    /* Get interfaces */
    res = (*player)->GetInterface(player, SL_IID_PLAY, (void*)&playItf);
    CheckErr(res);

    res = (*player)->GetInterface(player, SL_IID_VOLUME,  (void*)&volItf);
    CheckErr(res);

    res = (*player)->GetInterface(player, SL_IID_PREFETCHSTATUS, (void*)&prefetchItf);
    CheckErr(res);
    res = (*prefetchItf)->RegisterCallback(prefetchItf, PrefetchEventCallback, &prefetchItf);
    CheckErr(res);
    res = (*prefetchItf)->SetCallbackEventsMask(prefetchItf,
            SL_PREFETCHEVENT_FILLLEVELCHANGE | SL_PREFETCHEVENT_STATUSCHANGE);

    /* Display duration */
    SLmillisecond durationInMsec = SL_TIME_UNKNOWN;
    res = (*playItf)->GetDuration(playItf, &durationInMsec);
    CheckErr(res);

    /* Set the player volume */
    res = (*volItf)->SetVolumeLevel( volItf, -300);
    CheckErr(res);

    /* Play the URI */
    /*     first cause the player to prefetch the data */
    res = (*playItf)->SetPlayState( playItf, SL_PLAYSTATE_PAUSED );
    CheckErr(res);

    /*     wait until there's data to play */
    //SLpermille fillLevel = 0;
    SLuint32 prefetchStatus = SL_PREFETCHSTATUS_UNDERFLOW;
    SLuint32 timeOutIndex = 100; // 10s
    while ((prefetchStatus != SL_PREFETCHSTATUS_SUFFICIENTDATA) && (timeOutIndex > 0)) {
        usleep(100 * 1000);
        (*prefetchItf)->GetPrefetchStatus(prefetchItf, &prefetchStatus);
        timeOutIndex--;
    }

    if (timeOutIndex == 0) {
        fprintf(stderr, "Error: Failed to prefetch data in time, exiting\n");
        ASSERT_TRUE(false);
       // goto destroyRes;
    }

    /* Display duration again, */
    res = (*playItf)->GetDuration(playItf, &durationInMsec);
    CheckErr(res);
    if (durationInMsec == SL_TIME_UNKNOWN) {
        fprintf(stderr, "Error: GetDuration returned SL_TIME_UNKNOWN (after prefetch completed)\n");
        ASSERT_TRUE(false);
    }
    SLint32 durationDiffMsec = durationInMsec - MP3_DURATION;
    if (durationDiffMsec < 0) { durationDiffMsec *= -1; }
    if (durationDiffMsec > (MP3_DURATION/20)) {
        fprintf(stderr, "Error: GetDuration returned %d, more than 5percent off from expected %d\n",
                durationInMsec, MP3_DURATION);
        ASSERT_TRUE(false);
    }

    res = (*playItf)->SetPlayState( playItf, SL_PLAYSTATE_PLAYING );
    CheckErr(res);

    /* Play for the song duration*/
    usleep(MP3_DURATION * 1000);

    /* Validate the play position*/
    SLmillisecond currentPositionInMsec = SL_TIME_UNKNOWN;
           res = (*playItf)->GetPosition(playItf, &currentPositionInMsec);
           CheckErr(res);
    if (currentPositionInMsec == SL_TIME_UNKNOWN) {
      fprintf(stderr, "Error: GetPosition returns SL_TIME_UNKNOWN after expected duration\n");
      ASSERT_TRUE(false);
    } else if ( currentPositionInMsec <= 0 ||
        currentPositionInMsec > (MP3_DURATION * 1.1) ){
        fprintf(stderr, "Error: GetPosition returns %i, should be expected duration for test\n",
                (int) currentPositionInMsec);
        ASSERT_TRUE(false);
    }

    /* Make sure player is stopped */
    res = (*playItf)->SetPlayState(playItf, SL_PLAYSTATE_STOPPED);
    CheckErr(res);

destroyRes:

    /* Destroy the player */
    (*player)->Destroy(player);

    /* Destroy Output Mix object */
    (*OutputMix)->Destroy(OutputMix);

    fprintf(stdout, "End of test reached\n");
}

// The fixture for testing class MimeUri
class MimeUri: public ::testing::Test {
public:
    SLresult res;
    SLObjectItf sl;

protected:
    MimeUri() {
        // You can do set-up work for each test here.
        SLEngineOption EngineOption[] = { { (SLuint32) SL_ENGINEOPTION_THREADSAFE,
            (SLuint32) SL_BOOLEAN_TRUE } };

        res = slCreateEngine(&sl, 1, EngineOption, 0, NULL, NULL);
        CheckErr(res);

        /* Realizing the SL Engine in synchronous mode. */
        res = (*sl)->Realize(sl, SL_BOOLEAN_FALSE);
        CheckErr(res);
    }

    virtual ~MimeUri() {
        // You can do clean-up work that doesn't throw exceptions here.
        (*sl)->Destroy(sl);
    }

    virtual void SetUp() {
        // Code here will be called immediately after the constructor (right
        // before each test).

    }

    virtual void TearDown() {
        // Code here will be called immediately after each test (right
        // before the destructor).

    }
};

TEST_F(MimeUri, testPlayAbsPath){
    TestPlayUri(sl, "/sdcard/media_api/music/MP3_256kbps_2ch.mp3");
}

TEST_F(MimeUri, testPlayfilePath){
    TestPlayUri(sl, "file:///sdcard/media_api/music/MP3_256kbps_2ch.mp3");
}

//-----------------------------------------------------------------
int main(int argc, char **argv)
{
    testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}


text:
package com.taobao.weex.ui.component;

import com.taobao.weex.WXSDKInstance;

/**
 * Created by sospartan on 7/27/16.
 */
public class TestComponent extends WXDiv{
  public TestComponent(WXSDKInstance instance, WXDomObject dom, WXVContainer parent, String instanceId, boolean isLazy) {
    super(instance, dom, parent, instanceId, isLazy);
  }

  public TestComponent(WXSDKInstance instance, WXDomObject dom, WXVContainer parent) {
    super(instance, dom, parent);
  }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<form xmlns="http://jelix.org/ns/forms/1.1">

    <input ref="login" required="true" maxlength="150">
        Nom d'utilisateur
        <help>Pour l'accès à l'administration</help>
    </input>

    <input ref="email" required="true" maxlength="150">
        Adresse email
        <help>Associée à votre compte</help>
    </input>

    <input ref="return_path" required="true" maxlength="150">
        Email des rebonds
        <help>Email par défaut pour la gestion des rebonds (bounces)</help>
    </input>

    <input ref="batch_quota" required="true" defaultvalue="10">
        Nombre de mail par lot
    </input>

    <input ref="pause_quota" required="true" defaultvalue="10">
        Durée de la pause entre chaque lot (en secondes)
        <help>Durée en seconde</help>
    </input>

    <input ref="password" required="true" maxlength="150">
        Mot de passe
        <help>Mot de passe de plus de 6 caractères</help>
    </input>

    <submit ref="_submit">
        Terminer l'installation
    </submit>

</form>


text:
import sys
import unittest
import libsbml

class TestEventAssignment_newSetters(unittest.TestCase):

  global E
  E = None

  def setUp(self):
    self.E = libsbml.EventAssignment(2,4)
    if (self.E == None):
      pass
    pass

  def tearDown(self):
    _dummyList = [ self.E ]; _dummyList[:] = []; del _dummyList
    pass

  def test_EventAssignment_setMath1(self):
    math = libsbml.parseFormula("2 * k")
    i = self.E.setMath(math)
    self.assert_( i == libsbml.LIBSBML_OPERATION_SUCCESS )
    self.assert_( self.E.getMath() != math )
    self.assertEqual( True, self.E.isSetMath() )
    i = self.E.setMath(None)
    self.assert_( i == libsbml.LIBSBML_OPERATION_SUCCESS )
    self.assert_( self.E.getMath() == None )
    self.assertEqual( False, self.E.isSetMath() )
    _dummyList = [ math ]; _dummyList[:] = []; del _dummyList
    pass

  def test_EventAssignment_setMath2(self):
    math = libsbml.ASTNode(libsbml.AST_DIVIDE)
    i = self.E.setMath(math)
    self.assert_( i == libsbml.LIBSBML_INVALID_OBJECT )
    self.assertEqual( False, self.E.isSetMath() )
    _dummyList = [ math ]; _dummyList[:] = []; del _dummyList
    pass

  def test_EventAssignment_setVariable1(self):
    id =  "1e1";
    i = self.E.setVariable(id)
    self.assert_( i == libsbml.LIBSBML_INVALID_ATTRIBUTE_VALUE )
    self.assertEqual( False, self.E.isSetVariable() )
    pass

  def test_EventAssignment_setVariable2(self):
    id =  "e1";
    i = self.E.setVariable(id)
    self.assert_( i == libsbml.LIBSBML_OPERATION_SUCCESS )
    self.assert_(( id == self.E.getVariable() ))
    self.assertEqual( True, self.E.isSetVariable() )
    i = self.E.setVariable("")
    self.assert_( i == libsbml.LIBSBML_OPERATION_SUCCESS )
    self.assertEqual( False, self.E.isSetVariable() )
    pass

def suite():
  suite = unittest.TestSuite()
  suite.addTest(unittest.makeSuite(TestEventAssignment_newSetters))

  return suite

if __name__ == "__main__":
  if unittest.TextTestRunner(verbosity=1).run(suite()).wasSuccessful() :
    sys.exit(0)
  else:
    sys.exit(1)


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.psalgs.queue;

import java.util.LinkedList;
import java.util.Queue;

/**
 *
 * @author djoshi
 */
public class Itr_HeightBT {

    static class tNode {

        int data;
        tNode left, right;

        tNode(int d) {
            data = d;
            left = right = null;
        }
    }

    tNode root;

    private int treeHeight(tNode node) {
        if (node == null) {
            return 0;
        }

        int height = 0;
        Queue<tNode> queue = new LinkedList<>();
        queue.add(node);

        while (!queue.isEmpty()) {

            int noOfNodes = queue.size();

            height++;

            while (noOfNodes > 0) {
                tNode curr = queue.poll();

                if (curr.left != null) {
                    queue.add(curr.left);
                }

                if (curr.right != null) {
                    queue.add(curr.right);
                }
                noOfNodes--;
            }
        }

        return height;
    }

    public static void main(String args[]) {
        Itr_HeightBT tree = new Itr_HeightBT();
        // Let us create a binary tree shown in above diagram
        tree.root = new tNode(1);
        tree.root.left = new tNode(2);
        tree.root.right = new tNode(3);
        tree.root.left.left = new tNode(4);
        tree.root.left.right = new tNode(5);
        System.out.println("Height of tree is " + tree.treeHeight(tree.root));
    }

}


text:
package fpinscala.errorhandling

import org.specs2.mutable.Specification

class OptionTest extends Specification {
  "Options" should {
    "work" in {
      Option.mean(List(2,4,9)) mustEqual Some(5)
    }
    "map" in {
      val toStr: (Any) => String = _.toString
      val twice: (Int) => Int = _ * 2

      Some(3) map twice mustEqual Some(6)
      Some(3) map twice map toStr mustEqual Some("6")
      None map toStr mustEqual None
      (None map twice map toStr) mustEqual None
    }
    "getOrElse" in {
      Some(3) getOrElse(4) mustEqual 3
      None getOrElse(4) mustEqual 4
    }
    "flatMap" in {
      val flatTwice: (Int) => Option[Int] = a => Some(a * 2)
      (Some(3) flatMap flatTwice) mustEqual Some(6)
      (None flatMap flatTwice) mustEqual None
    }
    "orElse" in {
      (Some(3) orElse Some(4)) mustEqual Some(3)
      (None orElse Some(4)) mustEqual Some(4)
    }
    "filter" in {
      Some(1) filter(_ % 2 == 0) mustEqual None
      Some(2) filter(_ % 2 == 0) mustEqual Some(2)
      None filter(Nil) mustEqual None
    }
    "lift" in {
      def lift[A,B](f:A=>B) : Option[A] => Option[B] = _ map(f)
      val abs0 = lift(math.abs)
      abs0(Some(-3)) mustEqual Some(3)
      abs0(None) mustEqual None
    }
    "map2" in {
      Option.map2(Some(2), Some("a"))((a,b) => a + b) mustEqual Some("2a")
    }
    "sequence" in {
      Option.sequence(List()) mustEqual Some(Nil)
      Option.sequence(List(Some(1))) mustEqual Some(List(1))
      Option.sequence(List(Some(1), Some(2))) mustEqual Some(List(1,2))
      Option.sequence(List(Some(1), None)) mustEqual None
      Option.sequence(List(None, Some(2))) mustEqual None
    }
    "traverse" in {
      def Try[A](a: => A): Option[A] =
        try Some(a)
        catch { case e: Exception => None }

      Option.traverse(List("1", "4"))(a=>Try(a.toInt)) mustEqual Some(List(1,4))
      Option.traverse(List("1", "abc", "4"))(a=>Try(a.toInt)) mustEqual None
    }
    "sequence2" in {
      Option.sequence2(List()) mustEqual Some(Nil)
      Option.sequence2(List(Some(1))) mustEqual Some(List(1))
      Option.sequence2(List(Some(1), Some(2))) mustEqual Some(List(1,2))
      Option.sequence2(List(Some(1), None)) mustEqual None
      Option.sequence2(List(None, Some(2))) mustEqual None
    }

  }
}


text:
var express = require('express');
var morgan = require('morgan');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var path = require('path');
var fs = require('fs');
var spawn = require('child_process').spawn;

// Create Express app
var app = express();

// Config
var publicDir = path.resolve(__dirname, '../app');
var inDir = path.resolve(__dirname, '../app/in');
var outDir = path.resolve(__dirname, '../app/out');
var raytracerPath = path.resolve(__dirname, 'raytracer.o');

// Setup
app.use(express.static(publicDir)); // set the static files location /public/img will be /img for users
app.use(morgan('dev')); // log every request to the console
app.use(bodyParser.urlencoded({
        extended: false
    })) // parse application/x-www-form-urlencoded
app.use(bodyParser.json()) // parse application/json
app.use(methodOverride()); // simulate DELETE and PUT

// Ray Tracer
app.post('/api/scene/:name/:depthmin/:depthmax/:width/:height', function(req,
    res) {

    var sceneName = req.params.name;
    var sceneContents = req.body.contents;
    var depthMin = req.params.depthmin || 0;
    var depthMax = req.params.depthmax || 100;
    var width = req.params.width || 500;
    var height = req.params.height || 500;

    // Create file in `in/`
    var inFile = path.resolve(inDir, sceneName + '.txt');
    var outFile = path.resolve(outDir, sceneName + '.bmp');
    var depthFile = path.resolve(outDir, 'depth-'+sceneName + '.bmp');
    var normalFile = path.resolve(outDir, 'normals-'+sceneName + '.bmp');

    console.log("===================");
    console.log('Scene: ' + sceneName);
    console.log(sceneContents);

    fs.writeFile(inFile, sceneContents, function(err) {

        if (err) {
            console.error(err);
            return res.json({
                'error': err.message
            });
        }

        // Render using Raytracer
        // ./server/raytracer.o -input app/in/scene1.txt -output app/out/scene1.bmp -size 200 200
        var args = [
            '-input', inFile,
            '-output', outFile,
            '-size', width, height,
            '-depth', depthMin, depthMax, depthFile,
            '-normals', normalFile
        ];
        // console.log('args: ', args);
        var raytracer = spawn(raytracerPath, args);
        var log = "";
        raytracer.stderr.on('data', function(data) {
            log += data;
        });
        raytracer.stdout.on('data', function(data) {
            log += data;
        });
        raytracer.on('close', function(code) {
            // output here
            console.log(log);
            // Return to user
            return res.json({
                'imageName': sceneName,
                'imageUrl': '/out/' + sceneName + '.bmp',
                'depthImageUrl': '/out/' + 'depth-'+sceneName + '.bmp',
                'normalsImageUrl': '/out/' + 'normals-'+sceneName + '.bmp',
                'console': log
            });

        });

    });

});

// Start server
var server = app.listen(4000, function() {

    var host = server.address().address
    var port = server.address().port

    console.log('Example app listening at http://%s:%s', host, port)

});


text:
package it.conteit.scoresmanager.gui.models;

import java.util.Arrays;

import it.conteit.scoresmanager.control.management.storage.GrestsManager;
import it.conteit.scoresmanager.data.IGrest;

import javax.swing.DefaultListModel;

public class GrestsListModel extends DefaultListModel {
	private static final long serialVersionUID = -5398938206791197527L;

	public GrestsListModel(){
		super();
		IGrest[] grestsList = GrestsManager.getInstance().managedGrests();

		Arrays.sort(grestsList);

		for(int i=0; i<grestsList.length; i++){
			addGrest(grestsList[i]);
		}
	}

	// Possibile fonte di errore
	public void addGrest(IGrest grest){
		int i;
		boolean done = false;
		for(i=0; i<super.size(); i++){
			if(((IGrest) super.get(i)).compareTo(grest) >= 0){
				super.insertElementAt(grest, i);
				done = true;
				return;
			}
		}

		if(!done){
			super.addElement(grest);
		}
	}

	public void removeGrest(IGrest grest){
		super.removeElement(grest);
	}

	public IGrest getGrest(int index){
		return (IGrest) super.get(index);
	}

	public void updateGrest(IGrest grest){
		for(int i=0; i<super.size(); i++){
			if(((IGrest) super.get(i)).getName().equals(grest.getName())){
				super.set(i, grest);
			}
		}
	}
}


text:
package nom.bdezonia.zorbage.algorithm;

import static org.junit.Assert.assertEquals;

import org.junit.Test; import nom.bdezonia.zorbage.algebra.G;

import nom.bdezonia.zorbage.datasource.IndexedDataSource;
import nom.bdezonia.zorbage.storage.Storage;
import nom.bdezonia.zorbage.type.real.float64.Float64Member;

/**
 *
 * @author Barry DeZonia
 *
 */
public class TestUnique {

	@Test
	public void test1() {

		Float64Member value = G.DBL.construct();
		IndexedDataSource<Float64Member> nums = Storage.allocate(G.DBL.construct(),
				new double[] {1.1, 1.1, 1.2, 3, 3, 3, 1.1, 4, 5, 5, 5});
		// Unique expects a sorted list as input
		Sort.compute(G.DBL, nums);
		IndexedDataSource<Float64Member> uniqueNums =
				Unique.compute(G.DBL, nums);

		assertEquals(5, uniqueNums.size());

		uniqueNums.get(0, value);
		assertEquals(1.1, value.v(), 0);

		uniqueNums.get(1, value);
		assertEquals(1.2, value.v(), 0);

		uniqueNums.get(2, value);
		assertEquals(3, value.v(), 0);

		uniqueNums.get(3, value);
		assertEquals(4, value.v(), 0);

		uniqueNums.get(4, value);
		assertEquals(5, value.v(), 0);
	}
}


text:
import React from 'react'
import { Dropdown } from 'semantic-ui-react'

const options = [
  { key: 1, text: 'One', value: 1 },
  { key: 2, text: 'Two', value: 2 },
  { key: 3, text: 'Three', value: 3 },
]

const DropdownExampleUpwardSelection = () => (
  <Dropdown
    upward
    search
    selection
    options={options}
    placeholder='Choose an option'
  />
)

export default DropdownExampleUpwardSelection


text:
@interface MXTabBar()
@property(nonatomic,strong)UIButton* plusBtn;
@end
@implementation MXTabBar
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        UIButton *moreBtn=[[UIButton alloc]init];
        [moreBtn setBackgroundImage:[UIImage imageNamed:@"tabbar_compose_button"] forState:UIControlStateNormal];
        [moreBtn setBackgroundImage:[UIImage imageNamed:@"tabbar_compose_button_highlighted"] forState:UIControlStateHighlighted];
        [moreBtn setImage:[UIImage imageNamed:@"tabbar_compose_icon_add"] forState:UIControlStateNormal];
        [moreBtn setImage:[UIImage imageNamed:@"tabbar_compose_icon_add_highlighted"] forState:UIControlStateHighlighted];
        moreBtn.size=moreBtn.currentBackgroundImage.size;
        [moreBtn addTarget:self action:@selector(moreButtonDidClick:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:moreBtn];
        self.plusBtn=moreBtn;
    }
    return self;
}

-(void)layoutSubviews{
    [super layoutSubviews];
    self.plusBtn.centerX=self.width*0.5;
    self.plusBtn.centerY=self.height*0.5;
    CGFloat width=self.width / 5;
    CGFloat index=0;
    for (UIView *view in self.subviews) {
        Class class=NSClassFromString(@"UITabBarButton");
        if([view isKindOfClass:class]){
            view.x=width*index;
            view.width=width;
            index++;
            if(index==2){
                index++;
            }
        }
    }
}

- (void)moreButtonDidClick:(UIButton *)button{
    if ([self.delegate respondsToSelector:@selector(tabBar:DidClickMoreButton:)] ) {
        [self.delegate tabBar:self DidClickMoreButton:button];
    }
}
@end


text:
var assert = require('chai').assert;
var fs = require("fs");
var path = require('path');
var E = require('linq');
var S = require('string');
var Task = require('./task');
var sugar = require('sugar');
var TaskRunner = require('./task-runner.js');
var assert = require('chai').assert;

//
// Automatic loading of Grunt tasks from a collection of files.
//
module.exports = function (autoLoadConfig, log, validate, config) {

    assert.isObject(autoLoadConfig);
    assert.isObject(validate);
    assert.isObject(config);

    //
    // Load in all tasks from files.
    //
    var tasksValidated = {}; // Remembers tasks that have been validated, so they aren't validated again.
    var tasksInvoked = {}; // Remembers tasks that have been invoked, so they aren't invoked again.
    var tasksDir = autoLoadConfig.tasksDir || path.join(process.cwd(), "tasks");

    var taskRunner = new TaskRunner(log);

    //
    // Strips an extension from a filename.
    //
    var stripExt = function (fileName) {
        assert.isString(fileName);

        if (S(fileName).endsWith('.js')) {
            return fileName.slice(0, -3); // Hacky: Specific for .js files.
        }
        else {
            return fileName;
        }
    };

    //
    // Sync walk a directory structure and call the callback for each file.
    //
    var walkDirsInternal = function (rootPath, subDirPath) {

        assert.isString(rootPath);
        assert.isString(subDirPath);

        var dirPath = path.join(rootPath, subDirPath);
        var items = fs.readdirSync(dirPath);

        for (var i = 0; i < items.length; ++i) {

            var itemName = items[i];
            var relativeItemPath = path.join(subDirPath, itemName);
            var fullItemPath = path.join(dirPath, itemName);
            var stat = fs.statSync(fullItemPath);
            if (stat.isDirectory()) {
                walkDirsInternal(rootPath, relativeItemPath);
            }
            else {
                var taskName = stripExt(S(relativeItemPath).replaceAll('\\', '/').s);
                taskRunner.addTask(new Task(taskName, relativeItemPath, fullItemPath, log, validate, taskRunner));
            }
        }
    };

    var walkDirs = function (dirPath) {
        walkDirsInternal(dirPath, "./");
    };

    walkDirs(tasksDir);

    return taskRunner;
};