text:
package org.minijax.dao.converters;

import static org.junit.jupiter.api.Assertions.*;

import java.util.HashMap;
import java.util.Map;

import jakarta.json.bind.JsonbException;

import org.junit.jupiter.api.Test;

class JsonMapConverterTest {

    @Test
    void testNulls() {
        final JsonMapConverter c = new JsonMapConverter();
        assertNull(c.convertToDatabaseColumn(null));
        assertNull(c.convertToEntityAttribute(null));
    }

    @Test
    void testEmptyString() {
        final JsonMapConverter c = new JsonMapConverter();
        assertNull(c.convertToEntityAttribute(""));
    }

    @Test
    void testBasic() {
        final JsonMapConverter c = new JsonMapConverter();

        final Map<String, Object> m1 = new HashMap<>();
        m1.put("a", "b");

        final String s1 = c.convertToDatabaseColumn(m1);
        assertEquals("{\"a\":\"b\"}", s1);

        final Map<String, Object> m2 = c.convertToEntityAttribute(s1);
        assertEquals(1, m2.size());
        assertEquals("b", m2.get("a"));
        assertEquals(m1, m2);
    }

    @Test
    void testSpecialChars() {
        final JsonMapConverter c = new JsonMapConverter();

        final Map<String, Object> m1 = new HashMap<>();
        m1.put("&", "=");

        final String s1 = c.convertToDatabaseColumn(m1);
        assertEquals("{\"&\":\"=\"}", s1);

        final Map<String, Object> m2 = c.convertToEntityAttribute(s1);
        assertEquals(1, m2.size());
        assertEquals("=", m2.get("&"));
        assertEquals(m1, m2);
    }

    @Test
    void testInvalidJsonParse() {
        final JsonMapConverter c = new JsonMapConverter();
        assertThrows(JsonbException.class, () -> c.convertToEntityAttribute("{"));
    }

    @Test
    void testInvalidJsonWrite() {
        final JsonMapConverter c = new JsonMapConverter();
        final Map<String, Object> m1 = new HashMap<>();
        m1.put("a", new Object());
        assertThrows(JsonbException.class, () -> c.convertToDatabaseColumn(m1));
    }
}


text:
<?php
//**************************************************************************************************
//
// GET  /statistics?queryType=dataTotal&period_b=2015-01-01&period_e=2017-01-01
// GET  /statistics?queryType=dataDebetKreditTotal&period_b=2015-01-01&period_e=2017-01-01
//
//**************************************************************************************************

session_start();

if ( !isset( $_SESSION['User_ID'] ) or $_SESSION['User_ID'] == 0 ) {
    exit( 'Session not exists.' );
}

//**************************************************************************************************

include '../config.php';
include 'function_SQLexec.php';
include 'function_SQLtoJSON.php';
include 'function_txtToSQL.php';

//**************************************************************************************************

$_User_ID = $_SESSION['User_ID'];

if (isset($_GET['period_b'])) { $_period_b = txtToSQL($_GET['period_b']); }
else { exit('Variable "period_b" is not defined.'); }

if (isset($_GET['period_e'])) { $_period_e = txtToSQL($_GET['period_e']); }
else { exit('Variable "period_e" is not defined.'); }

//**************************************************************************************************

switch ( $_REQUEST['queryType'] ) {
    case "dataTotal" : dataTotal(); break;
    case "dataDebetKreditTotal" : dataDebetKreditTotal(); break;
    default : exit('Unknown "queryType".'); break;
}

//**************************************************************************************************
////////////////////////////////////////////////////////////////////////////////////////////////////
//**************************************************************************************************

function dataTotal() {

    global $_User_ID, $_period_b, $_period_e;

    $txtSQL = <<<HERE
        SELECT
            SUM( IF( Money_Date < '$_period_b', Money_Debet - Money_Kredit, 0 ) ) AS Money_Rest,
            SUM( IF( Money_Date >= '$_period_b', Money_Debet, 0 ) ) AS Money_Debet,
            SUM( IF( Money_Date >= '$_period_b', Money_Kredit, 0 ) ) AS Money_Kredit,
            SUM( Money_Debet - Money_Kredit ) AS Money_Total
        FROM ng_money
        WHERE Money_User_ID = $_User_ID
          AND Money_Date <= '$_period_e'
HERE;

    SQLtoJSON( $txtSQL );

}

//****************************************************************************************************

function dataDebetKreditTotal() {

    global $_User_ID, $_period_b, $_period_e;

    $txtSQL = <<<HERE
        SELECT Money_ID, Money_Date, Money_Debet, Money_Kredit, Money_Category, Money_Note
        FROM ng_money
        WHERE Money_User_ID = $_User_ID
          AND Money_Date >= '$_period_b'
          AND Money_Date <= '$_period_e'

        UNION ALL

        SELECT 0 AS Money_ID,
            '' AS Money_Date,
            SUM(Money_Debet) AS Money_Debet,
            SUM(Money_Kredit) AS Money_Kredit,
            'Остаток на начало' AS Money_Category,
            '' AS Money_Note
        FROM ng_money
        WHERE Money_User_ID = $_User_ID
          AND Money_Date < '$_period_b'

        ORDER BY Money_Date DESC, Money_ID DESC
HERE;

    SQLtoJSON( $txtSQL );

}

//****************************************************************************************************
?>

redpajama_set_name: RedPajamaGithub


text:
var Moment = require ("moment");

// get json values
var fifaCoefficients = require ("./jsonres/fifa_coefficients")
  , teams = require ("./jsonres/teams")
  , teamsWithCoefficients = {}
  ;

// add fifa coefficient for each team
for (var i = 0; i < teams.length; ++i) {

    var cTeam = teams[i];

    if (!fifaCoefficients[cTeam]) {
        console.warn("Missing FIFA coefficient for team: " + cTeam);
    }

    teamsWithCoefficients[cTeam] = fifaCoefficients[cTeam]
}

// compute min and max coefficients
var max = -Infinity
  , min = Infinity
  ;

for (var team in teamsWithCoefficients) {

    var coefficient = teamsWithCoefficients[team];

    if (coefficient > max) {
        max = teamsWithCoefficients[team];
    }

    if (coefficient < min) {
        min = teamsWithCoefficients[team];
    }
}

// compute x classes
var diff = max - min
  , classRange = diff / 7
  , countryClasses = {}
  ;

// compute country classes
for (var team in teamsWithCoefficients) {
    countryClasses[team] = Math.round ((teamsWithCoefficients[team] - min) / classRange) + 1;
}

// output country classes
// console.log(JSON.stringify(countryClasses, null, 4));

// get matches
var finalArray = require ("./jsonres/matches.json");

// update match objects
for (var i = 0; i < finalArray.length; ++i) {
    var cMatch = finalArray[i];

    // kickoff date
    cMatch.kickoff = Moment(cMatch.kickoff, "DD MMM YYYY HH:mm")
                        .add("hours", 5)
                        .toDate()
                        .getTime()
                        .toString();

    if (typeof cMatch.teams[0] === "string") {
        continue;
    }

    // get team names
    var team1 = teams[cMatch.teams[0]]
      , team2 = teams[cMatch.teams[1]]
      , xClass = 8 - Math.abs(
            countryClasses[team1]
          - countryClasses[team2]
        )
      ;

    // teams
    cMatch.teams = [
        team1.toLowerCase()
      , team2.toLowerCase()
    ];

    // x class
    cMatch.x = xClass;
};

// sort by date
finalArray.sort(function (a, b) {
     return (a.kickoff > b.kickoff) ? 1 : -1
});

if (process.argv[2] === "uglify") {
    console.log (JSON.stringify (finalArray));
    process.exit (0);
}

// output
console.log (JSON.stringify (finalArray, null, 4));


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IdentityModel.Tokens;
using ADAL = Microsoft.IdentityModel.Clients.ActiveDirectory;

namespace AzureGraphAdalWebClient.Controllers {
  public class TokenViewerController : Controller {

    public ActionResult IdToken() {
      string idToken = CustomAuthenticationManager.GetIdToken();
      JwtSecurityToken jwtIdToken = new JwtSecurityToken(idToken);
      return View(jwtIdToken);

    }

    public ActionResult AccessToken() {
      string accessToken = CustomAuthenticationManager.GetAccessToken();
      JwtSecurityToken jwtAccessToken = new JwtSecurityToken(accessToken);
      return View(jwtAccessToken);
    }

    public ActionResult RefreshToken() {
      string refreshToken = CustomAuthenticationManager.GetRefreshToken();
      JwtSecurityToken jwtRefreshToken = new JwtSecurityToken(refreshToken);
      return View(jwtRefreshToken);
    }

    public ActionResult AppOnlyAccessToken() {

      string urlTokenEndpointForTenant =
        string.Format("https://login.windows.net/{0}/oauth2/token",
                      CustomAuthenticationManager.GetTenantID());

      ADAL.AuthenticationContext authenticationContext
        = new ADAL.AuthenticationContext(urlTokenEndpointForTenant);

      string resource = DemoConstants.TargetResource;
      ADAL.ClientAssertionCertificate clientAssertionCertificate =
        DemoConstants.GetClientAssertionCertificate();

      ADAL.AuthenticationResult authenticationResult =
        authenticationContext.AcquireToken(resource, clientAssertionCertificate);

      string appOnlyAccessToken = authenticationResult.AccessToken;
      JwtSecurityToken jwtAppOnlyAccessToken = new JwtSecurityToken(appOnlyAccessToken);
      return View(jwtAppOnlyAccessToken);

    }

  }
}


text:
<?php

namespace yfinite\exceptions;

use yii\base\Exception;

/**
 * Class TransitionException
 * @package yfinite
 * @author: Aleksei Vesnin <dizeee@dizeee.ru>
 */
class TransitionException extends Exception
{
	/**
	 * @inheritdoc
	 */
	public function getName()
	{
		return 'yFinite Transition Exception';
	}
}


text:
package org.apache.hadoop.hbase.client;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.NavigableMap;
import java.util.UUID;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellBuilder;
import org.apache.hadoop.hbase.CellBuilderType;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.KeyValue;
import org.apache.hadoop.hbase.security.access.Permission;
import org.apache.hadoop.hbase.security.visibility.CellVisibility;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.yetus.audience.InterfaceAudience;

/**
 * Used to perform Delete operations on a single row.
 *

 * To delete an entire row, instantiate a Delete object with the row to delete. To further define
 * the scope of what to delete, perform additional methods as outlined below.
 *

 * To delete specific families, execute {@link #addFamily(byte[]) deleteFamily} for each family to
 * delete.
 *

 * To delete multiple versions of specific columns, execute {@link #addColumns(byte[], byte[])
 * deleteColumns} for each column to delete.
 *

 * To delete specific versions of specific columns, execute {@link #addColumn(byte[], byte[], long)
 * deleteColumn} for each column version to delete.
 *

 * Specifying timestamps, deleteFamily and deleteColumns will delete all versions with a timestamp
 * less than or equal to that passed. If no timestamp is specified, an entry is added with a
 * timestamp of 'now' where 'now' is the servers's EnvironmentEdgeManager.currentTime(). Specifying
 * a timestamp to the deleteColumn method will delete versions only with a timestamp equal to that
 * specified. If no timestamp is passed to deleteColumn, internally, it figures the most recent
 * cell's timestamp and adds a delete at that timestamp; i.e. it deletes the most recently added
 * cell.
 *

 * The timestamp passed to the constructor is used ONLY for delete of rows. For anything less -- a
 * deleteColumn, deleteColumns or deleteFamily -- then you need to use the method overrides that
 * take a timestamp. The constructor timestamp is not referenced.
 */
@InterfaceAudience.Public
public class Delete extends Mutation {
  /**
   * Create a Delete operation for the specified row.
   *

   * If no further operations are done, this will delete everything associated with the specified
   * row (all versions of all columns in all families), with timestamp from current point in time to
   * the past. Cells defining timestamp for a future point in time (timestamp > current time) will
   * not be deleted.
   * @param row row key
   */
  public Delete(byte[] row) {
    this(row, HConstants.LATEST_TIMESTAMP);
  }

  /**
   * Create a Delete operation for the specified row and timestamp.
   *

   * If no further operations are done, this will delete all columns in all families of the
   * specified row with a timestamp less than or equal to the specified timestamp.
   *

   * This timestamp is ONLY used for a delete row operation. If specifying families or columns, you
   * must specify each timestamp individually.
   * @param row       row key
   * @param timestamp maximum version timestamp (only for delete row)
   */
  public Delete(byte[] row, long timestamp) {
    this(row, 0, row.length, timestamp);
  }

  /**
   * Create a Delete operation for the specified row and timestamp.
   *

   * If no further operations are done, this will delete all columns in all families of the
   * specified row with a timestamp less than or equal to the specified timestamp.
   *

   * This timestamp is ONLY used for a delete row operation. If specifying families or columns, you
   * must specify each timestamp individually.
   * @param row We make a local copy of this passed in row. nn
   */
  public Delete(final byte[] row, final int rowOffset, final int rowLength) {
    this(row, rowOffset, rowLength, HConstants.LATEST_TIMESTAMP);
  }

  /**
   * Create a Delete operation for the specified row and timestamp.
   *

   * If no further operations are done, this will delete all columns in all families of the
   * specified row with a timestamp less than or equal to the specified timestamp.
   *

   * This timestamp is ONLY used for a delete row operation. If specifying families or columns, you
   * must specify each timestamp individually.
   */
  public Delete(final byte[] row, final int rowOffset, final int rowLength, long timestamp) {
    checkRow(row, rowOffset, rowLength);
    this.row = Bytes.copy(row, rowOffset, rowLength);
    setTimestamp(timestamp);
  }

  /**
   * Create a Delete operation using another Delete as template.
   * @param deleteToCopy delete to copy
   */
  public Delete(final Delete deleteToCopy) {
    super(deleteToCopy);
  }

  /**
   * Construct the Delete with user defined data. NOTED: 1) all cells in the familyMap must have the
   * delete type. see {@link org.apache.hadoop.hbase.Cell.Type} 2) the row of each cell must be same
   * with passed row.
   * @param row       row. CAN'T be null
   * @param ts        timestamp
   * @param familyMap the map to collect all cells internally. CAN'T be null
   */
  public Delete(byte[] row, long ts, NavigableMap<byte[], List<Cell>> familyMap) {
    super(row, ts, familyMap);
  }

  /**
   * Add an existing delete marker to this Delete object.
   * @param cell An existing cell of type "delete".
   * @return this for invocation chaining n
   */
  @Override
  public Delete add(Cell cell) throws IOException {
    super.add(cell);
    return this;
  }

  /**
   * Delete all versions of all columns of the specified family.
   *

   * Overrides previous calls to deleteColumn and deleteColumns for the specified family.
   * @param family family name
   * @return this for invocation chaining
   */
  public Delete addFamily(final byte[] family) {
    this.addFamily(family, this.ts);
    return this;
  }

  /**
   * Delete all columns of the specified family with a timestamp less than or equal to the specified
   * timestamp.
   *

   * Overrides previous calls to deleteColumn and deleteColumns for the specified family.
   * @param family    family name
   * @param timestamp maximum version timestamp
   * @return this for invocation chaining
   */
  public Delete addFamily(final byte[] family, final long timestamp) {
    if (timestamp < 0) {
      throw new IllegalArgumentException("Timestamp cannot be negative. ts=" + timestamp);
    }
    List<Cell> list = getCellList(family);
    if (!list.isEmpty()) {
      list.clear();
    }
    KeyValue kv = new KeyValue(row, family, null, timestamp, KeyValue.Type.DeleteFamily);
    list.add(kv);
    return this;
  }

  /**
   * Delete all columns of the specified family with a timestamp equal to the specified timestamp.
   * @param family    family name
   * @param timestamp version timestamp
   * @return this for invocation chaining
   */
  public Delete addFamilyVersion(final byte[] family, final long timestamp) {
    List<Cell> list = getCellList(family);
    list.add(new KeyValue(row, family, null, timestamp, KeyValue.Type.DeleteFamilyVersion));
    return this;
  }

  /**
   * Delete all versions of the specified column.
   * @param family    family name
   * @param qualifier column qualifier
   * @return this for invocation chaining
   */
  public Delete addColumns(final byte[] family, final byte[] qualifier) {
    addColumns(family, qualifier, this.ts);
    return this;
  }

  /**
   * Delete all versions of the specified column with a timestamp less than or equal to the
   * specified timestamp.
   * @param family    family name
   * @param qualifier column qualifier
   * @param timestamp maximum version timestamp
   * @return this for invocation chaining
   */
  public Delete addColumns(final byte[] family, final byte[] qualifier, final long timestamp) {
    if (timestamp < 0) {
      throw new IllegalArgumentException("Timestamp cannot be negative. ts=" + timestamp);
    }
    List<Cell> list = getCellList(family);
    list.add(new KeyValue(this.row, family, qualifier, timestamp, KeyValue.Type.DeleteColumn));
    return this;
  }

  /**
   * Delete the latest version of the specified column. This is an expensive call in that on the
   * server-side, it first does a get to find the latest versions timestamp. Then it adds a delete
   * using the fetched cells timestamp.
   * @param family    family name
   * @param qualifier column qualifier
   * @return this for invocation chaining
   */
  public Delete addColumn(final byte[] family, final byte[] qualifier) {
    this.addColumn(family, qualifier, this.ts);
    return this;
  }

  /**
   * Delete the specified version of the specified column.
   * @param family    family name
   * @param qualifier column qualifier
   * @param timestamp version timestamp
   * @return this for invocation chaining
   */
  public Delete addColumn(byte[] family, byte[] qualifier, long timestamp) {
    if (timestamp < 0) {
      throw new IllegalArgumentException("Timestamp cannot be negative. ts=" + timestamp);
    }
    List<Cell> list = getCellList(family);
    KeyValue kv = new KeyValue(this.row, family, qualifier, timestamp, KeyValue.Type.Delete);
    list.add(kv);
    return this;
  }

  @Override
  public Delete setTimestamp(long timestamp) {
    super.setTimestamp(timestamp);
    return this;
  }

  @Override
  public Delete setAttribute(String name, byte[] value) {
    return (Delete) super.setAttribute(name, value);
  }

  @Override
  public Delete setId(String id) {
    return (Delete) super.setId(id);
  }

  @Override
  public Delete setDurability(Durability d) {
    return (Delete) super.setDurability(d);
  }

  @Override
  public Delete setClusterIds(List<UUID> clusterIds) {
    return (Delete) super.setClusterIds(clusterIds);
  }

  @Override
  public Delete setCellVisibility(CellVisibility expression) {
    return (Delete) super.setCellVisibility(expression);
  }

  @Override
  public Delete setACL(String user, Permission perms) {
    return (Delete) super.setACL(user, perms);
  }

  @Override
  public Delete setACL(Map<String, Permission> perms) {
    return (Delete) super.setACL(perms);
  }

  @Override
  public Delete setTTL(long ttl) {
    throw new UnsupportedOperationException("Setting TTLs on Deletes is not supported");
  }

  @Override
  public Delete setPriority(int priority) {
    return (Delete) super.setPriority(priority);
  }

  @Override
  public CellBuilder getCellBuilder(CellBuilderType type) {
    return getCellBuilder(type, Cell.Type.Delete);
  }
}


text:
using UnityEngine;

namespace FullInspector.Samples.FullSerializer {
    [AddComponentMenu("Full Inspector Samples/FullSerializer/Attributes")]
    public class SampleFullSerializerAttributes : BaseBehavior<FullSerializerSerializer> {
        [InspectorComment("Welcome! Please click on the game object of choice to see how to serialize and inspect objects relating to the specified Unity type.")]
        public int ReadMeFirst;

        [InspectorTooltip("Hey, there. This is a tooltip from an attribute!")]
        public int HoverOverMe;

        [InspectorMargin(50)]
        [InspectorComment("Wow! I'm pretty far away! Thanks Margin!")]
        public int WayBelow;
    }
}


text:
from net_map.net_object import NetObjectType

class ReachabilityController(object):

    def __init__(self, net_map, events=None):
        self._net_map = net_map
        self._res_table = None

    def has_access(self, src_obj, dst_obj, src_service=None, dst_service=None):

        def find_not_filtered_hops_in_subnet(net_object):
            switch_list = []
            router_list = []
            hosts_list = []

            passed_list.append(net_object)

            if not net_object.table_pass_packet(src_obj, dst_obj, src_service, dst_service):
                return router_list, hosts_list

            for interface in filter(lambda i: i.is_linked(), net_object.interfaces):

                connected_object = interface.get_linked().net_object
                if connected_object not in passed_list:

                    #Фильтрация
                    if connected_object.table_pass_packet(src_obj, dst_obj, src_service, dst_service):
                        if connected_object.type == NetObjectType.switch:
                            switch_list.append(connected_object)
                        elif connected_object.type == NetObjectType.router:
                            router_list.append(connected_object)
                        elif connected_object.type == NetObjectType.host:
                            hosts_list.append(connected_object)

            for hop in switch_list:
                result = find_not_filtered_hops_in_subnet(hop)
                router_list.extend(result[0])
                hosts_list.extend(result[1])

            return router_list, hosts_list

        def find_router_with_gateway(gateway, routers):
            for router in routers:
                for interface in (x for x in router.interfaces if x.cidr):
                    if gateway.ip == interface.cidr.ip:
                        return router

        #Check to self
        if src_obj is dst_obj:
            #Filtration
            return src_obj.table_pass_packet(src_obj, dst_obj, src_service, dst_service)

        passed_list = []
        obj_list = [src_obj]

        for hop_src_obj in obj_list:
            router_list, hosts_list = find_not_filtered_hops_in_subnet(hop_src_obj)

            if dst_obj in hosts_list + router_list:
                return True

            if hop_src_obj.type == NetObjectType.host:
                router = find_router_with_gateway(hop_src_obj.interfaces[0].gateway, router_list)
                if not router:
                    #  Cannot find next gateway
                    return False

                next_gateway = router.next_hope_address(dst_obj)
                if not next_gateway:
                    #  Router with no route to destination host
                    return False
                obj_list.append(router)

            elif hop_src_obj.type == NetObjectType.router:
                next_gateway = hop_src_obj.next_hope_address(dst_obj)
                if not next_gateway:
                    return False    # Router with no route to destination host

                router = find_router_with_gateway(next_gateway, router_list)
                if not router:
                    return False    # Cannot find next gateway
                obj_list.append(router)

    def calculate(self):

        class NestedDict(dict):
            def __getitem__(self, key):
                if key in self:
                    return self.get(key)
                return self.setdefault(key, NestedDict())

        res_table = NestedDict()

        for src_subnet in self._net_map.subnets:
            for src_net_obj in src_subnet.net_objects:
                if src_net_obj.type == NetObjectType.switch:
                    continue
                for dst_subnet in self._net_map.subnets:
                    for dst_net_obj in dst_subnet.net_objects:
                        if dst_net_obj.type == NetObjectType.switch:
                            continue

                        table_part = res_table[src_subnet.id][src_net_obj.id]

                        #from object to object
                        access = self.has_access(src_net_obj, dst_net_obj)
                        table_part['default'][dst_subnet.id][dst_net_obj.id]['default'] = access

                        #from object to service
                        for dst_service in dst_net_obj.services:
                            access = self.has_access(src_net_obj, dst_net_obj, None, dst_service)
                            table_part['default'][dst_subnet.id][dst_net_obj.id][dst_service.id] = access

                        #from service to object
                        for src_service in src_net_obj.services:
                            access = self.has_access(src_net_obj, dst_net_obj, src_service, None)
                            table_part[src_service.id][dst_subnet.id][dst_net_obj.id]['default'] = access

                        #from service to service
                        for src_service in src_net_obj.services:
                            for dst_service in dst_net_obj.services:
                                access = self.has_access(src_net_obj, dst_net_obj, src_service, dst_service)
                                table_part[src_service.id][dst_subnet.id][dst_net_obj.id][dst_service.id] = access

        self._res_table = res_table

    def get_all(self):
        return self._res_table

    def _extract_service(self, subnet_id, net_object_id, service_id):
        try:
            return self._net_map.get_subnet(subnet_id).get_net_object(net_object_id).get_service(service_id)
        except:
            return None

    def get_reachable_services(self, net_object):
        if not self._res_table:
            # raise exeption
            return []

        res = []
        base_part = self._res_table[net_object.subnet.id][net_object.id]['default']
        for dest_subnets_part_key in base_part:
            dest_subnets_part = base_part[dest_subnets_part_key]
            for dest_net_obj_part_key in dest_subnets_part:
                dest_net_obj_part = dest_subnets_part[dest_net_obj_part_key]
                for dest_service_part_key in dest_net_obj_part:
                    dest_service_part = dest_net_obj_part[dest_service_part_key]
                    #нас интересуют реально существующие доступные сервисы
                    if dest_service_part and dest_service_part_key != "default":
                        res.append(self._extract_service(dest_subnets_part_key,
                                                         dest_net_obj_part_key, dest_service_part_key))

        return res


text:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using umbraco.BasePages;
using System.Collections.Generic;
using umbraco.interfaces;
using umbraco.BusinessLogic.Actions;
using umbraco.BusinessLogic;
using umbraco.uicontrols;
using umbraco.cms.presentation.Trees;
using Umbraco.Core.IO;

namespace umbraco.cms.presentation.user
{
    public partial class EditUserType : UmbracoEnsuredPage
    {
        public EditUserType()
        {
            CurrentApp = BusinessLogic.DefaultApps.users.ToString();
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            pnlUmbraco.Text = umbraco.ui.Text("usertype", base.getUser());

            ImageButton save = pnlUmbraco.Menu.NewImageButton();
            save.ImageUrl = SystemDirectories.Umbraco + "/images/editor/save.gif";
            save.Click += new ImageClickEventHandler(save_Click);
            save.ID = "save";
            pp_alias.Text = umbraco.ui.Text("usertype", base.getUser()) + " " + umbraco.ui.Text("alias", base.getUser());
            pp_name.Text = umbraco.ui.Text("usertype", base.getUser()) + " " + umbraco.ui.Text("name", base.getUser());

            pp_rights.Text = umbraco.ui.Text("default", base.getUser()) + " " + umbraco.ui.Text("rights", base.getUser());

            //ensure we have a query string
            if (string.IsNullOrEmpty(Request.QueryString["id"]))
                return;
            //ensuer it is an integer
            if (!int.TryParse(Request.QueryString["id"], out m_userTypeID))
                return;

			if (!IsPostBack)
			{
				BindActions();

				ClientTools
					.SetActiveTreeType(TreeDefinitionCollection.Instance.FindTree<UserTypes>().Tree.Alias)
					.SyncTree(m_userTypeID.ToString(), false);
			}

        }

        void save_Click(object sender, ImageClickEventArgs e)
        {
            UserType userType = CurrentUserType;
            userType.Name = txtUserTypeName.Text;
            string actions = "";

            foreach (ListItem li in cbl_rights.Items) {
                if (li.Selected)
                    actions += li.Value;
            }

            userType.DefaultPermissions = actions;
            userType.Save();

            ClientTools.ShowSpeechBubble(speechBubbleIcon.save, ui.Text("speechBubbles", "editUserTypeSaved", base.getUser()), "");
        }

        protected List<IAction> CurrentUserTypeActions
        {
            get
            {
                if (m_userTypeActions == null)
                    m_userTypeActions = umbraco.BusinessLogic.Actions.Action.FromString(CurrentUserType.DefaultPermissions);
                return m_userTypeActions;
            }
        }

        protected UserType CurrentUserType
        {
            get
            {
                if (m_userType == null)
                    m_userType = UserType.GetUserType(m_userTypeID);
                return m_userType;
            }
        }
        private UserType m_userType;
        private List<IAction> m_userTypeActions;
        private int m_userTypeID;

        private void BindActions()
        {
            lblUserTypeAlias.Text = CurrentUserType.Alias;
            txtUserTypeName.Text = CurrentUserType.Name;
            hidUserTypeID.Value = CurrentUserType.Id.ToString();

            foreach (IAction ai in global::umbraco.BusinessLogic.Actions.Action.GetPermissionAssignable()) {

                ListItem li = new ListItem(umbraco.ui.Text(ai.Alias, base.getUser()), ai.Letter.ToString());

                if(CurrentUserTypeActions.Contains(ai))
                    li.Selected = true;

                cbl_rights.Items.Add(li);
            }
        }

    }
}


text:
<!DOCTYPE html>

<title>How do I edit a calendar item?</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta content="sakai.schedule" name="description">
<meta content="schedule, edit schedule, edit event" name="search">
<link href="/library/skin/tool_base.css" media="screen" rel="stylesheet" type="text/css" charset="utf-8">
<link href="/library/skin/morpheus-default/tool.css" media="screen" rel="stylesheet" type="text/css" charset="utf-8">
<link href="/sakai-help-tool/css/help.css" media="screen" rel="stylesheet" type="text/css" charset="utf-8">
<link href="/library/js/jquery/featherlight/0.4.0/featherlight.min.css" media="screen" rel="stylesheet" type="text/css" charset="utf-8">

How do I edit a calendar item?

Go to Schedule.

Select the Schedule tool from the Tool Menu in your site. (Remember that it may also be called Calendar.)

Click on the item you want to edit.

              Zoom

Click Edit.

              Zoom

Make your changes to the event.

              Zoom

Click Save Event.


text:
package org.apache.http.impl.conn;

import java.util.concurrent.TimeUnit;

import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.HttpResponse;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.ClientConnectionRequest;
import org.apache.http.conn.ManagedClientConnection;
import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.ExecutionContext;
import org.apache.http.protocol.HttpProcessor;
import org.apache.http.protocol.HttpRequestExecutor;
import org.apache.http.protocol.ImmutableHttpProcessor;
import org.apache.http.protocol.RequestConnControl;
import org.apache.http.protocol.RequestContent;
import org.apache.http.util.EntityUtils;

class ExecReqThread extends Thread {

    private final HttpRequest request;
    private final HttpRoute route;
    private final ClientConnectionManager connman;
    private final long timeout;

    private volatile Exception exception;
    private volatile HttpResponse response;
    private volatile byte[] response_data;

    public ExecReqThread(
            HttpRequest request,
            HttpRoute route,
            ClientConnectionManager mgr,
            long timeout) {
        super();
        this.request = request;
        this.route = route;
        this.connman = mgr;
        this.timeout = timeout;
    }

    public Exception getException() {
        return this.exception;
    }

    public HttpResponse getResponse() {
        return this.response;
    }

    public byte[] getResponseData() {
        return this.response_data;
    }

    @Override
    public void run() {
        try {

            HttpProcessor processor = new ImmutableHttpProcessor(
                    new HttpRequestInterceptor[] { new RequestContent(), new RequestConnControl() });
            HttpRequestExecutor executor = new HttpRequestExecutor();
            HttpContext context = new BasicHttpContext();
            HttpParams params = new BasicHttpParams();

            ClientConnectionRequest connRequest = this.connman.requestConnection(this.route, null);
            ManagedClientConnection conn = connRequest.getConnection(this.timeout, TimeUnit.MILLISECONDS);
            try {
                context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, this.route.getTargetHost());
                context.setAttribute(ClientContext.ROUTE, this.route);
                context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);

                conn.open(this.route, context, params);

                executor.preProcess(this.request, processor, context);

                this.response = executor.execute(this.request, conn, context);
                if (this.response.getEntity() != null) {
                    this.response_data = EntityUtils.toByteArray(this.response.getEntity());
                }
            } finally {
                this.connman.releaseConnection(conn, -1, null);
            }
        } catch (Exception ex) {
            this.exception = ex;
        }
    }

}


text:
package homework4.gift;

/**
 * Created by Алексей on 17.09.2018.
 */
public class Chocolate extends NewYearGift {

    double saturation;

    public Chocolate(String name, double weight, int price, double saturation) {
        super(name, weight, price);
        this.saturation = saturation;
    }

    public double getSaturation() {
        return saturation;
    }

    public void setSaturation(double saturation) {
        this.saturation = saturation;
    }

    @Override
    public String toString() {
        return "Chocolate + [" + super.toString() + ", saturation = " + saturation + "]";
    }
}


text:
  [[a11yAssociation(data.name)]]

      <template is="dom-if"
          if="[[computeSourceIndicatorIcon_(data.*)]]">

            <iron-icon icon="[[computeSourceIndicatorIcon_(data.*)]]">
            </iron-icon>

      </template>

    <template is="dom-if"
        if="[[computeSourceIndicatorIcon_(data.*)]]">
      <paper-tooltip id="source-indicator-text" for="source-indicator"
          position="top" fit-to-visible-bounds aria-hidden="true">
        [[computeSourceIndicatorText_(data.*)]]
      </paper-tooltip>
    </template>

[[data.name]]

            [[data.version]]

        [[data.description]]

      <template is="dom-if"
          if="[[hasSevereWarnings_(data.disableReasons.*, data.*)]]">

          <iron-icon class="message-icon" icon="cr:error"></iron-icon>

            <template is="dom-repeat" items="[[data.runtimeWarnings]]">
              [[item]]
            </template>

            $i18n{itemSuspiciousInstall}

              $i18n{learnMore}

            $i18n{itemCorruptInstall}

          [[data.blacklistText]]

      </template>
      <template is="dom-if"
          if="[[showAllowlistWarning_(data.disableReasons.*, data.*)]]">

          <iron-icon class="message-icon"
              icon="extensions-icons:safebrowsing_warning">
          </iron-icon>

            $i18n{itemAllowlistWarning}

              $i18n{learnMore}

      </template>
      <template is="dom-if" if="[[inDevMode]]">

          [[data.id]]

        <template is="dom-if"
            if="[[!computeInspectViewsHidden_(data.views)]]">

                $i18n{itemInspectViews}

                [[computeFirstInspectLabel_(firstInspectView_)]]

                 [[computeExtraInspectLabel_(data.views)]]

        </template>
      </template>

      <cr-button id="detailsButton" on-click="onDetailsTap_"
          aria-describedby="a11yAssociation">
        $i18n{itemDetails}
      </cr-button>
      <cr-button id="removeButton" on-click="onRemoveTap_"
          aria-describedby="a11yAssociation"
          hidden="[[data.mustRemainInstalled]]">
        $i18n{remove}
      </cr-button>
      <template is="dom-if" if="[[shouldShowErrorsButton_(data.*)]]">
        <cr-button id="errors-button" on-click="onErrorsTap_"
            aria-describedby="a11yAssociation">
          $i18n{itemErrors}
        </cr-button>
      </template>

    <template is="dom-if" if="[[!computeDevReloadButtonHidden_(data.*)]]">
      <cr-icon-button id="dev-reload-button" class="icon-refresh no-overlap"
          aria-label="$i18n{itemReload}" aria-describedby="a11yAssociation"
          on-click="onReloadTap_"></cr-icon-button>
    </template>
    <template is="dom-if"
        if="[[showRepairButton_(data.disableReasons.corruptInstall)]]">
      <cr-button id="repair-button" class="action-button"
          aria-describedby="a11yAssociation" on-click="onRepairTap_">
        $i18n{itemRepair}
      </cr-button>
    </template>
    <template is="dom-if" if="[[showReloadButton_(data.state)]]">
      <cr-button id="terminated-reload-button" on-click="onReloadTap_"
          aria-describedby="a11yAssociation" class="action-button">
        $i18n{itemReload}
      </cr-button>
    </template>
    <cr-tooltip-icon id="parentDisabledPermissionsToolTip"
        hidden$="[[!data.disableReasons.parentDisabledPermissions]]"
        tooltip-text="$i18n{parentDisabledPermissions}"
        icon-class="cr20:kite"
        icon-aria-label="$i18n{parentDisabledPermissions}">
    </cr-tooltip-icon>
    <cr-toggle id="enableToggle"
        aria-label$="[[appOrExtension(
            data.type,
            '$i18nPolymer{appEnabled}',
            '$i18nPolymer{extensionEnabled}')]]"
        aria-describedby="a11yAssociation"
        checked="[[isEnabled_(data.state)]]"
        on-change="onEnableToggleChange_"
        disabled$="[[!isEnableToggleEnabled_(data.*)]]"
        hidden$="[[!showEnableToggle_(data.*)]]">
    </cr-toggle>


text:
/*
 * This is a generated class.
 */

package com.mailjet.client.resource;

import com.mailjet.client.Resource;
import com.mailjet.client.enums.ApiAuthenticationType;
import com.mailjet.client.enums.ApiVersion;

/**
 *
 * @author Guillaume Badi
 */
public class Messagehistory {

    public static Resource resource = new Resource("messagehistory", "", ApiVersion.V3, ApiAuthenticationType.Basic);

	public static String COMMENT = "Comment";
	public static String EVENTAT = "EventAt";
	public static String EVENTTYPE = "EventType";
	public static String STATE = "State";
	public static String USERAGENT = "Useragent";
	public static String MESSAGE = "Message";
	public static String LIMIT = "Limit";
	public static String OFFSET = "Offset";
	public static String COUNTONLY = "CountOnly";

}


text:
        <select placeholder="源" [(ngModel)]="language.from" class="source-select">
            <option *ngFor="let item of languageData" [value]="item.key">
                {{item.name}}
            </option>
        </select>
        <button (click)="toggleFromAndTo()" class="translate-language-btn">
            <svg-icon url="assets/img/ter.svg"></svg-icon>
        </button>
        <select placeholder="目标" [(ngModel)]="language.to" class="target">
            <option *ngFor="let item of languageData" [value]="item.key">
                {{item.name}}
            </option>
        </select>

        <input [(ngModel)]="needTranlstate" (keyup.enter)="test($event)" placeholder="原来">
        <button (click)="test($event)" class="search-btn">搜索</button>

        <translate [data]="translate"></translate>

        更多>>


text:
<project name="project" basedir="." default="build">

<target name="build">

    <echo>CREATING package.xml</echo>

    <pearpkg2 name="FOP" dir=".">

        <option name="packagefile" value="package.xml"/>
        <option name="outputdirectory" value="."/>

        <option name="packagedirectory" value="."/>
        <fileset dir="." >
            <include name="FOP/*" />
            <include name="tests/**" />
            <include name="FOP.php" />
        </fileset>

        <option name="baseinstalldir" value="."/>
        <option name="channel" value="pear.sashabereka.com"/>

        <option name="releaseversion" value="1.1.0"/>
        <option name="apiversion" value="1.1.0"/>
        <option name="apistability" value="stable"/>

        <option name="summary" value="Wrapper for Apache FOP application"/>
        <option name="description" value="Generates PDF using xsl template"/>
        <option name="notes" value="Generates PDF using xsl template"/>

        <option name="releasestability" value="stable"/>
        <option name="license" value="BSD"/>
        <option name="phpdep" value="5.2.0"/>
        <option name="pearinstallerdep" value="1.4.6"/>
        <option name="packagetype" value="php"/>

        <mapping name="maintainers">
            <element>
                <element key="handle" value="sashabereka"/>
                <element key="name" value="Sasha Bereka"/>
                <element key="email" value="tender.post@gmail.com"/>
                <element key="role" value="lead"/>
            </element>
        </mapping>

    </pearpkg2>

</target>

</project>


text:
using System;
using System.Data;
using System.Data.SQLite;

public static partial class Extensions
{
    /// <summary>
    ///     A SQLiteConnection extension method that executes the data set operation.
    /// </summary>
    /// <param name="this">The @this to act on.</param>
    /// <param name="cmdText">The command text.</param>
    /// <param name="parameters">Options for controlling the operation.</param>
    /// <param name="commandType">Type of the command.</param>
    /// <param name="transaction">The transaction.</param>
    /// <returns>A DataSet.</returns>
    public static DataSet ExecuteDataSet(this SQLiteConnection @this, string cmdText, SQLiteParameter[] parameters, CommandType commandType, SQLiteTransaction transaction)
    {
        using (SQLiteCommand command = @this.CreateCommand())
        {
            command.CommandText = cmdText;
            command.CommandType = commandType;
            command.Transaction = transaction;

            if (parameters != null)
            {
                command.Parameters.AddRange(parameters);
            }

            var ds = new DataSet();
            using (var dataAdapter = new SQLiteDataAdapter(command))
            {
                dataAdapter.Fill(ds);
            }

            return ds;
        }
    }

    /// <summary>
    ///     A SQLiteConnection extension method that executes the data set operation.
    /// </summary>
    /// <param name="this">The @this to act on.</param>
    /// <param name="commandFactory">The command factory.</param>
    /// <returns>A DataSet.</returns>
    public static DataSet ExecuteDataSet(this SQLiteConnection @this, Action<SQLiteCommand> commandFactory)
    {
        using (SQLiteCommand command = @this.CreateCommand())
        {
            commandFactory(command);

            var ds = new DataSet();
            using (var dataAdapter = new SQLiteDataAdapter(command))
            {
                dataAdapter.Fill(ds);
            }

            return ds;
        }
    }

    /// <summary>
    ///     A SQLiteConnection extension method that executes the data set operation.
    /// </summary>
    /// <param name="this">The @this to act on.</param>
    /// <param name="cmdText">The command text.</param>
    /// <returns>A DataSet.</returns>
    public static DataSet ExecuteDataSet(this SQLiteConnection @this, string cmdText)
    {
        return @this.ExecuteDataSet(cmdText, null, CommandType.Text, null);
    }

    /// <summary>
    ///     A SQLiteConnection extension method that executes the data set operation.
    /// </summary>
    /// <param name="this">The @this to act on.</param>
    /// <param name="cmdText">The command text.</param>
    /// <param name="transaction">The transaction.</param>
    /// <returns>A DataSet.</returns>
    public static DataSet ExecuteDataSet(this SQLiteConnection @this, string cmdText, SQLiteTransaction transaction)
    {
        return @this.ExecuteDataSet(cmdText, null, CommandType.Text, transaction);
    }

    /// <summary>
    ///     A SQLiteConnection extension method that executes the data set operation.
    /// </summary>
    /// <param name="this">The @this to act on.</param>
    /// <param name="cmdText">The command text.</param>
    /// <param name="commandType">Type of the command.</param>
    /// <returns>A DataSet.</returns>
    public static DataSet ExecuteDataSet(this SQLiteConnection @this, string cmdText, CommandType commandType)
    {
        return @this.ExecuteDataSet(cmdText, null, commandType, null);
    }

    /// <summary>
    ///     A SQLiteConnection extension method that executes the data set operation.
    /// </summary>
    /// <param name="this">The @this to act on.</param>
    /// <param name="cmdText">The command text.</param>
    /// <param name="commandType">Type of the command.</param>
    /// <param name="transaction">The transaction.</param>
    /// <returns>A DataSet.</returns>
    public static DataSet ExecuteDataSet(this SQLiteConnection @this, string cmdText, CommandType commandType, SQLiteTransaction transaction)
    {
        return @this.ExecuteDataSet(cmdText, null, commandType, transaction);
    }

    /// <summary>
    ///     A SQLiteConnection extension method that executes the data set operation.
    /// </summary>
    /// <param name="this">The @this to act on.</param>
    /// <param name="cmdText">The command text.</param>
    /// <param name="parameters">Options for controlling the operation.</param>
    /// <returns>A DataSet.</returns>
    public static DataSet ExecuteDataSet(this SQLiteConnection @this, string cmdText, SQLiteParameter[] parameters)
    {
        return @this.ExecuteDataSet(cmdText, parameters, CommandType.Text, null);
    }

    /// <summary>
    ///     A SQLiteConnection extension method that executes the data set operation.
    /// </summary>
    /// <param name="this">The @this to act on.</param>
    /// <param name="cmdText">The command text.</param>
    /// <param name="parameters">Options for controlling the operation.</param>
    /// <param name="transaction">The transaction.</param>
    /// <returns>A DataSet.</returns>
    public static DataSet ExecuteDataSet(this SQLiteConnection @this, string cmdText, SQLiteParameter[] parameters, SQLiteTransaction transaction)
    {
        return @this.ExecuteDataSet(cmdText, parameters, CommandType.Text, transaction);
    }

    /// <summary>
    ///     A SQLiteConnection extension method that executes the data set operation.
    /// </summary>
    /// <param name="this">The @this to act on.</param>
    /// <param name="cmdText">The command text.</param>
    /// <param name="parameters">Options for controlling the operation.</param>
    /// <param name="commandType">Type of the command.</param>
    /// <returns>A DataSet.</returns>
    public static DataSet ExecuteDataSet(this SQLiteConnection @this, string cmdText, SQLiteParameter[] parameters, CommandType commandType)
    {
        return @this.ExecuteDataSet(cmdText, parameters, commandType, null);
    }
}


text:
In order to test Splunks SDKs on Travis CI, there must be a docker container with Splunk installed and all required configurations set.

## Usage
Currently the build version of this image is located at http://hub.docker.com/r/adamryman/splunk-travis-ci which you can get with

```
docker pull adamryman/splunk-travis-ci:$SPLUNK_VERSION
```

Current built versions are `6.2.5`, `6.1.9` and `6.0.10`.

## Build a different version

To build this docker image for a different version of Splunk, in the [Dockerfile](https://github.com/adamryman/docker-splunk-travis-ci/blob/master/Dockerfile) change `SPLUNK_VERSION` and `SPLUNK_BUILD` to your choice of version and build respectivly.

## Additonal Information

### [Dockerfile](https://github.com/adamryman/docker-splunk-travis-ci/blob/master/Dockerfile)
This Dockerfile builds an image with the following qualites:
- Splunk installed
- [SDK App Collection](https://github.com/splunk/sdk-app-collection) installed
- `allowRemoteLogin=true` to allow api access with default password

### [.travis.yml](https://github.com/adamryman/docker-splunk-travis-ci/blob/master/.travis.yml) file
This file is example `.travis.yml` file for [Travis CI](http://travis-ci.org). It:
- Adds a `.splunkrc` file
- Pulls and runs the docker image built from this container


text:
<!doctype html>

  <meta charset="UTF-8">
  <title>Example - example-example56-debug</title>

  Check me to make text readonly: <input type="checkbox" ng-model="checked">

<input type="text" ng-readonly="checked" value="I'm Angular" aria-label="Readonly field" />


text:
package broker_acceptance_test

import (
	"io/ioutil"
	"time"

	"github.com/cloudfoundry/cf-test-helpers/cf"
	"github.com/cloudfoundry/cf-test-helpers/generator"
	"github.com/cloudfoundry/cf-test-helpers/helpers"
	. "github.com/onsi/ginkgo/v2"
	. "github.com/onsi/gomega"
	. "github.com/onsi/gomega/gbytes"
	. "github.com/onsi/gomega/gexec"
)

var _ = Describe("SQS broker", func() {
	const (
		serviceName      = "aws-sqs-queue"
		standardPlanName = "standard"
		fifoPlanName     = "fifo"
	)

	It("is registered in the marketplace", func() {
		plans := cf.Cf("marketplace").Wait(testConfig.DefaultTimeoutDuration())
		Expect(plans).To(Exit(0))
		Expect(plans).To(Say(serviceName))
	})

	It("has the expected plans available", func() {
		plans := cf.Cf("marketplace", "-e", serviceName).Wait(testConfig.DefaultTimeoutDuration())
		Expect(plans).To(Exit(0))
		Expect(plans.Out.Contents()).To(ContainSubstring(standardPlanName))
		Expect(plans.Out.Contents()).To(ContainSubstring(fifoPlanName))
	})

	Context("creating an SQS queue", func() {
		var (
			appName             string
			serviceInstanceName string
		)

		It("is accessible from the healthcheck app", func() {

			appName = generator.PrefixedRandomName(testConfig.GetNamePrefix(), "APP")
			serviceInstanceName = generator.PrefixedRandomName(testConfig.GetNamePrefix(), "test-sqs-queue")

			By("creating a standard queue service: "+serviceInstanceName, func() {
				Expect(cf.Cf("create-service", serviceName, standardPlanName, serviceInstanceName, "-c", `{"message_retention_period": 60}`).Wait(testConfig.DefaultTimeoutDuration())).To(Exit(0))
				pollForServiceCreationCompletion(serviceInstanceName)
			})

			defer By("deleting a standard queue service", func() {
				Expect(cf.Cf("delete-service", serviceInstanceName, "-f").Wait(testConfig.DefaultTimeoutDuration())).To(Exit(0))
				pollForServiceDeletionCompletion(serviceInstanceName)
			})

			By("updating the service's queue retention period", func() {
				Expect(cf.Cf("update-service", serviceInstanceName, "-c", `{"message_retention_period": 120}`).Wait(testConfig.DefaultTimeoutDuration())).To(Exit(0))
				pollForServiceUpdateCompletion(serviceInstanceName)
			})

			By("pushing the healthcheck app", func() {
				Expect(cf.Cf(
					"push", appName,
					"--no-start",
					"-b", testConfig.GetGoBuildpackName(),
					"-p", "../example-apps/healthcheck",
					"-f", "../example-apps/healthcheck/manifest.yml",
				).Wait(testConfig.CfPushTimeoutDuration())).To(Exit(0))
			})

			defer By("deleting the app", func() {
				cf.Cf("delete", appName, "-f").Wait(testConfig.DefaultTimeoutDuration())
			})

			By("binding the service", func() {
				Expect(cf.Cf("bind-service", appName, serviceInstanceName).Wait(testConfig.DefaultTimeoutDuration())).To(Exit(0))
				pollForServiceBound(serviceInstanceName, appName)
			})

			defer By("unbinding the service", func() {
				Expect(cf.Cf("unbind-service", appName, serviceInstanceName).Wait(testConfig.DefaultTimeoutDuration())).To(Exit(0))
				pollForServiceUnbound(serviceInstanceName, appName)
			})

			By("starting the app", func() {
				Expect(cf.Cf("start", appName).Wait(testConfig.CfPushTimeoutDuration())).To(Exit(0))
			})

			By("testing the SQS queue access from the app", func() {
				resp, err := httpClient.Get(helpers.AppUri(appName, "/sqs-test", testConfig))
				Expect(err).NotTo(HaveOccurred())
				body, err := ioutil.ReadAll(resp.Body)
				Expect(err).NotTo(HaveOccurred())
				resp.Body.Close()
				Expect(resp.StatusCode).To(Equal(200), "Got %d response from healthcheck app. Response body:\n%s\n", resp.StatusCode, string(body))
			})

		})
	})

	Context("multiple operations against a single queue", func() {
		var (
			appOneName          string
			appTwoName          string
			serviceInstanceName string
		)

		BeforeEach(func() {
			appOneName = generator.PrefixedRandomName(testConfig.GetNamePrefix(), "APP")
			appTwoName = generator.PrefixedRandomName(testConfig.GetNamePrefix(), "APP")

			By("deploying a first app", func() {
				Expect(cf.Cf(
					"push", appOneName,
					"--no-start",
					"-b", testConfig.GetGoBuildpackName(),
					"-p", "../example-apps/healthcheck",
					"-f", "../example-apps/healthcheck/manifest.yml",
				).Wait(testConfig.CfPushTimeoutDuration())).To(Exit(0))
			})

			By("deploying a second app", func() {
				Expect(cf.Cf(
					"push", appTwoName,
					"--no-start",
					"-b", testConfig.GetGoBuildpackName(),
					"-p", "../example-apps/healthcheck",
					"-f", "../example-apps/healthcheck/manifest.yml",
				).Wait(testConfig.CfPushTimeoutDuration())).To(Exit(0))
			})

			serviceInstanceName = generator.PrefixedRandomName(testConfig.GetNamePrefix(), "test-sqs-queue")

			By("creating the service: "+serviceInstanceName, func() {
				Expect(
					cf.
						Cf("create-service", serviceName, standardPlanName, serviceInstanceName).
						Wait(testConfig.DefaultTimeoutDuration()),
				).
					To(Exit(0))
				pollForServiceCreationCompletion(serviceInstanceName)
			})

			By("Waiting for AWS to be eventually consistent", func() {
				time.Sleep(10 * time.Second)
			})
		})

		AfterEach(func() {
			By("deleting the first app", func() {
				cf.Cf("delete", appOneName, "-f").Wait(testConfig.DefaultTimeoutDuration())
			})

			By("deleting the second app", func() {
				cf.Cf("delete", appTwoName, "-f").Wait(testConfig.DefaultTimeoutDuration())
			})

			By("deleting the service", func() {
				Expect(
					cf.Cf("delete-service", serviceInstanceName, "-f").
						Wait(testConfig.DefaultTimeoutDuration()),
				).To(Exit(0))
				pollForServiceDeletionCompletion(serviceInstanceName)
			})
		})
	})
})


text:
using System;
using System.IO;
using static System.Text.Encoding;

namespace Screna.Audio
{
    /// <summary>
    /// Writes an Audio file.
    /// </summary>
    public class AudioFileWriter : IAudioFileWriter
    {
        readonly object _syncLock = new object();
        readonly BinaryWriter _writer;
        readonly WaveFormat _format;

        readonly long _dataSizePos, _factSampleCountPos;

        readonly bool _riff;

        /// <summary>
        /// Creates a new instance of <see cref="AudioFileWriter"/>.
        /// </summary>
        public AudioFileWriter(Stream OutStream, WaveFormat Format, bool Riff = true)
        {
            if (OutStream == null)
                throw new ArgumentNullException(nameof(OutStream));

            _format = Format ?? throw new ArgumentNullException(nameof(Format));
            _riff = Riff;

            _writer = new BinaryWriter(OutStream, UTF8);

            if (Riff)
            {
                _writer.Write(UTF8.GetBytes("RIFF"));
                _writer.Write(0); // placeholder
                _writer.Write(UTF8.GetBytes("WAVE"));

                _writer.Write(UTF8.GetBytes("fmt "));

                _writer.Write(18 + Format.ExtraSize); // wave format length
            }

            Format.Serialize(_writer);

            if (!Riff)
                return;

            // CreateFactChunk
            if (HasFactChunk)
            {
                _writer.Write(UTF8.GetBytes("fact"));
                _writer.Write(4);
                _factSampleCountPos = OutStream.Position;
                _writer.Write(0); // number of samples
            }

            // WriteDataChunkHeader
            _writer.Write(UTF8.GetBytes("data"));
            _dataSizePos = OutStream.Position;
            _writer.Write(0); // placeholder
        }

        /// <summary>
        /// Creates a new instance of <see cref="AudioFileWriter"/>.
        /// </summary>
        public AudioFileWriter(string FileName, WaveFormat Format, bool Riff = true)
            : this(new FileStream(FileName, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read), Format, Riff) { }

        bool HasFactChunk => _format.Encoding != WaveFormatEncoding.Pcm && _format.BitsPerSample != 0;

        /// <summary>
        /// Number of bytes of audio in the data chunk
        /// </summary>
        public long Length { get; private set; }

        /// <summary>
        /// Writes to file.
        /// </summary>
        public void Write(byte[] Data, int Offset, int Count)
        {
            lock (_syncLock)
            {
                if (_riff && _writer.BaseStream.Length + Count > uint.MaxValue)
                    throw new ArgumentException("WAV file too large", nameof(Count));

                _writer.Write(Data, Offset, Count);
                Length += Count;
            }
        }

        /// <summary>
        /// Writes all buffered data to file.
        /// </summary>
        public void Flush()
        {
            lock (_syncLock)
            {
                _writer.Flush();

                if (!_riff)
                    return;

                var pos = _writer.BaseStream.Position;
                UpdateHeader();
                _writer.BaseStream.Position = pos;
            }
        }

        /// <summary>
        /// Updates the header with file size information
        /// </summary>
        void UpdateHeader()
        {
            // UpdateRiffChunk
            _writer.Seek(4, SeekOrigin.Begin);
            _writer.Write((uint)(_writer.BaseStream.Length - 8));

            // UpdateFactChunk
            if (HasFactChunk)
            {
                var bitsPerSample = _format.BitsPerSample * _format.Channels;
                if (bitsPerSample != 0)
                {
                    _writer.Seek((int)_factSampleCountPos, SeekOrigin.Begin);

                    _writer.Write((int)(Length * 8 / bitsPerSample));
                }
            }

            // UpdateDataChunk
            _writer.Seek((int)_dataSizePos, SeekOrigin.Begin);
            _writer.Write((uint)Length);
        }

        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        public void Dispose()
        {
            using (_writer)
                Flush();
        }
    }
}


text:
namespace SharedChannelTable
{
	struct ChannelTableItem;
}

struct ChannelImpl;
struct MemRollbackManager;
class DpFixedSizeSharedMemAllocator;

class Channel
{
	friend class ShareChannelManager;
public:
	~Channel();
	bool Write(const char * buf, int length);
	int Read(char * buf, int length);
	int Peek(char * buf, int length);
	unsigned Size();
	void Close();
	int Type();
	bool IsWriterAlive();
	void SetBufferLimit(int size);

private:
	Channel(SharedChannelTable::ChannelTableItem * shareChannel, DpFixedSizeSharedMemAllocator * allocator, MemRollbackManager * rollbackManager);
	SharedChannelTable::ChannelTableItem * ShareStruct();

private:
	ChannelImpl * _channel;
};


text:
class ApiBase(object):
    """Clase base del objeto API"""

    def __init__(self, controller, rest_client):
        self.controller = controller
        self.rest_client = rest_client


text:
YUI.add('ac-flickr-tests', function(Y) {

    var suite = new Y.Test.Suite('ac-flickr example test suite'),
        Assert = Y.Assert;

    suite.add(new Y.Test.Case({
        name: 'Example tests',
        'test is rendered' : function() {
            Assert.isNotNull(Y.one('#demo'));
            Assert.isNotNull(Y.one('.example #demo #ac-input'));
            Assert.isNotNull(Y.one('.example #demo .yui3-aclist-list'));
        },

        'test type "a" into ac list' : function() {
            var input =  Y.one('.example #demo #ac-input'),
                list = Y.one('.example #demo .yui3-aclist-list'),
                inputStr = "a";
            input.focus();
            input.set('value', inputStr);

            var interval = 10,
                timeout = 10000,
                condition = function() {
                    // Return a truthy/falsey result.
                    return (list.all('li').size() > 0);
                    // For example:
                    // return Y.one("#waitForMe") !== null
                },
            success = function() {
                Assert.isTrue((list.all('li').size() > 0), ' - Failed to find more than 0 results for ' + inputStr);
                Assert.isTrue((list.one('li').all('img').size() === 1), ' - Failed to find exactly one image in the first ac-list item');
//                Assert.areEqual(inputStr.toLowerCase(), list.one('.yui3-highlight').getHTML().toLowerCase(), 'failed to hightlight ' + inputStr + ' on first result');
            },
            failure = function() {
                Y.Assert.fail("#waitForMe never showed up in " + timeout + "ms");
            };

            // failure is optional. Will default to "wait() without resume()" error
            this.poll(condition, interval, timeout, success, failure);
        },
        'test select item from ac list' : function() {
            var input =  Y.one('.example #demo #ac-input'),
                list = Y.one('.example #demo .yui3-aclist-list'),
                inputStr = "a";
            input.focus();
            input.set('value', '');
            input.set('value', inputStr);

            var interval = 10,
                timeout = 10000,
                condition = function() {
                    // Return a truthy/falsey result.
                    return (list.all('li').size() > 0);
                    // For example:
                    // return Y.one("#waitForMe") !== null
                },
            success = function() {
                var photos = Y.one('.example #photos');
                list.all('li').item(0).simulate('click');
                Assert.areEqual(1, photos.all('li img').size(), ' - Failed to find exactly 1 selected photo');

                list.all('li').item(1).simulate('click');
                Assert.areEqual(2, photos.all('li img').size(), ' - Failed to find exactly 2 selected photo');
            },
            failure = function() {
                Y.Assert.fail("#waitForMe never showed up in " + timeout + "ms");
            };

            // failure is optional. Will default to "wait() without resume()" error
            this.poll(condition, interval, timeout, success, failure);
        }

    }))

    Y.Test.Runner.add(suite);

}, '', { requires: [ 'node', 'node-event-simulate' ] });


text:
if (!process.versions.openssl) {
  console.error('Skipping because node compiled without OpenSSL.');
  process.exit(0);
}

var hosterr = /Hostname\/IP doesn\'t match certificate\'s altnames/g;
var testCases =
    [{ ca: ['ca1-cert'],
       key: 'agent2-key',
       cert: 'agent2-cert',
       servers: [
         { ok: true, key: 'agent1-key', cert: 'agent1-cert' },
         { ok: false, key: 'agent2-key', cert: 'agent2-cert' },
         { ok: false, key: 'agent3-key', cert: 'agent3-cert' }
       ]
     },

     { ca: [],
       key: 'agent2-key',
       cert: 'agent2-cert',
       servers: [
         { ok: false, key: 'agent1-key', cert: 'agent1-cert' },
         { ok: false, key: 'agent2-key', cert: 'agent2-cert' },
         { ok: false, key: 'agent3-key', cert: 'agent3-cert' }
       ]
     },

     { ca: ['ca1-cert', 'ca2-cert'],
       key: 'agent2-key',
       cert: 'agent2-cert',
       servers: [
         { ok: true, key: 'agent1-key', cert: 'agent1-cert' },
         { ok: false, key: 'agent2-key', cert: 'agent2-cert' },
         { ok: true, key: 'agent3-key', cert: 'agent3-cert' }
       ]
     }
    ];

var common = require('../common');
var assert = require('assert');
var fs = require('fs');
var tls = require('tls');

function filenamePEM(n) {
  return require('path').join(common.fixturesDir, 'keys', n + '.pem');
}

function loadPEM(n) {
  return fs.readFileSync(filenamePEM(n));
}

var successfulTests = 0;

function testServers(index, servers, clientOptions, cb) {
  var serverOptions = servers[index];
  if (!serverOptions) {
    cb();
    return;
  }

  var ok = serverOptions.ok;

  if (serverOptions.key) {
    serverOptions.key = loadPEM(serverOptions.key);
  }

  if (serverOptions.cert) {
    serverOptions.cert = loadPEM(serverOptions.cert);
  }

  var server = tls.createServer(serverOptions, function(s) {
    s.end('hello world\n');
  });

  server.listen(common.PORT, function() {
    var b = '';

    console.error('connecting...');
    var client = tls.connect(clientOptions, function() {
      var authorized = client.authorized ||
                       hosterr.test(client.authorizationError);

      console.error('expected: ' + ok + ' authed: ' + authorized);

      assert.equal(ok, authorized);
      server.close();
    });

    client.on('data', function(d) {
      b += d.toString();
    });

    client.on('end', function() {
      assert.equal('hello world\n', b);
    });

    client.on('close', function() {
      testServers(index + 1, servers, clientOptions, cb);
    });
  });
}

function runTest(testIndex) {
  var tcase = testCases[testIndex];
  if (!tcase) return;

  var clientOptions = {
    port: common.PORT,
    ca: tcase.ca.map(loadPEM),
    key: loadPEM(tcase.key),
    cert: loadPEM(tcase.cert),
    rejectUnauthorized: false
  };

  testServers(0, tcase.servers, clientOptions, function() {
    successfulTests++;
    runTest(testIndex + 1);
  });
}

runTest(0);

process.on('exit', function() {
  console.log('successful tests: %d', successfulTests);
  assert.equal(successfulTests, testCases.length);
});


text:
import $ from 'jquery';
import {Router} from 'backbone';
import Gallery from '../views/gallery';
import Photos from '../collections/photos';
import Photo from '../models/photo';
import PhotoView from '../views/photo';
import HeaderView from '../views/header';

class AppRouter extends Router {
	constructor() {
		super();
		this.App = {
		Collections: {
			Photos: new Photos()
		},
			Views: {}
		}

		this.renderHeader();
	}
	routes() {
		return {
			'': 'gallery',
			'photo/:id': 'photo',
			'search?q=:query': 'search'
		}
	}

	gallery() {
		this.App.Collections.Photos = this.App.Collections.Photos ? this.App.Collections.Photos: new Photos();
		this.App.Collections.Photos.clean().loadMore();
		this.App.Views.Gallery = this.App.Views.Gallery ? this.App.Views.Gallery : new Gallery({model: this.App.Collections.Photos});
		this.App.Views.Header.updateSearchQuery('');
		$('#app').html('').append(this.App.Views.Gallery.el);
	}

	photo(id) {
		if (this.App.Views.Gallery) {
			this.App.Views.Gallery.isActive = false;
		}
		const model = new Photo({id: id});
		const view =  new PhotoView({model: model});
		$('#app').html('').append(view.el);
	}

	search(query) {
		this.App.Collections.Photos = this.App.Collections.Photos ? this.App.Collections.Photos : new Photos();
		this.App.Collections.Photos.search(query).loadMore();
		this.App.Views.Gallery = this.App.Views.Gallery ? this.App.Views.Gallery : new Gallery({model: this.App.Collections.Photos});
		this.App.Views.Header.updateSearchQuery(query);
		$('#app').html('').append(this.App.Views.Gallery.el);
	}

	renderHeader() {
		this.App.Views.Header = this.App.Views.Header ? this.App.Views.Header : new HeaderView({model: this.App.Collections.Photos});
	}
}

export default AppRouter;


text:
![Packagist](https://img.shields.io/badge/PHP-project-green.svg)
![Packagist](https://img.shields.io/badge/HTML-5-yellowgreen.svg)
[![Packagist](https://img.shields.io/packagist/l/doctrine/orm.svg)](LICENSE)
![Packagist](https://img.shields.io/badge/Versi%C3%B3n-Estable%201.0-orange.svg)

Script PHP para recibir un formulario de contacto y enviarlo por correo electrónico a un destinatario específico.

## Información
Este proyecto está hecho con el único propósito de tener a la mano la funcionalidad
de un script escrito en PHP para recibir un formulario de contacto (o cualquier otro formulario) y enviar los campos a un correo electrónico específico.

Este tipo de recursos es muy utilizado a la hora de diseñar cualquier página web,
como en la sección de **Contáctanos**, por ejemplo.

La idea es hacer una plantilla en HTML y agregar algunos campos con *placeholders*
que sirvan después para poder reemplazarlos dinámicamente con PHP y con los campos
recibidos desde el formulario.

Estaremos usando la función *mail* de PHP para enviar correos en formato HTML.

El uso normal de esta función es:

```PHP
mail($para, $titulo, $mensaje);
```

Iremos ajustando cada parámetro de acuerdo a nuestras necesidades.

Para efectos de prueba, estaremos haciendo la página del formulario con **Bootstrap**
e incluiremos algunas rutinas en **Javascript** para validar los campos.
Siguiendo con la página de prueba, mandaremos el formulario a través de AJAX, usando
**jQuery** y de acuerdo a la respuesta del servidor (*response*) añadiremos un cuadro
de *alert* para notificar al usuario que se ha mandado (o no) el formulario.

No es la intención de este ejercicio enseñar a usar **Bootstrap** ni **jQuery** sino
el *script* hecho en PHP para recibir el formulario y enviarlo por correo.

Así que, pueden hacer la página que quieran usando su propio HTML y/o CSS. Incluso
mandando el formulario a través de ```method="POST" action="confirmacion.php"``` o por medio de AJAX.

Este *script* funciona perfectamente para versiones de PHP 5, 6 y 7.

## Cómo usarlo
Simplemente copia todos los archivos del repositorio a una carpeta dentro de tu servicio
de hosting que tengas contratado. Recuerda que necesitas un stock de desarrollo **LAMP**,
es decir, que tu proveedor de hosting tenga sus servicios bajo LINUX, que use APACHE
como servidor web y que tenga el intérprete de PHP instalado.

Si usas ```method="POST" action="confirmacion.php"``` entonces, el script lo deberás
de poner en el archivo **confirmacion.php** o el que quieras (solo recuerda cambiarlo
en el atributo **action** del formulario).

Al mandarlo por medio del formulario a otra página, recuerda usar el ```method="POST"```
para que no se muestre en el URL el contenido del formulario.

Si deseas usarlo por medio de AJAX, entonces el URL será **confirmacion.php** y
tendrás que esperar el **response text** que sea igual a OK. En Javascript podrás
compararlo y de ahí mostrar el mensaje de alerta correspondiente.

Lee los diferentes comentarios en el archivo PHP para que tengas el control de acuerdo
al método de envío que seleccionaste.

## Desarrollo
* Autor: Fernando Magrosoto [@fmagrosoto](https://twitter.com/fmagrosoto)
* Historia: Febrero 2017
* Frameworks usados: Bootstrap 3, jQuery 3
* Stack de desarrollo: LAMPP
* Versión de PHP: 7
* Tecnologías: HTML5, CSS3, Javascript, PHP
* Licencia: [MIT](LICENSE)

## Git Ignore
En este repositorio se han contemplado una serie de herramientas, sistemas operativos,
editores de código, IDE's, etc., que se han puesto en el archivo .gitignore con el
propósito de mantener lo más limpio este proyecto.

Si decides clonar este repositorio para mejorarlo o añadirle funcionalidades y quieres
hacer un PR para que nosotros lo integremos, entonces te pido que incluyas en el
.gitignore tu entorno de desarrollo para continuar con este propósito de mantener
lo más limpio posible este ejercicio.

## Notas
Este repositorio está hecho bajo una licencia [MIT](LICENCE).
Puedes hacer lo que quieras con el, pero siempre respetando la autoría original.

Para cualquier comentario, puedes contactarme aquí mismo o en [Twitter](https://twitter.com/fmagrosoto).

***

Copyleft 2017.
Fernando Magrosoto Vásquez
\#HappyCoding


text:
namespace orion
{
namespace debug
{

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

struct SymbolsImpl
{
   std::unique_ptr<dw::Object> object;

   Dwarf_Obj_Access_Interface obj_access;

   std::wstring file_name;

   std::unique_ptr<dw::Debug> dbg;

   explicit SymbolsImpl(const std::wstring& fname)
      : object(dw::make_object(fname))
      , obj_access()
      , file_name(fname)
      , dbg()
   {
      obj_access.object  = object.get();
      obj_access.methods = &dw::methods;

      dbg = std::make_unique<dw::Debug>(obj_access);
   }

   SymbolsImpl(uintptr_t file_handle, const std::wstring& fname)
      : object(dw::make_object(file_handle))
      , obj_access()
      , file_name(fname)
      , dbg()
   {
      obj_access.object  = object.get();
      obj_access.methods = &dw::methods;

      dbg = std::make_unique<dw::Debug>(obj_access);
   }
};

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

Symbols::Symbols(const std::wstring& file_name)
   : _impl(std::make_unique<SymbolsImpl>(file_name))
{
}

Symbols::Symbols(uintptr_t file_handle, const std::wstring& name)
   : _impl(std::make_unique<SymbolsImpl>(file_handle, name))
{
}

Symbols::Symbols(Symbols&& rhs) noexcept
   : _impl(std::move(rhs._impl))
{
}

Symbols::~Symbols() = default;

Symbols& Symbols::operator=(Symbols&& rhs) noexcept
{
   _impl = std::move(rhs._impl);

   return *this;
}

void Symbols::dump() const
{
   std::wcout << "Symbols -> " << impl()->file_name << "\n";
   impl()->dbg->address_ranges().dump();
}

bool Symbols::find_address(uintptr_t address, LocationInfo& location_info) const
{
   if (impl()->dbg->empty())
      return false;

   // Use the ".debug_aranges" DWARF section to pinpoint the CU (Compilation Unit) that
   // corresponds to the address we want to find information about.
   const dw::AddressRangeTable& arange_table = impl()->dbg->address_ranges();

   const dw::AddressRange& arange = arange_table.find(address);

   const dw::CompileUnit& cu =
      arange.empty() ? impl()->dbg->compile_units().find(address) : arange.compile_unit();

   if (cu.empty())
      return false;

   // great, got a range that matches. let's find the CU it describes, and the DIE
   // (Debugging Information Entry) related to that CU.
   const dw::Die& die = cu.die();

   if (die.empty())
      return false;

   // Inside this CU, find the exact statement (DWARF calls it a "line") that
   // corresponds to the address we want to find information about.
   dw::LineTable line_table = die.line_table();

   dw::LineEntry entry = line_table.find(address);

   auto& src_files = die.source_files();

   location_info.file_name     = src_files[entry.src_file_id];
   location_info.function_name = die.find_function(address);
   location_info.line          = entry.lineno;
   return true;
}

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

Symbols make_symbols(const std::wstring& file_name)
{
   return Symbols{file_name};
}

Symbols make_symbols(uintptr_t file_handle, const std::wstring& image_name)
{
   return Symbols{file_handle, image_name};
}

} // namespace debug
} // namespace orion


text:
@ECHO OFF
setlocal

set GOARCH=amd64

cd %~dp0
md artifacts

echo Windows
set GOOS=windows
call go build -o artifacts\jsonmerge.exe .\cmd || goto :error

echo Linux
set GOOS=linux
call go build -o artifacts\jsonmerge .\cmd || goto :error

echo Darwin
set GOOS=darwin
call go build -o artifacts\jsonmerge_darwin .\cmd || goto :error

echo Build done
exit

:error
exit /b %errorlevel%


text:
package technology.tikal.gae.http.cache.model;

import java.math.BigInteger;
import java.security.SecureRandom;
import java.util.Date;

import org.apache.commons.lang.StringUtils;

/**
 *
 * @author Nekorp
 *
 */
public class UriEtagEntryFactory {

    private final static String DEFAULT_NAMESPACE = "DEFAULT";
    private String namespace = UriEtagEntryFactory.DEFAULT_NAMESPACE;
    private SecureRandom random;

    public UriEtagEntryFactory() {
        this.random = new SecureRandom();
    }

    public String resolveId(String uri) {
        if (StringUtils.isEmpty(namespace)) {
            throw new NullPointerException("The name space can't be null");
        }
        if (StringUtils.isEmpty(uri)) {
            throw new NullPointerException("The uri can't be null");
        }
        return namespace + ":" + uri;
    }

    public String buildNewEtagValue() {
        Date ahora = new Date();
        String r =Long.toString(ahora.getTime(), 32);
        r = r + new BigInteger(130, random).toString(32);
        return r;
    }

    public UriEtagEntry buildUriEtagEntry(String uri) {
        UriEtagEntry result = new UriEtagEntry(resolveId(uri), namespace, uri, buildNewEtagValue());
        return result;
    }

    public void setNamespace(String namespace) {
        this.namespace = namespace;
    }
}


text:
package panic_printer

import (
	"fmt"

	"github.com/cloudfoundry/cli/cf"
	"github.com/cloudfoundry/cli/cf/errors"
	"github.com/cloudfoundry/cli/cf/terminal"
)

var UI terminal.UI

func DisplayCrashDialog(err interface{}, commandArgs string, stackTrace string) {
	if err != nil && err != terminal.QuietPanic {
		switch err := err.(type) {
		case errors.Exception:
			if err.DisplayCrashDialog {
				printCrashDialog(err.Message, commandArgs, stackTrace)
			} else {
				fmt.Println(err.Message)
			}
		case error:
			printCrashDialog(err.Error(), commandArgs, stackTrace)
		case string:
			printCrashDialog(err, commandArgs, stackTrace)
		default:
			printCrashDialog("An unexpected type of error", commandArgs, stackTrace)
		}
	}
}

func CrashDialog(errorMessage string, commandArgs string, stackTrace string) string {
	formattedString := `

	Aww shucks.

	Something completely unexpected happened. This is a bug in %s.
	Please file this bug : https://github.com/cloudfoundry/cli/issues
	Tell us that you ran this command:

		%s

	using this version of the CLI:

		%s

	and that this error occurred:

		%s

	and this stack trace:

	%s
`

	return fmt.Sprintf(formattedString, cf.Name(), commandArgs, cf.Version, errorMessage, stackTrace)
}

func printCrashDialog(errorMessage string, commandArgs string, stackTrace string) {
	UI.Say(CrashDialog(errorMessage, commandArgs, stackTrace))
}


text:
#include "PID.h"
#include "Timer.h"
#include "Timing.h"
#include "ADC.h"

struct Motor {
 PID pid_s; //each motor has its own pid
 PID* pid;
 Timer timer_s; //each motor has its own timer
 Timer* timer;
 ADC* adc;
 int adc_port;
};

typedef struct Motor Motor;

void Motor_init(Motor* this, Timing* timing,
ADC* adc, int adc_port);
PID* Motor_get_pid(Motor* this);
void Motor_set_angle(Motor* this, float target_angle);
float Motor_get_angle(Motor* this);
void Motor_break(Motor* this);
void Motor_set_accuracy(Motor* this, float accuracy);

#endif //MOTOR_H


text:
"""Test RPC help output."""

from test_framework.test_framework import SyscoinTestFramework
from test_framework.util import assert_equal, assert_raises_rpc_error

import os

class HelpRpcTest(SyscoinTestFramework):
    def set_test_params(self):
        self.num_nodes = 1
        self.supports_cli = False

    def run_test(self):
        self.test_categories()
        self.dump_help()

    def test_categories(self):
        node = self.nodes[0]

        # wrong argument count
        assert_raises_rpc_error(-1, 'help', node.help, 'foo', 'bar')

        # invalid argument
        assert_raises_rpc_error(-1, 'JSON value is not a string as expected', node.help, 0)

        # help of unknown command
        assert_equal(node.help('foo'), 'help: unknown command: foo')

        # command titles
        titles = [line[3:-3] for line in node.help().splitlines() if line.startswith('==')]

        components = ['Blockchain', 'Control', 'Generating', 'Mining', 'Network', 'Rawtransactions', 'Util']

        if self.is_wallet_compiled():
            components.append('Wallet')

        if self.is_zmq_compiled():
            components.append('Zmq')

        assert_equal(titles, components)

    def dump_help(self):
        dump_dir = os.path.join(self.options.tmpdir, 'rpc_help_dump')
        os.mkdir(dump_dir)
        calls = [line.split(' ', 1)[0] for line in self.nodes[0].help().splitlines() if line and not line.startswith('==')]
        for call in calls:
            with open(os.path.join(dump_dir, call), 'w', encoding='utf-8') as f:
                # Make sure the node can generate the help at runtime without crashing
                f.write(self.nodes[0].help(call))

if __name__ == '__main__':
    HelpRpcTest().main()